babylon.max.js 3.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. var absX = Math.abs(this.x);
  1403. var absY = Math.abs(this.y);
  1404. if (absX !== absY) {
  1405. return true;
  1406. }
  1407. var absZ = Math.abs(this.z);
  1408. if (absX !== absZ) {
  1409. return true;
  1410. }
  1411. if (absY !== absZ) {
  1412. return true;
  1413. }
  1414. return false;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. // Properties
  1420. /**
  1421. * Returns the length of the Vector3 (float).
  1422. */
  1423. Vector3.prototype.length = function () {
  1424. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1425. };
  1426. /**
  1427. * Returns the squared length of the Vector3 (float).
  1428. */
  1429. Vector3.prototype.lengthSquared = function () {
  1430. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1431. };
  1432. // Methods
  1433. /**
  1434. * Normalize the current Vector3.
  1435. * Returns the updated Vector3.
  1436. */
  1437. Vector3.prototype.normalize = function () {
  1438. var len = this.length();
  1439. if (len === 0 || len === 1.0)
  1440. return this;
  1441. var num = 1.0 / len;
  1442. this.x *= num;
  1443. this.y *= num;
  1444. this.z *= num;
  1445. return this;
  1446. };
  1447. /**
  1448. * Returns a new Vector3 copied from the current Vector3.
  1449. */
  1450. Vector3.prototype.clone = function () {
  1451. return new Vector3(this.x, this.y, this.z);
  1452. };
  1453. /**
  1454. * Copies the passed vector coordinates to the current Vector3 ones.
  1455. * Returns the updated Vector3.
  1456. */
  1457. Vector3.prototype.copyFrom = function (source) {
  1458. this.x = source.x;
  1459. this.y = source.y;
  1460. this.z = source.z;
  1461. return this;
  1462. };
  1463. /**
  1464. * Copies the passed floats to the current Vector3 coordinates.
  1465. * Returns the updated Vector3.
  1466. */
  1467. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1468. this.x = x;
  1469. this.y = y;
  1470. this.z = z;
  1471. return this;
  1472. };
  1473. /**
  1474. * Copies the passed floats to the current Vector3 coordinates.
  1475. * Returns the updated Vector3.
  1476. */
  1477. Vector3.prototype.set = function (x, y, z) {
  1478. return this.copyFromFloats(x, y, z);
  1479. };
  1480. // Statics
  1481. /**
  1482. *
  1483. */
  1484. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1485. var d0 = Vector3.Dot(vector0, axis) - size;
  1486. var d1 = Vector3.Dot(vector1, axis) - size;
  1487. var s = d0 / (d0 - d1);
  1488. return s;
  1489. };
  1490. /**
  1491. * Returns a new Vector3 set from the index "offset" of the passed array.
  1492. */
  1493. Vector3.FromArray = function (array, offset) {
  1494. if (!offset) {
  1495. offset = 0;
  1496. }
  1497. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1498. };
  1499. /**
  1500. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1501. * This function is deprecated. Use FromArray instead.
  1502. */
  1503. Vector3.FromFloatArray = function (array, offset) {
  1504. return Vector3.FromArray(array, offset);
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1508. */
  1509. Vector3.FromArrayToRef = function (array, offset, result) {
  1510. result.x = array[offset];
  1511. result.y = array[offset + 1];
  1512. result.z = array[offset + 2];
  1513. };
  1514. /**
  1515. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1516. * This function is deprecated. Use FromArrayToRef instead.
  1517. */
  1518. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1519. return Vector3.FromArrayToRef(array, offset, result);
  1520. };
  1521. /**
  1522. * Sets the passed vector "result" with the passed floats.
  1523. */
  1524. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1525. result.x = x;
  1526. result.y = y;
  1527. result.z = z;
  1528. };
  1529. /**
  1530. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1531. */
  1532. Vector3.Zero = function () {
  1533. return new Vector3(0.0, 0.0, 0.0);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1537. */
  1538. Vector3.One = function () {
  1539. return new Vector3(1.0, 1.0, 1.0);
  1540. };
  1541. /**
  1542. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1543. */
  1544. Vector3.Up = function () {
  1545. return new Vector3(0.0, 1.0, 0.0);
  1546. };
  1547. /**
  1548. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1549. */
  1550. Vector3.Forward = function () {
  1551. return new Vector3(0.0, 0.0, 1.0);
  1552. };
  1553. /**
  1554. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1555. */
  1556. Vector3.Right = function () {
  1557. return new Vector3(1.0, 0.0, 0.0);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1561. */
  1562. Vector3.Left = function () {
  1563. return new Vector3(-1.0, 0.0, 0.0);
  1564. };
  1565. /**
  1566. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1567. * This method computes tranformed coordinates only, not transformed direction vectors.
  1568. */
  1569. Vector3.TransformCoordinates = function (vector, transformation) {
  1570. var result = Vector3.Zero();
  1571. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1572. return result;
  1573. };
  1574. /**
  1575. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1576. * This method computes tranformed coordinates only, not transformed direction vectors.
  1577. */
  1578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1583. result.x = x / w;
  1584. result.y = y / w;
  1585. result.z = z / w;
  1586. };
  1587. /**
  1588. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1589. * This method computes tranformed coordinates only, not transformed direction vectors.
  1590. */
  1591. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1592. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1593. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1594. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1595. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1596. result.x = rx / rw;
  1597. result.y = ry / rw;
  1598. result.z = rz / rw;
  1599. };
  1600. /**
  1601. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1602. * This methods computes transformed normalized direction vectors only.
  1603. */
  1604. Vector3.TransformNormal = function (vector, transformation) {
  1605. var result = Vector3.Zero();
  1606. Vector3.TransformNormalToRef(vector, transformation, result);
  1607. return result;
  1608. };
  1609. /**
  1610. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1611. * This methods computes transformed normalized direction vectors only.
  1612. */
  1613. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1614. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1615. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1616. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1617. result.x = x;
  1618. result.y = y;
  1619. result.z = z;
  1620. };
  1621. /**
  1622. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1623. * This methods computes transformed normalized direction vectors only.
  1624. */
  1625. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1626. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1627. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1628. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1629. };
  1630. /**
  1631. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1632. */
  1633. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1634. var squared = amount * amount;
  1635. var cubed = amount * squared;
  1636. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1637. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1638. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1639. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1640. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1641. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1642. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1643. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1644. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1645. return new Vector3(x, y, z);
  1646. };
  1647. /**
  1648. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1649. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1650. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1651. */
  1652. Vector3.Clamp = function (value, min, max) {
  1653. var x = value.x;
  1654. x = (x > max.x) ? max.x : x;
  1655. x = (x < min.x) ? min.x : x;
  1656. var y = value.y;
  1657. y = (y > max.y) ? max.y : y;
  1658. y = (y < min.y) ? min.y : y;
  1659. var z = value.z;
  1660. z = (z > max.z) ? max.z : z;
  1661. z = (z < min.z) ? min.z : z;
  1662. return new Vector3(x, y, z);
  1663. };
  1664. /**
  1665. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1666. */
  1667. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1668. var squared = amount * amount;
  1669. var cubed = amount * squared;
  1670. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1671. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1672. var part3 = (cubed - (2.0 * squared)) + amount;
  1673. var part4 = cubed - squared;
  1674. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1675. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1676. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1677. return new Vector3(x, y, z);
  1678. };
  1679. /**
  1680. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1681. */
  1682. Vector3.Lerp = function (start, end, amount) {
  1683. var result = new Vector3(0, 0, 0);
  1684. Vector3.LerpToRef(start, end, amount, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1689. */
  1690. Vector3.LerpToRef = function (start, end, amount, result) {
  1691. result.x = start.x + ((end.x - start.x) * amount);
  1692. result.y = start.y + ((end.y - start.y) * amount);
  1693. result.z = start.z + ((end.z - start.z) * amount);
  1694. };
  1695. /**
  1696. * Returns the dot product (float) between the vectors "left" and "right".
  1697. */
  1698. Vector3.Dot = function (left, right) {
  1699. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1700. };
  1701. /**
  1702. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1703. * The cross product is then orthogonal to both "left" and "right".
  1704. */
  1705. Vector3.Cross = function (left, right) {
  1706. var result = Vector3.Zero();
  1707. Vector3.CrossToRef(left, right, result);
  1708. return result;
  1709. };
  1710. /**
  1711. * Sets the passed vector "result" with the cross product of "left" and "right".
  1712. * The cross product is then orthogonal to both "left" and "right".
  1713. */
  1714. Vector3.CrossToRef = function (left, right, result) {
  1715. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1716. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1717. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1718. result.copyFrom(MathTmp.Vector3[0]);
  1719. };
  1720. /**
  1721. * Returns a new Vector3 as the normalization of the passed vector.
  1722. */
  1723. Vector3.Normalize = function (vector) {
  1724. var result = Vector3.Zero();
  1725. Vector3.NormalizeToRef(vector, result);
  1726. return result;
  1727. };
  1728. /**
  1729. * Sets the passed vector "result" with the normalization of the passed first vector.
  1730. */
  1731. Vector3.NormalizeToRef = function (vector, result) {
  1732. result.copyFrom(vector);
  1733. result.normalize();
  1734. };
  1735. Vector3.Project = function (vector, world, transform, viewport) {
  1736. var cw = viewport.width;
  1737. var ch = viewport.height;
  1738. var cx = viewport.x;
  1739. var cy = viewport.y;
  1740. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1741. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1742. var matrix = MathTmp.Matrix[0];
  1743. world.multiplyToRef(transform, matrix);
  1744. matrix.multiplyToRef(viewportMatrix, matrix);
  1745. return Vector3.TransformCoordinates(vector, matrix);
  1746. };
  1747. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1748. var matrix = MathTmp.Matrix[0];
  1749. world.multiplyToRef(transform, matrix);
  1750. matrix.invert();
  1751. source.x = source.x / viewportWidth * 2 - 1;
  1752. source.y = -(source.y / viewportHeight * 2 - 1);
  1753. var vector = Vector3.TransformCoordinates(source, matrix);
  1754. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1755. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1756. vector = vector.scale(1.0 / num);
  1757. }
  1758. return vector;
  1759. };
  1760. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1761. var matrix = MathTmp.Matrix[0];
  1762. world.multiplyToRef(view, matrix);
  1763. matrix.multiplyToRef(projection, matrix);
  1764. matrix.invert();
  1765. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1766. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1767. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1768. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1769. vector = vector.scale(1.0 / num);
  1770. }
  1771. return vector;
  1772. };
  1773. Vector3.Minimize = function (left, right) {
  1774. var min = left.clone();
  1775. min.MinimizeInPlace(right);
  1776. return min;
  1777. };
  1778. Vector3.Maximize = function (left, right) {
  1779. var max = left.clone();
  1780. max.MaximizeInPlace(right);
  1781. return max;
  1782. };
  1783. /**
  1784. * Returns the distance (float) between the vectors "value1" and "value2".
  1785. */
  1786. Vector3.Distance = function (value1, value2) {
  1787. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1788. };
  1789. /**
  1790. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1791. */
  1792. Vector3.DistanceSquared = function (value1, value2) {
  1793. var x = value1.x - value2.x;
  1794. var y = value1.y - value2.y;
  1795. var z = value1.z - value2.z;
  1796. return (x * x) + (y * y) + (z * z);
  1797. };
  1798. /**
  1799. * Returns a new Vector3 located at the center between "value1" and "value2".
  1800. */
  1801. Vector3.Center = function (value1, value2) {
  1802. var center = value1.add(value2);
  1803. center.scaleInPlace(0.5);
  1804. return center;
  1805. };
  1806. /**
  1807. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1808. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1809. * to something in order to rotate it from its local system to the given target system.
  1810. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1811. * Returns a new Vector3.
  1812. */
  1813. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1814. var rotation = Vector3.Zero();
  1815. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1816. return rotation;
  1817. };
  1818. /**
  1819. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1820. */
  1821. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1822. var quat = MathTmp.Quaternion[0];
  1823. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1824. quat.toEulerAnglesToRef(ref);
  1825. };
  1826. return Vector3;
  1827. }());
  1828. BABYLON.Vector3 = Vector3;
  1829. //Vector4 class created for EulerAngle class conversion to Quaternion
  1830. var Vector4 = /** @class */ (function () {
  1831. /**
  1832. * Creates a Vector4 object from the passed floats.
  1833. */
  1834. function Vector4(x, y, z, w) {
  1835. this.x = x;
  1836. this.y = y;
  1837. this.z = z;
  1838. this.w = w;
  1839. }
  1840. /**
  1841. * Returns the string with the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.toString = function () {
  1844. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1845. };
  1846. /**
  1847. * Returns the string "Vector4".
  1848. */
  1849. Vector4.prototype.getClassName = function () {
  1850. return "Vector4";
  1851. };
  1852. /**
  1853. * Returns the Vector4 hash code.
  1854. */
  1855. Vector4.prototype.getHashCode = function () {
  1856. var hash = this.x || 0;
  1857. hash = (hash * 397) ^ (this.y || 0);
  1858. hash = (hash * 397) ^ (this.z || 0);
  1859. hash = (hash * 397) ^ (this.w || 0);
  1860. return hash;
  1861. };
  1862. // Operators
  1863. /**
  1864. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1865. */
  1866. Vector4.prototype.asArray = function () {
  1867. var result = new Array();
  1868. this.toArray(result, 0);
  1869. return result;
  1870. };
  1871. /**
  1872. * Populates the passed array from the passed index with the Vector4 coordinates.
  1873. * Returns the Vector4.
  1874. */
  1875. Vector4.prototype.toArray = function (array, index) {
  1876. if (index === undefined) {
  1877. index = 0;
  1878. }
  1879. array[index] = this.x;
  1880. array[index + 1] = this.y;
  1881. array[index + 2] = this.z;
  1882. array[index + 3] = this.w;
  1883. return this;
  1884. };
  1885. /**
  1886. * Adds the passed vector to the current Vector4.
  1887. * Returns the updated Vector4.
  1888. */
  1889. Vector4.prototype.addInPlace = function (otherVector) {
  1890. this.x += otherVector.x;
  1891. this.y += otherVector.y;
  1892. this.z += otherVector.z;
  1893. this.w += otherVector.w;
  1894. return this;
  1895. };
  1896. /**
  1897. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1898. */
  1899. Vector4.prototype.add = function (otherVector) {
  1900. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1901. };
  1902. /**
  1903. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1904. * Returns the current Vector4.
  1905. */
  1906. Vector4.prototype.addToRef = function (otherVector, result) {
  1907. result.x = this.x + otherVector.x;
  1908. result.y = this.y + otherVector.y;
  1909. result.z = this.z + otherVector.z;
  1910. result.w = this.w + otherVector.w;
  1911. return this;
  1912. };
  1913. /**
  1914. * Subtract in place the passed vector from the current Vector4.
  1915. * Returns the updated Vector4.
  1916. */
  1917. Vector4.prototype.subtractInPlace = function (otherVector) {
  1918. this.x -= otherVector.x;
  1919. this.y -= otherVector.y;
  1920. this.z -= otherVector.z;
  1921. this.w -= otherVector.w;
  1922. return this;
  1923. };
  1924. /**
  1925. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1926. */
  1927. Vector4.prototype.subtract = function (otherVector) {
  1928. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1929. };
  1930. /**
  1931. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1932. * Returns the current Vector4.
  1933. */
  1934. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1935. result.x = this.x - otherVector.x;
  1936. result.y = this.y - otherVector.y;
  1937. result.z = this.z - otherVector.z;
  1938. result.w = this.w - otherVector.w;
  1939. return this;
  1940. };
  1941. /**
  1942. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1943. */
  1944. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1945. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1946. };
  1947. /**
  1948. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1949. * Returns the current Vector4.
  1950. */
  1951. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1952. result.x = this.x - x;
  1953. result.y = this.y - y;
  1954. result.z = this.z - z;
  1955. result.w = this.w - w;
  1956. return this;
  1957. };
  1958. /**
  1959. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1960. */
  1961. Vector4.prototype.negate = function () {
  1962. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1963. };
  1964. /**
  1965. * Multiplies the current Vector4 coordinates by scale (float).
  1966. * Returns the updated Vector4.
  1967. */
  1968. Vector4.prototype.scaleInPlace = function (scale) {
  1969. this.x *= scale;
  1970. this.y *= scale;
  1971. this.z *= scale;
  1972. this.w *= scale;
  1973. return this;
  1974. };
  1975. /**
  1976. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1977. */
  1978. Vector4.prototype.scale = function (scale) {
  1979. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1980. };
  1981. /**
  1982. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1983. * Returns the current Vector4.
  1984. */
  1985. Vector4.prototype.scaleToRef = function (scale, result) {
  1986. result.x = this.x * scale;
  1987. result.y = this.y * scale;
  1988. result.z = this.z * scale;
  1989. result.w = this.w * scale;
  1990. return this;
  1991. };
  1992. /**
  1993. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1994. */
  1995. Vector4.prototype.equals = function (otherVector) {
  1996. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1997. };
  1998. /**
  1999. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2000. */
  2001. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2002. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2003. return otherVector
  2004. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2005. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2006. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2007. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2008. };
  2009. /**
  2010. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2011. */
  2012. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2013. return this.x === x && this.y === y && this.z === z && this.w === w;
  2014. };
  2015. /**
  2016. * Multiplies in place the current Vector4 by the passed one.
  2017. * Returns the updated Vector4.
  2018. */
  2019. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2020. this.x *= otherVector.x;
  2021. this.y *= otherVector.y;
  2022. this.z *= otherVector.z;
  2023. this.w *= otherVector.w;
  2024. return this;
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2028. */
  2029. Vector4.prototype.multiply = function (otherVector) {
  2030. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2037. result.x = this.x * otherVector.x;
  2038. result.y = this.y * otherVector.y;
  2039. result.z = this.z * otherVector.z;
  2040. result.w = this.w * otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2045. */
  2046. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2047. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2048. };
  2049. /**
  2050. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2051. */
  2052. Vector4.prototype.divide = function (otherVector) {
  2053. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2054. };
  2055. /**
  2056. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2057. * Returns the current Vector4.
  2058. */
  2059. Vector4.prototype.divideToRef = function (otherVector, result) {
  2060. result.x = this.x / otherVector.x;
  2061. result.y = this.y / otherVector.y;
  2062. result.z = this.z / otherVector.z;
  2063. result.w = this.w / otherVector.w;
  2064. return this;
  2065. };
  2066. /**
  2067. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2068. */
  2069. Vector4.prototype.MinimizeInPlace = function (other) {
  2070. if (other.x < this.x)
  2071. this.x = other.x;
  2072. if (other.y < this.y)
  2073. this.y = other.y;
  2074. if (other.z < this.z)
  2075. this.z = other.z;
  2076. if (other.w < this.w)
  2077. this.w = other.w;
  2078. return this;
  2079. };
  2080. /**
  2081. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2082. */
  2083. Vector4.prototype.MaximizeInPlace = function (other) {
  2084. if (other.x > this.x)
  2085. this.x = other.x;
  2086. if (other.y > this.y)
  2087. this.y = other.y;
  2088. if (other.z > this.z)
  2089. this.z = other.z;
  2090. if (other.w > this.w)
  2091. this.w = other.w;
  2092. return this;
  2093. };
  2094. // Properties
  2095. /**
  2096. * Returns the Vector4 length (float).
  2097. */
  2098. Vector4.prototype.length = function () {
  2099. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2100. };
  2101. /**
  2102. * Returns the Vector4 squared length (float).
  2103. */
  2104. Vector4.prototype.lengthSquared = function () {
  2105. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2106. };
  2107. // Methods
  2108. /**
  2109. * Normalizes in place the Vector4.
  2110. * Returns the updated Vector4.
  2111. */
  2112. Vector4.prototype.normalize = function () {
  2113. var len = this.length();
  2114. if (len === 0)
  2115. return this;
  2116. var num = 1.0 / len;
  2117. this.x *= num;
  2118. this.y *= num;
  2119. this.z *= num;
  2120. this.w *= num;
  2121. return this;
  2122. };
  2123. /**
  2124. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2125. */
  2126. Vector4.prototype.toVector3 = function () {
  2127. return new Vector3(this.x, this.y, this.z);
  2128. };
  2129. /**
  2130. * Returns a new Vector4 copied from the current one.
  2131. */
  2132. Vector4.prototype.clone = function () {
  2133. return new Vector4(this.x, this.y, this.z, this.w);
  2134. };
  2135. /**
  2136. * Updates the current Vector4 with the passed one coordinates.
  2137. * Returns the updated Vector4.
  2138. */
  2139. Vector4.prototype.copyFrom = function (source) {
  2140. this.x = source.x;
  2141. this.y = source.y;
  2142. this.z = source.z;
  2143. this.w = source.w;
  2144. return this;
  2145. };
  2146. /**
  2147. * Updates the current Vector4 coordinates with the passed floats.
  2148. * Returns the updated Vector4.
  2149. */
  2150. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2151. this.x = x;
  2152. this.y = y;
  2153. this.z = z;
  2154. this.w = w;
  2155. return this;
  2156. };
  2157. /**
  2158. * Updates the current Vector4 coordinates with the passed floats.
  2159. * Returns the updated Vector4.
  2160. */
  2161. Vector4.prototype.set = function (x, y, z, w) {
  2162. return this.copyFromFloats(x, y, z, w);
  2163. };
  2164. // Statics
  2165. /**
  2166. * Returns a new Vector4 set from the starting index of the passed array.
  2167. */
  2168. Vector4.FromArray = function (array, offset) {
  2169. if (!offset) {
  2170. offset = 0;
  2171. }
  2172. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2173. };
  2174. /**
  2175. * Updates the passed vector "result" from the starting index of the passed array.
  2176. */
  2177. Vector4.FromArrayToRef = function (array, offset, result) {
  2178. result.x = array[offset];
  2179. result.y = array[offset + 1];
  2180. result.z = array[offset + 2];
  2181. result.w = array[offset + 3];
  2182. };
  2183. /**
  2184. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2185. */
  2186. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2187. Vector4.FromArrayToRef(array, offset, result);
  2188. };
  2189. /**
  2190. * Updates the passed vector "result" coordinates from the passed floats.
  2191. */
  2192. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2193. result.x = x;
  2194. result.y = y;
  2195. result.z = z;
  2196. result.w = w;
  2197. };
  2198. /**
  2199. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2200. */
  2201. Vector4.Zero = function () {
  2202. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2203. };
  2204. /**
  2205. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2206. */
  2207. Vector4.One = function () {
  2208. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2209. };
  2210. /**
  2211. * Returns a new normalized Vector4 from the passed one.
  2212. */
  2213. Vector4.Normalize = function (vector) {
  2214. var result = Vector4.Zero();
  2215. Vector4.NormalizeToRef(vector, result);
  2216. return result;
  2217. };
  2218. /**
  2219. * Updates the passed vector "result" from the normalization of the passed one.
  2220. */
  2221. Vector4.NormalizeToRef = function (vector, result) {
  2222. result.copyFrom(vector);
  2223. result.normalize();
  2224. };
  2225. Vector4.Minimize = function (left, right) {
  2226. var min = left.clone();
  2227. min.MinimizeInPlace(right);
  2228. return min;
  2229. };
  2230. Vector4.Maximize = function (left, right) {
  2231. var max = left.clone();
  2232. max.MaximizeInPlace(right);
  2233. return max;
  2234. };
  2235. /**
  2236. * Returns the distance (float) between the vectors "value1" and "value2".
  2237. */
  2238. Vector4.Distance = function (value1, value2) {
  2239. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2240. };
  2241. /**
  2242. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2243. */
  2244. Vector4.DistanceSquared = function (value1, value2) {
  2245. var x = value1.x - value2.x;
  2246. var y = value1.y - value2.y;
  2247. var z = value1.z - value2.z;
  2248. var w = value1.w - value2.w;
  2249. return (x * x) + (y * y) + (z * z) + (w * w);
  2250. };
  2251. /**
  2252. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2253. */
  2254. Vector4.Center = function (value1, value2) {
  2255. var center = value1.add(value2);
  2256. center.scaleInPlace(0.5);
  2257. return center;
  2258. };
  2259. /**
  2260. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2261. * This methods computes transformed normalized direction vectors only.
  2262. */
  2263. Vector4.TransformNormal = function (vector, transformation) {
  2264. var result = Vector4.Zero();
  2265. Vector4.TransformNormalToRef(vector, transformation, result);
  2266. return result;
  2267. };
  2268. /**
  2269. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2270. * This methods computes transformed normalized direction vectors only.
  2271. */
  2272. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2273. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2274. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2275. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2276. result.x = x;
  2277. result.y = y;
  2278. result.z = z;
  2279. result.w = vector.w;
  2280. };
  2281. /**
  2282. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2283. * This methods computes transformed normalized direction vectors only.
  2284. */
  2285. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2286. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2287. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2288. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2289. result.w = w;
  2290. };
  2291. return Vector4;
  2292. }());
  2293. BABYLON.Vector4 = Vector4;
  2294. var Size = /** @class */ (function () {
  2295. /**
  2296. * Creates a Size object from the passed width and height (floats).
  2297. */
  2298. function Size(width, height) {
  2299. this.width = width;
  2300. this.height = height;
  2301. }
  2302. // Returns a string with the Size width and height.
  2303. Size.prototype.toString = function () {
  2304. return "{W: " + this.width + ", H: " + this.height + "}";
  2305. };
  2306. /**
  2307. * Returns the string "Size"
  2308. */
  2309. Size.prototype.getClassName = function () {
  2310. return "Size";
  2311. };
  2312. /**
  2313. * Returns the Size hash code.
  2314. */
  2315. Size.prototype.getHashCode = function () {
  2316. var hash = this.width || 0;
  2317. hash = (hash * 397) ^ (this.height || 0);
  2318. return hash;
  2319. };
  2320. /**
  2321. * Updates the current size from the passed one.
  2322. * Returns the updated Size.
  2323. */
  2324. Size.prototype.copyFrom = function (src) {
  2325. this.width = src.width;
  2326. this.height = src.height;
  2327. };
  2328. /**
  2329. * Updates in place the current Size from the passed floats.
  2330. * Returns the updated Size.
  2331. */
  2332. Size.prototype.copyFromFloats = function (width, height) {
  2333. this.width = width;
  2334. this.height = height;
  2335. return this;
  2336. };
  2337. /**
  2338. * Updates in place the current Size from the passed floats.
  2339. * Returns the updated Size.
  2340. */
  2341. Size.prototype.set = function (width, height) {
  2342. return this.copyFromFloats(width, height);
  2343. };
  2344. /**
  2345. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2346. */
  2347. Size.prototype.multiplyByFloats = function (w, h) {
  2348. return new Size(this.width * w, this.height * h);
  2349. };
  2350. /**
  2351. * Returns a new Size copied from the passed one.
  2352. */
  2353. Size.prototype.clone = function () {
  2354. return new Size(this.width, this.height);
  2355. };
  2356. /**
  2357. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2358. */
  2359. Size.prototype.equals = function (other) {
  2360. if (!other) {
  2361. return false;
  2362. }
  2363. return (this.width === other.width) && (this.height === other.height);
  2364. };
  2365. Object.defineProperty(Size.prototype, "surface", {
  2366. /**
  2367. * Returns the surface of the Size : width * height (float).
  2368. */
  2369. get: function () {
  2370. return this.width * this.height;
  2371. },
  2372. enumerable: true,
  2373. configurable: true
  2374. });
  2375. /**
  2376. * Returns a new Size set to (0.0, 0.0)
  2377. */
  2378. Size.Zero = function () {
  2379. return new Size(0.0, 0.0);
  2380. };
  2381. /**
  2382. * Returns a new Size set as the addition result of the current Size and the passed one.
  2383. */
  2384. Size.prototype.add = function (otherSize) {
  2385. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2386. return r;
  2387. };
  2388. /**
  2389. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2390. */
  2391. Size.prototype.subtract = function (otherSize) {
  2392. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2393. return r;
  2394. };
  2395. /**
  2396. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2397. */
  2398. Size.Lerp = function (start, end, amount) {
  2399. var w = start.width + ((end.width - start.width) * amount);
  2400. var h = start.height + ((end.height - start.height) * amount);
  2401. return new Size(w, h);
  2402. };
  2403. return Size;
  2404. }());
  2405. BABYLON.Size = Size;
  2406. var Quaternion = /** @class */ (function () {
  2407. /**
  2408. * Creates a new Quaternion from the passed floats.
  2409. */
  2410. function Quaternion(x, y, z, w) {
  2411. if (x === void 0) { x = 0.0; }
  2412. if (y === void 0) { y = 0.0; }
  2413. if (z === void 0) { z = 0.0; }
  2414. if (w === void 0) { w = 1.0; }
  2415. this.x = x;
  2416. this.y = y;
  2417. this.z = z;
  2418. this.w = w;
  2419. }
  2420. /**
  2421. * Returns a string with the Quaternion coordinates.
  2422. */
  2423. Quaternion.prototype.toString = function () {
  2424. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2425. };
  2426. /**
  2427. * Returns the string "Quaternion".
  2428. */
  2429. Quaternion.prototype.getClassName = function () {
  2430. return "Quaternion";
  2431. };
  2432. /**
  2433. * Returns the Quaternion hash code.
  2434. */
  2435. Quaternion.prototype.getHashCode = function () {
  2436. var hash = this.x || 0;
  2437. hash = (hash * 397) ^ (this.y || 0);
  2438. hash = (hash * 397) ^ (this.z || 0);
  2439. hash = (hash * 397) ^ (this.w || 0);
  2440. return hash;
  2441. };
  2442. /**
  2443. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2444. */
  2445. Quaternion.prototype.asArray = function () {
  2446. return [this.x, this.y, this.z, this.w];
  2447. };
  2448. /**
  2449. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2450. */
  2451. Quaternion.prototype.equals = function (otherQuaternion) {
  2452. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2453. };
  2454. /**
  2455. * Returns a new Quaternion copied from the current one.
  2456. */
  2457. Quaternion.prototype.clone = function () {
  2458. return new Quaternion(this.x, this.y, this.z, this.w);
  2459. };
  2460. /**
  2461. * Updates the current Quaternion from the passed one coordinates.
  2462. * Returns the updated Quaterion.
  2463. */
  2464. Quaternion.prototype.copyFrom = function (other) {
  2465. this.x = other.x;
  2466. this.y = other.y;
  2467. this.z = other.z;
  2468. this.w = other.w;
  2469. return this;
  2470. };
  2471. /**
  2472. * Updates the current Quaternion from the passed float coordinates.
  2473. * Returns the updated Quaterion.
  2474. */
  2475. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2476. this.x = x;
  2477. this.y = y;
  2478. this.z = z;
  2479. this.w = w;
  2480. return this;
  2481. };
  2482. /**
  2483. * Updates the current Quaternion from the passed float coordinates.
  2484. * Returns the updated Quaterion.
  2485. */
  2486. Quaternion.prototype.set = function (x, y, z, w) {
  2487. return this.copyFromFloats(x, y, z, w);
  2488. };
  2489. /**
  2490. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2491. */
  2492. Quaternion.prototype.add = function (other) {
  2493. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2494. };
  2495. /**
  2496. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2497. */
  2498. Quaternion.prototype.subtract = function (other) {
  2499. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2500. };
  2501. /**
  2502. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2503. */
  2504. Quaternion.prototype.scale = function (value) {
  2505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2506. };
  2507. /**
  2508. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2509. */
  2510. Quaternion.prototype.multiply = function (q1) {
  2511. var result = new Quaternion(0, 0, 0, 1.0);
  2512. this.multiplyToRef(q1, result);
  2513. return result;
  2514. };
  2515. /**
  2516. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2517. * Returns the current Quaternion.
  2518. */
  2519. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2520. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2521. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2522. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2523. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2524. result.copyFromFloats(x, y, z, w);
  2525. return this;
  2526. };
  2527. /**
  2528. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2529. * Returns the updated Quaternion.
  2530. */
  2531. Quaternion.prototype.multiplyInPlace = function (q1) {
  2532. this.multiplyToRef(q1, this);
  2533. return this;
  2534. };
  2535. /**
  2536. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2537. * Returns the current Quaternion.
  2538. */
  2539. Quaternion.prototype.conjugateToRef = function (ref) {
  2540. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2541. return this;
  2542. };
  2543. /**
  2544. * Conjugates in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.conjugateInPlace = function () {
  2548. this.x *= -1;
  2549. this.y *= -1;
  2550. this.z *= -1;
  2551. return this;
  2552. };
  2553. /**
  2554. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2555. */
  2556. Quaternion.prototype.conjugate = function () {
  2557. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2558. return result;
  2559. };
  2560. /**
  2561. * Returns the Quaternion length (float).
  2562. */
  2563. Quaternion.prototype.length = function () {
  2564. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2565. };
  2566. /**
  2567. * Normalize in place the current Quaternion.
  2568. * Returns the updated Quaternion.
  2569. */
  2570. Quaternion.prototype.normalize = function () {
  2571. var length = 1.0 / this.length();
  2572. this.x *= length;
  2573. this.y *= length;
  2574. this.z *= length;
  2575. this.w *= length;
  2576. return this;
  2577. };
  2578. /**
  2579. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2580. */
  2581. Quaternion.prototype.toEulerAngles = function (order) {
  2582. if (order === void 0) { order = "YZX"; }
  2583. var result = Vector3.Zero();
  2584. this.toEulerAnglesToRef(result, order);
  2585. return result;
  2586. };
  2587. /**
  2588. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2589. * Returns the current Quaternion.
  2590. */
  2591. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2592. if (order === void 0) { order = "YZX"; }
  2593. var qz = this.z;
  2594. var qx = this.x;
  2595. var qy = this.y;
  2596. var qw = this.w;
  2597. var sqw = qw * qw;
  2598. var sqz = qz * qz;
  2599. var sqx = qx * qx;
  2600. var sqy = qy * qy;
  2601. var zAxisY = qy * qz - qx * qw;
  2602. var limit = .4999999;
  2603. if (zAxisY < -limit) {
  2604. result.y = 2 * Math.atan2(qy, qw);
  2605. result.x = Math.PI / 2;
  2606. result.z = 0;
  2607. }
  2608. else if (zAxisY > limit) {
  2609. result.y = 2 * Math.atan2(qy, qw);
  2610. result.x = -Math.PI / 2;
  2611. result.z = 0;
  2612. }
  2613. else {
  2614. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2615. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2616. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2617. }
  2618. return this;
  2619. };
  2620. /**
  2621. * Updates the passed rotation matrix with the current Quaternion values.
  2622. * Returns the current Quaternion.
  2623. */
  2624. Quaternion.prototype.toRotationMatrix = function (result) {
  2625. var xx = this.x * this.x;
  2626. var yy = this.y * this.y;
  2627. var zz = this.z * this.z;
  2628. var xy = this.x * this.y;
  2629. var zw = this.z * this.w;
  2630. var zx = this.z * this.x;
  2631. var yw = this.y * this.w;
  2632. var yz = this.y * this.z;
  2633. var xw = this.x * this.w;
  2634. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2635. result.m[1] = 2.0 * (xy + zw);
  2636. result.m[2] = 2.0 * (zx - yw);
  2637. result.m[3] = 0;
  2638. result.m[4] = 2.0 * (xy - zw);
  2639. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2640. result.m[6] = 2.0 * (yz + xw);
  2641. result.m[7] = 0;
  2642. result.m[8] = 2.0 * (zx + yw);
  2643. result.m[9] = 2.0 * (yz - xw);
  2644. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2645. result.m[11] = 0;
  2646. result.m[12] = 0;
  2647. result.m[13] = 0;
  2648. result.m[14] = 0;
  2649. result.m[15] = 1.0;
  2650. result._markAsUpdated();
  2651. return this;
  2652. };
  2653. /**
  2654. * Updates the current Quaternion from the passed rotation matrix values.
  2655. * Returns the updated Quaternion.
  2656. */
  2657. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2658. Quaternion.FromRotationMatrixToRef(matrix, this);
  2659. return this;
  2660. };
  2661. // Statics
  2662. /**
  2663. * Returns a new Quaternion set from the passed rotation matrix values.
  2664. */
  2665. Quaternion.FromRotationMatrix = function (matrix) {
  2666. var result = new Quaternion();
  2667. Quaternion.FromRotationMatrixToRef(matrix, result);
  2668. return result;
  2669. };
  2670. /**
  2671. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2672. */
  2673. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2674. var data = matrix.m;
  2675. var m11 = data[0], m12 = data[4], m13 = data[8];
  2676. var m21 = data[1], m22 = data[5], m23 = data[9];
  2677. var m31 = data[2], m32 = data[6], m33 = data[10];
  2678. var trace = m11 + m22 + m33;
  2679. var s;
  2680. if (trace > 0) {
  2681. s = 0.5 / Math.sqrt(trace + 1.0);
  2682. result.w = 0.25 / s;
  2683. result.x = (m32 - m23) * s;
  2684. result.y = (m13 - m31) * s;
  2685. result.z = (m21 - m12) * s;
  2686. }
  2687. else if (m11 > m22 && m11 > m33) {
  2688. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2689. result.w = (m32 - m23) / s;
  2690. result.x = 0.25 * s;
  2691. result.y = (m12 + m21) / s;
  2692. result.z = (m13 + m31) / s;
  2693. }
  2694. else if (m22 > m33) {
  2695. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2696. result.w = (m13 - m31) / s;
  2697. result.x = (m12 + m21) / s;
  2698. result.y = 0.25 * s;
  2699. result.z = (m23 + m32) / s;
  2700. }
  2701. else {
  2702. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2703. result.w = (m21 - m12) / s;
  2704. result.x = (m13 + m31) / s;
  2705. result.y = (m23 + m32) / s;
  2706. result.z = 0.25 * s;
  2707. }
  2708. };
  2709. /**
  2710. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2711. */
  2712. Quaternion.Zero = function () {
  2713. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2714. };
  2715. /**
  2716. * Returns a new Quaternion as the inverted current Quaternion.
  2717. */
  2718. Quaternion.Inverse = function (q) {
  2719. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2720. };
  2721. /**
  2722. * Returns the identity Quaternion.
  2723. */
  2724. Quaternion.Identity = function () {
  2725. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2726. };
  2727. Quaternion.IsIdentity = function (quaternion) {
  2728. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2729. };
  2730. /**
  2731. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2732. */
  2733. Quaternion.RotationAxis = function (axis, angle) {
  2734. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2735. };
  2736. /**
  2737. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2738. */
  2739. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2740. var sin = Math.sin(angle / 2);
  2741. axis.normalize();
  2742. result.w = Math.cos(angle / 2);
  2743. result.x = axis.x * sin;
  2744. result.y = axis.y * sin;
  2745. result.z = axis.z * sin;
  2746. return result;
  2747. };
  2748. /**
  2749. * Retuns a new Quaternion set from the starting index of the passed array.
  2750. */
  2751. Quaternion.FromArray = function (array, offset) {
  2752. if (!offset) {
  2753. offset = 0;
  2754. }
  2755. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2756. };
  2757. /**
  2758. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2759. */
  2760. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2761. var q = new Quaternion();
  2762. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2763. return q;
  2764. };
  2765. /**
  2766. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2767. */
  2768. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2769. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2770. var halfRoll = roll * 0.5;
  2771. var halfPitch = pitch * 0.5;
  2772. var halfYaw = yaw * 0.5;
  2773. var sinRoll = Math.sin(halfRoll);
  2774. var cosRoll = Math.cos(halfRoll);
  2775. var sinPitch = Math.sin(halfPitch);
  2776. var cosPitch = Math.cos(halfPitch);
  2777. var sinYaw = Math.sin(halfYaw);
  2778. var cosYaw = Math.cos(halfYaw);
  2779. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2780. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2781. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2782. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2783. };
  2784. /**
  2785. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2786. */
  2787. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2788. var result = new Quaternion();
  2789. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2790. return result;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2794. */
  2795. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2796. // Produces a quaternion from Euler angles in the z-x-z orientation
  2797. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2798. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2799. var halfBeta = beta * 0.5;
  2800. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2801. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2802. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2803. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2804. };
  2805. /**
  2806. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2807. * cf to Vector3.RotationFromAxis() documentation.
  2808. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2809. */
  2810. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2811. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2812. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2813. return quat;
  2814. };
  2815. /**
  2816. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2817. * cf to Vector3.RotationFromAxis() documentation.
  2818. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2819. */
  2820. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2821. var rotMat = MathTmp.Matrix[0];
  2822. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2823. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2824. };
  2825. Quaternion.Slerp = function (left, right, amount) {
  2826. var result = Quaternion.Identity();
  2827. Quaternion.SlerpToRef(left, right, amount, result);
  2828. return result;
  2829. };
  2830. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2831. var num2;
  2832. var num3;
  2833. var num = amount;
  2834. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2835. var flag = false;
  2836. if (num4 < 0) {
  2837. flag = true;
  2838. num4 = -num4;
  2839. }
  2840. if (num4 > 0.999999) {
  2841. num3 = 1 - num;
  2842. num2 = flag ? -num : num;
  2843. }
  2844. else {
  2845. var num5 = Math.acos(num4);
  2846. var num6 = (1.0 / Math.sin(num5));
  2847. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2848. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2849. }
  2850. result.x = (num3 * left.x) + (num2 * right.x);
  2851. result.y = (num3 * left.y) + (num2 * right.y);
  2852. result.z = (num3 * left.z) + (num2 * right.z);
  2853. result.w = (num3 * left.w) + (num2 * right.w);
  2854. };
  2855. /**
  2856. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2857. */
  2858. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2859. var squared = amount * amount;
  2860. var cubed = amount * squared;
  2861. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2862. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2863. var part3 = (cubed - (2.0 * squared)) + amount;
  2864. var part4 = cubed - squared;
  2865. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2866. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2867. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2868. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2869. return new Quaternion(x, y, z, w);
  2870. };
  2871. return Quaternion;
  2872. }());
  2873. BABYLON.Quaternion = Quaternion;
  2874. var Matrix = /** @class */ (function () {
  2875. function Matrix() {
  2876. this._isIdentity = false;
  2877. this._isIdentityDirty = true;
  2878. this.m = new Float32Array(16);
  2879. this._markAsUpdated();
  2880. }
  2881. Matrix.prototype._markAsUpdated = function () {
  2882. this.updateFlag = Matrix._updateFlagSeed++;
  2883. this._isIdentityDirty = true;
  2884. };
  2885. // Properties
  2886. /**
  2887. * Boolean : True is the matrix is the identity matrix
  2888. */
  2889. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2890. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2891. if (this._isIdentityDirty) {
  2892. this._isIdentityDirty = false;
  2893. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2894. this._isIdentity = false;
  2895. }
  2896. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2897. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2898. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2899. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2900. this._isIdentity = false;
  2901. }
  2902. else {
  2903. this._isIdentity = true;
  2904. }
  2905. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2906. this._isIdentity = false;
  2907. }
  2908. }
  2909. return this._isIdentity;
  2910. };
  2911. /**
  2912. * Returns the matrix determinant (float).
  2913. */
  2914. Matrix.prototype.determinant = function () {
  2915. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2916. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2917. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2918. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2919. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2920. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2921. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2922. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2923. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2924. };
  2925. // Methods
  2926. /**
  2927. * Returns the matrix underlying array.
  2928. */
  2929. Matrix.prototype.toArray = function () {
  2930. return this.m;
  2931. };
  2932. /**
  2933. * Returns the matrix underlying array.
  2934. */
  2935. Matrix.prototype.asArray = function () {
  2936. return this.toArray();
  2937. };
  2938. /**
  2939. * Inverts in place the Matrix.
  2940. * Returns the Matrix inverted.
  2941. */
  2942. Matrix.prototype.invert = function () {
  2943. this.invertToRef(this);
  2944. return this;
  2945. };
  2946. /**
  2947. * Sets all the matrix elements to zero.
  2948. * Returns the Matrix.
  2949. */
  2950. Matrix.prototype.reset = function () {
  2951. for (var index = 0; index < 16; index++) {
  2952. this.m[index] = 0.0;
  2953. }
  2954. this._markAsUpdated();
  2955. return this;
  2956. };
  2957. /**
  2958. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2959. */
  2960. Matrix.prototype.add = function (other) {
  2961. var result = new Matrix();
  2962. this.addToRef(other, result);
  2963. return result;
  2964. };
  2965. /**
  2966. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2967. * Returns the Matrix.
  2968. */
  2969. Matrix.prototype.addToRef = function (other, result) {
  2970. for (var index = 0; index < 16; index++) {
  2971. result.m[index] = this.m[index] + other.m[index];
  2972. }
  2973. result._markAsUpdated();
  2974. return this;
  2975. };
  2976. /**
  2977. * Adds in place the passed matrix to the current Matrix.
  2978. * Returns the updated Matrix.
  2979. */
  2980. Matrix.prototype.addToSelf = function (other) {
  2981. for (var index = 0; index < 16; index++) {
  2982. this.m[index] += other.m[index];
  2983. }
  2984. this._markAsUpdated();
  2985. return this;
  2986. };
  2987. /**
  2988. * Sets the passed matrix with the current inverted Matrix.
  2989. * Returns the unmodified current Matrix.
  2990. */
  2991. Matrix.prototype.invertToRef = function (other) {
  2992. var l1 = this.m[0];
  2993. var l2 = this.m[1];
  2994. var l3 = this.m[2];
  2995. var l4 = this.m[3];
  2996. var l5 = this.m[4];
  2997. var l6 = this.m[5];
  2998. var l7 = this.m[6];
  2999. var l8 = this.m[7];
  3000. var l9 = this.m[8];
  3001. var l10 = this.m[9];
  3002. var l11 = this.m[10];
  3003. var l12 = this.m[11];
  3004. var l13 = this.m[12];
  3005. var l14 = this.m[13];
  3006. var l15 = this.m[14];
  3007. var l16 = this.m[15];
  3008. var l17 = (l11 * l16) - (l12 * l15);
  3009. var l18 = (l10 * l16) - (l12 * l14);
  3010. var l19 = (l10 * l15) - (l11 * l14);
  3011. var l20 = (l9 * l16) - (l12 * l13);
  3012. var l21 = (l9 * l15) - (l11 * l13);
  3013. var l22 = (l9 * l14) - (l10 * l13);
  3014. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3015. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3016. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3017. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3018. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3019. var l28 = (l7 * l16) - (l8 * l15);
  3020. var l29 = (l6 * l16) - (l8 * l14);
  3021. var l30 = (l6 * l15) - (l7 * l14);
  3022. var l31 = (l5 * l16) - (l8 * l13);
  3023. var l32 = (l5 * l15) - (l7 * l13);
  3024. var l33 = (l5 * l14) - (l6 * l13);
  3025. var l34 = (l7 * l12) - (l8 * l11);
  3026. var l35 = (l6 * l12) - (l8 * l10);
  3027. var l36 = (l6 * l11) - (l7 * l10);
  3028. var l37 = (l5 * l12) - (l8 * l9);
  3029. var l38 = (l5 * l11) - (l7 * l9);
  3030. var l39 = (l5 * l10) - (l6 * l9);
  3031. other.m[0] = l23 * l27;
  3032. other.m[4] = l24 * l27;
  3033. other.m[8] = l25 * l27;
  3034. other.m[12] = l26 * l27;
  3035. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3036. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3037. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3038. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3039. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3040. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3041. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3042. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3043. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3044. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3045. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3046. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3047. other._markAsUpdated();
  3048. return this;
  3049. };
  3050. /**
  3051. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3052. * Returns the updated Matrix.
  3053. */
  3054. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3055. this.m[12] = x;
  3056. this.m[13] = y;
  3057. this.m[14] = z;
  3058. this._markAsUpdated();
  3059. return this;
  3060. };
  3061. /**
  3062. * Inserts the translation vector in the current Matrix.
  3063. * Returns the updated Matrix.
  3064. */
  3065. Matrix.prototype.setTranslation = function (vector3) {
  3066. this.m[12] = vector3.x;
  3067. this.m[13] = vector3.y;
  3068. this.m[14] = vector3.z;
  3069. this._markAsUpdated();
  3070. return this;
  3071. };
  3072. /**
  3073. * Returns a new Vector3 as the extracted translation from the Matrix.
  3074. */
  3075. Matrix.prototype.getTranslation = function () {
  3076. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3077. };
  3078. /**
  3079. * Fill a Vector3 with the extracted translation from the Matrix.
  3080. */
  3081. Matrix.prototype.getTranslationToRef = function (result) {
  3082. result.x = this.m[12];
  3083. result.y = this.m[13];
  3084. result.z = this.m[14];
  3085. return this;
  3086. };
  3087. /**
  3088. * Remove rotation and scaling part from the Matrix.
  3089. * Returns the updated Matrix.
  3090. */
  3091. Matrix.prototype.removeRotationAndScaling = function () {
  3092. this.setRowFromFloats(0, 1, 0, 0, 0);
  3093. this.setRowFromFloats(1, 0, 1, 0, 0);
  3094. this.setRowFromFloats(2, 0, 0, 1, 0);
  3095. return this;
  3096. };
  3097. /**
  3098. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3099. */
  3100. Matrix.prototype.multiply = function (other) {
  3101. var result = new Matrix();
  3102. this.multiplyToRef(other, result);
  3103. return result;
  3104. };
  3105. /**
  3106. * Updates the current Matrix from the passed one values.
  3107. * Returns the updated Matrix.
  3108. */
  3109. Matrix.prototype.copyFrom = function (other) {
  3110. for (var index = 0; index < 16; index++) {
  3111. this.m[index] = other.m[index];
  3112. }
  3113. this._markAsUpdated();
  3114. return this;
  3115. };
  3116. /**
  3117. * Populates the passed array from the starting index with the Matrix values.
  3118. * Returns the Matrix.
  3119. */
  3120. Matrix.prototype.copyToArray = function (array, offset) {
  3121. if (offset === void 0) { offset = 0; }
  3122. for (var index = 0; index < 16; index++) {
  3123. array[offset + index] = this.m[index];
  3124. }
  3125. return this;
  3126. };
  3127. /**
  3128. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3129. */
  3130. Matrix.prototype.multiplyToRef = function (other, result) {
  3131. this.multiplyToArray(other, result.m, 0);
  3132. result._markAsUpdated();
  3133. return this;
  3134. };
  3135. /**
  3136. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3137. */
  3138. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3139. var tm0 = this.m[0];
  3140. var tm1 = this.m[1];
  3141. var tm2 = this.m[2];
  3142. var tm3 = this.m[3];
  3143. var tm4 = this.m[4];
  3144. var tm5 = this.m[5];
  3145. var tm6 = this.m[6];
  3146. var tm7 = this.m[7];
  3147. var tm8 = this.m[8];
  3148. var tm9 = this.m[9];
  3149. var tm10 = this.m[10];
  3150. var tm11 = this.m[11];
  3151. var tm12 = this.m[12];
  3152. var tm13 = this.m[13];
  3153. var tm14 = this.m[14];
  3154. var tm15 = this.m[15];
  3155. var om0 = other.m[0];
  3156. var om1 = other.m[1];
  3157. var om2 = other.m[2];
  3158. var om3 = other.m[3];
  3159. var om4 = other.m[4];
  3160. var om5 = other.m[5];
  3161. var om6 = other.m[6];
  3162. var om7 = other.m[7];
  3163. var om8 = other.m[8];
  3164. var om9 = other.m[9];
  3165. var om10 = other.m[10];
  3166. var om11 = other.m[11];
  3167. var om12 = other.m[12];
  3168. var om13 = other.m[13];
  3169. var om14 = other.m[14];
  3170. var om15 = other.m[15];
  3171. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3172. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3173. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3174. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3175. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3176. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3177. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3178. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3179. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3180. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3181. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3182. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3183. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3184. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3185. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3186. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3187. return this;
  3188. };
  3189. /**
  3190. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3191. */
  3192. Matrix.prototype.equals = function (value) {
  3193. return value &&
  3194. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3195. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3196. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3197. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3198. };
  3199. /**
  3200. * Returns a new Matrix from the current Matrix.
  3201. */
  3202. Matrix.prototype.clone = function () {
  3203. 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]);
  3204. };
  3205. /**
  3206. * Returns the string "Matrix"
  3207. */
  3208. Matrix.prototype.getClassName = function () {
  3209. return "Matrix";
  3210. };
  3211. /**
  3212. * Returns the Matrix hash code.
  3213. */
  3214. Matrix.prototype.getHashCode = function () {
  3215. var hash = this.m[0] || 0;
  3216. for (var i = 1; i < 16; i++) {
  3217. hash = (hash * 397) ^ (this.m[i] || 0);
  3218. }
  3219. return hash;
  3220. };
  3221. /**
  3222. * Decomposes the current Matrix into :
  3223. * - a scale vector3 passed as a reference to update,
  3224. * - a rotation quaternion passed as a reference to update,
  3225. * - a translation vector3 passed as a reference to update.
  3226. * Returns the boolean `true`.
  3227. */
  3228. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3229. translation.x = this.m[12];
  3230. translation.y = this.m[13];
  3231. translation.z = this.m[14];
  3232. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3233. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3234. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3235. if (this.determinant() <= 0) {
  3236. scale.y *= -1;
  3237. }
  3238. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3239. rotation.x = 0;
  3240. rotation.y = 0;
  3241. rotation.z = 0;
  3242. rotation.w = 1;
  3243. return false;
  3244. }
  3245. 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]);
  3246. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3247. return true;
  3248. };
  3249. /**
  3250. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3251. */
  3252. Matrix.prototype.getRotationMatrix = function () {
  3253. var result = Matrix.Identity();
  3254. this.getRotationMatrixToRef(result);
  3255. return result;
  3256. };
  3257. /**
  3258. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3259. * Returns the current Matrix.
  3260. */
  3261. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3262. var m = this.m;
  3263. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3264. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3265. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3266. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3267. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3268. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3269. 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);
  3270. return this;
  3271. };
  3272. // Statics
  3273. /**
  3274. * Returns a new Matrix set from the starting index of the passed array.
  3275. */
  3276. Matrix.FromArray = function (array, offset) {
  3277. var result = new Matrix();
  3278. if (!offset) {
  3279. offset = 0;
  3280. }
  3281. Matrix.FromArrayToRef(array, offset, result);
  3282. return result;
  3283. };
  3284. /**
  3285. * Sets the passed "result" matrix from the starting index of the passed array.
  3286. */
  3287. Matrix.FromArrayToRef = function (array, offset, result) {
  3288. for (var index = 0; index < 16; index++) {
  3289. result.m[index] = array[index + offset];
  3290. }
  3291. result._markAsUpdated();
  3292. };
  3293. /**
  3294. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3295. */
  3296. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3297. for (var index = 0; index < 16; index++) {
  3298. result.m[index] = array[index + offset] * scale;
  3299. }
  3300. result._markAsUpdated();
  3301. };
  3302. /**
  3303. * Sets the passed matrix "result" with the 16 passed floats.
  3304. */
  3305. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3306. result.m[0] = initialM11;
  3307. result.m[1] = initialM12;
  3308. result.m[2] = initialM13;
  3309. result.m[3] = initialM14;
  3310. result.m[4] = initialM21;
  3311. result.m[5] = initialM22;
  3312. result.m[6] = initialM23;
  3313. result.m[7] = initialM24;
  3314. result.m[8] = initialM31;
  3315. result.m[9] = initialM32;
  3316. result.m[10] = initialM33;
  3317. result.m[11] = initialM34;
  3318. result.m[12] = initialM41;
  3319. result.m[13] = initialM42;
  3320. result.m[14] = initialM43;
  3321. result.m[15] = initialM44;
  3322. result._markAsUpdated();
  3323. };
  3324. /**
  3325. * Returns the index-th row of the current matrix as a new Vector4.
  3326. */
  3327. Matrix.prototype.getRow = function (index) {
  3328. if (index < 0 || index > 3) {
  3329. return null;
  3330. }
  3331. var i = index * 4;
  3332. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3333. };
  3334. /**
  3335. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3336. * Returns the updated Matrix.
  3337. */
  3338. Matrix.prototype.setRow = function (index, row) {
  3339. if (index < 0 || index > 3) {
  3340. return this;
  3341. }
  3342. var i = index * 4;
  3343. this.m[i + 0] = row.x;
  3344. this.m[i + 1] = row.y;
  3345. this.m[i + 2] = row.z;
  3346. this.m[i + 3] = row.w;
  3347. this._markAsUpdated();
  3348. return this;
  3349. };
  3350. /**
  3351. * Compute the transpose of the matrix.
  3352. * Returns a new Matrix.
  3353. */
  3354. Matrix.prototype.transpose = function () {
  3355. return Matrix.Transpose(this);
  3356. };
  3357. /**
  3358. * Compute the transpose of the matrix.
  3359. * Returns the current matrix.
  3360. */
  3361. Matrix.prototype.transposeToRef = function (result) {
  3362. Matrix.TransposeToRef(this, result);
  3363. return this;
  3364. };
  3365. /**
  3366. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3367. * Returns the updated Matrix.
  3368. */
  3369. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3370. if (index < 0 || index > 3) {
  3371. return this;
  3372. }
  3373. var i = index * 4;
  3374. this.m[i + 0] = x;
  3375. this.m[i + 1] = y;
  3376. this.m[i + 2] = z;
  3377. this.m[i + 3] = w;
  3378. this._markAsUpdated();
  3379. return this;
  3380. };
  3381. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3382. /**
  3383. * Static identity matrix to be used as readonly matrix
  3384. * Must not be updated.
  3385. */
  3386. get: function () {
  3387. return Matrix._identityReadOnly;
  3388. },
  3389. enumerable: true,
  3390. configurable: true
  3391. });
  3392. /**
  3393. * Returns a new Matrix set from the 16 passed floats.
  3394. */
  3395. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3396. var result = new Matrix();
  3397. result.m[0] = initialM11;
  3398. result.m[1] = initialM12;
  3399. result.m[2] = initialM13;
  3400. result.m[3] = initialM14;
  3401. result.m[4] = initialM21;
  3402. result.m[5] = initialM22;
  3403. result.m[6] = initialM23;
  3404. result.m[7] = initialM24;
  3405. result.m[8] = initialM31;
  3406. result.m[9] = initialM32;
  3407. result.m[10] = initialM33;
  3408. result.m[11] = initialM34;
  3409. result.m[12] = initialM41;
  3410. result.m[13] = initialM42;
  3411. result.m[14] = initialM43;
  3412. result.m[15] = initialM44;
  3413. return result;
  3414. };
  3415. /**
  3416. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3417. */
  3418. Matrix.Compose = function (scale, rotation, translation) {
  3419. var result = Matrix.Identity();
  3420. Matrix.ComposeToRef(scale, rotation, translation, result);
  3421. return result;
  3422. };
  3423. /**
  3424. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3425. */
  3426. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3427. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3428. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3429. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3430. result.setTranslation(translation);
  3431. };
  3432. /**
  3433. * Returns a new indentity Matrix.
  3434. */
  3435. Matrix.Identity = function () {
  3436. 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);
  3437. };
  3438. /**
  3439. * Sets the passed "result" as an identity matrix.
  3440. */
  3441. Matrix.IdentityToRef = function (result) {
  3442. 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);
  3443. };
  3444. /**
  3445. * Returns a new zero Matrix.
  3446. */
  3447. Matrix.Zero = function () {
  3448. 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);
  3449. };
  3450. /**
  3451. * Returns a new rotation matrix for "angle" radians around the X axis.
  3452. */
  3453. Matrix.RotationX = function (angle) {
  3454. var result = new Matrix();
  3455. Matrix.RotationXToRef(angle, result);
  3456. return result;
  3457. };
  3458. /**
  3459. * Returns a new Matrix as the passed inverted one.
  3460. */
  3461. Matrix.Invert = function (source) {
  3462. var result = new Matrix();
  3463. source.invertToRef(result);
  3464. return result;
  3465. };
  3466. /**
  3467. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3468. */
  3469. Matrix.RotationXToRef = function (angle, result) {
  3470. var s = Math.sin(angle);
  3471. var c = Math.cos(angle);
  3472. result.m[0] = 1.0;
  3473. result.m[15] = 1.0;
  3474. result.m[5] = c;
  3475. result.m[10] = c;
  3476. result.m[9] = -s;
  3477. result.m[6] = s;
  3478. result.m[1] = 0.0;
  3479. result.m[2] = 0.0;
  3480. result.m[3] = 0.0;
  3481. result.m[4] = 0.0;
  3482. result.m[7] = 0.0;
  3483. result.m[8] = 0.0;
  3484. result.m[11] = 0.0;
  3485. result.m[12] = 0.0;
  3486. result.m[13] = 0.0;
  3487. result.m[14] = 0.0;
  3488. result._markAsUpdated();
  3489. };
  3490. /**
  3491. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3492. */
  3493. Matrix.RotationY = function (angle) {
  3494. var result = new Matrix();
  3495. Matrix.RotationYToRef(angle, result);
  3496. return result;
  3497. };
  3498. /**
  3499. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3500. */
  3501. Matrix.RotationYToRef = function (angle, result) {
  3502. var s = Math.sin(angle);
  3503. var c = Math.cos(angle);
  3504. result.m[5] = 1.0;
  3505. result.m[15] = 1.0;
  3506. result.m[0] = c;
  3507. result.m[2] = -s;
  3508. result.m[8] = s;
  3509. result.m[10] = c;
  3510. result.m[1] = 0.0;
  3511. result.m[3] = 0.0;
  3512. result.m[4] = 0.0;
  3513. result.m[6] = 0.0;
  3514. result.m[7] = 0.0;
  3515. result.m[9] = 0.0;
  3516. result.m[11] = 0.0;
  3517. result.m[12] = 0.0;
  3518. result.m[13] = 0.0;
  3519. result.m[14] = 0.0;
  3520. result._markAsUpdated();
  3521. };
  3522. /**
  3523. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3524. */
  3525. Matrix.RotationZ = function (angle) {
  3526. var result = new Matrix();
  3527. Matrix.RotationZToRef(angle, result);
  3528. return result;
  3529. };
  3530. /**
  3531. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3532. */
  3533. Matrix.RotationZToRef = function (angle, result) {
  3534. var s = Math.sin(angle);
  3535. var c = Math.cos(angle);
  3536. result.m[10] = 1.0;
  3537. result.m[15] = 1.0;
  3538. result.m[0] = c;
  3539. result.m[1] = s;
  3540. result.m[4] = -s;
  3541. result.m[5] = c;
  3542. result.m[2] = 0.0;
  3543. result.m[3] = 0.0;
  3544. result.m[6] = 0.0;
  3545. result.m[7] = 0.0;
  3546. result.m[8] = 0.0;
  3547. result.m[9] = 0.0;
  3548. result.m[11] = 0.0;
  3549. result.m[12] = 0.0;
  3550. result.m[13] = 0.0;
  3551. result.m[14] = 0.0;
  3552. result._markAsUpdated();
  3553. };
  3554. /**
  3555. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3556. */
  3557. Matrix.RotationAxis = function (axis, angle) {
  3558. var result = Matrix.Zero();
  3559. Matrix.RotationAxisToRef(axis, angle, result);
  3560. return result;
  3561. };
  3562. /**
  3563. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3564. */
  3565. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3566. var s = Math.sin(-angle);
  3567. var c = Math.cos(-angle);
  3568. var c1 = 1 - c;
  3569. axis.normalize();
  3570. result.m[0] = (axis.x * axis.x) * c1 + c;
  3571. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3572. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3573. result.m[3] = 0.0;
  3574. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3575. result.m[5] = (axis.y * axis.y) * c1 + c;
  3576. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3577. result.m[7] = 0.0;
  3578. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3579. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3580. result.m[10] = (axis.z * axis.z) * c1 + c;
  3581. result.m[11] = 0.0;
  3582. result.m[15] = 1.0;
  3583. result._markAsUpdated();
  3584. };
  3585. /**
  3586. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3587. */
  3588. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3589. var result = new Matrix();
  3590. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3591. return result;
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3595. */
  3596. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3597. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3598. this._tempQuaternion.toRotationMatrix(result);
  3599. };
  3600. /**
  3601. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3602. */
  3603. Matrix.Scaling = function (x, y, z) {
  3604. var result = Matrix.Zero();
  3605. Matrix.ScalingToRef(x, y, z, result);
  3606. return result;
  3607. };
  3608. /**
  3609. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3610. */
  3611. Matrix.ScalingToRef = function (x, y, z, result) {
  3612. result.m[0] = x;
  3613. result.m[1] = 0.0;
  3614. result.m[2] = 0.0;
  3615. result.m[3] = 0.0;
  3616. result.m[4] = 0.0;
  3617. result.m[5] = y;
  3618. result.m[6] = 0.0;
  3619. result.m[7] = 0.0;
  3620. result.m[8] = 0.0;
  3621. result.m[9] = 0.0;
  3622. result.m[10] = z;
  3623. result.m[11] = 0.0;
  3624. result.m[12] = 0.0;
  3625. result.m[13] = 0.0;
  3626. result.m[14] = 0.0;
  3627. result.m[15] = 1.0;
  3628. result._markAsUpdated();
  3629. };
  3630. /**
  3631. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3632. */
  3633. Matrix.Translation = function (x, y, z) {
  3634. var result = Matrix.Identity();
  3635. Matrix.TranslationToRef(x, y, z, result);
  3636. return result;
  3637. };
  3638. /**
  3639. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3640. */
  3641. Matrix.TranslationToRef = function (x, y, z, result) {
  3642. 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);
  3643. };
  3644. /**
  3645. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3646. */
  3647. Matrix.Lerp = function (startValue, endValue, gradient) {
  3648. var result = Matrix.Zero();
  3649. for (var index = 0; index < 16; index++) {
  3650. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3651. }
  3652. result._markAsUpdated();
  3653. return result;
  3654. };
  3655. /**
  3656. * Returns a new Matrix whose values are computed by :
  3657. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3658. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3659. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3660. */
  3661. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3662. var startScale = new Vector3(0, 0, 0);
  3663. var startRotation = new Quaternion();
  3664. var startTranslation = new Vector3(0, 0, 0);
  3665. startValue.decompose(startScale, startRotation, startTranslation);
  3666. var endScale = new Vector3(0, 0, 0);
  3667. var endRotation = new Quaternion();
  3668. var endTranslation = new Vector3(0, 0, 0);
  3669. endValue.decompose(endScale, endRotation, endTranslation);
  3670. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3671. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3672. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3673. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3674. };
  3675. /**
  3676. * 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".
  3677. * This methods works for a Left-Handed system.
  3678. */
  3679. Matrix.LookAtLH = function (eye, target, up) {
  3680. var result = Matrix.Zero();
  3681. Matrix.LookAtLHToRef(eye, target, up, result);
  3682. return result;
  3683. };
  3684. /**
  3685. * 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".
  3686. * This methods works for a Left-Handed system.
  3687. */
  3688. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3689. // Z axis
  3690. target.subtractToRef(eye, this._zAxis);
  3691. this._zAxis.normalize();
  3692. // X axis
  3693. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3694. if (this._xAxis.lengthSquared() === 0) {
  3695. this._xAxis.x = 1.0;
  3696. }
  3697. else {
  3698. this._xAxis.normalize();
  3699. }
  3700. // Y axis
  3701. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3702. this._yAxis.normalize();
  3703. // Eye angles
  3704. var ex = -Vector3.Dot(this._xAxis, eye);
  3705. var ey = -Vector3.Dot(this._yAxis, eye);
  3706. var ez = -Vector3.Dot(this._zAxis, eye);
  3707. 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);
  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 Right-Handed system.
  3712. */
  3713. Matrix.LookAtRH = function (eye, target, up) {
  3714. var result = Matrix.Zero();
  3715. Matrix.LookAtRHToRef(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.LookAtRHToRef = function (eye, target, up, result) {
  3723. // Z axis
  3724. eye.subtractToRef(target, 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 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.
  3745. */
  3746. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3747. var matrix = Matrix.Zero();
  3748. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3749. return matrix;
  3750. };
  3751. /**
  3752. * 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.
  3753. */
  3754. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3755. var n = znear;
  3756. var f = zfar;
  3757. var a = 2.0 / width;
  3758. var b = 2.0 / height;
  3759. var c = 2.0 / (f - n);
  3760. var d = -(f + n) / (f - n);
  3761. 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);
  3762. };
  3763. /**
  3764. * 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.
  3765. */
  3766. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3767. var matrix = Matrix.Zero();
  3768. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3769. return matrix;
  3770. };
  3771. /**
  3772. * 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.
  3773. */
  3774. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3775. var n = znear;
  3776. var f = zfar;
  3777. var a = 2.0 / (right - left);
  3778. var b = 2.0 / (top - bottom);
  3779. var c = 2.0 / (f - n);
  3780. var d = -(f + n) / (f - n);
  3781. var i0 = (left + right) / (left - right);
  3782. var i1 = (top + bottom) / (bottom - top);
  3783. 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);
  3784. };
  3785. /**
  3786. * 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.
  3787. */
  3788. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3789. var matrix = Matrix.Zero();
  3790. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3791. return matrix;
  3792. };
  3793. /**
  3794. * 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.
  3795. */
  3796. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3797. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3798. result.m[10] *= -1.0;
  3799. };
  3800. /**
  3801. * 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.
  3802. */
  3803. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3804. var matrix = Matrix.Zero();
  3805. var n = znear;
  3806. var f = zfar;
  3807. var a = 2.0 * n / width;
  3808. var b = 2.0 * n / height;
  3809. var c = (f + n) / (f - n);
  3810. var d = -2.0 * f * n / (f - n);
  3811. 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);
  3812. return matrix;
  3813. };
  3814. /**
  3815. * 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.
  3816. */
  3817. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3818. var matrix = Matrix.Zero();
  3819. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3820. return matrix;
  3821. };
  3822. /**
  3823. * 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.
  3824. */
  3825. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3826. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3827. var n = znear;
  3828. var f = zfar;
  3829. var t = 1.0 / (Math.tan(fov * 0.5));
  3830. var a = isVerticalFovFixed ? (t / aspect) : t;
  3831. var b = isVerticalFovFixed ? t : (t * aspect);
  3832. var c = (f + n) / (f - n);
  3833. var d = -2.0 * f * n / (f - n);
  3834. 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);
  3835. };
  3836. /**
  3837. * 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.
  3838. */
  3839. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3840. var matrix = Matrix.Zero();
  3841. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3842. return matrix;
  3843. };
  3844. /**
  3845. * 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.
  3846. */
  3847. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3848. //alternatively this could be expressed as:
  3849. // m = PerspectiveFovLHToRef
  3850. // m[10] *= -1.0;
  3851. // m[11] *= -1.0;
  3852. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3853. var n = znear;
  3854. var f = zfar;
  3855. var t = 1.0 / (Math.tan(fov * 0.5));
  3856. var a = isVerticalFovFixed ? (t / aspect) : t;
  3857. var b = isVerticalFovFixed ? t : (t * aspect);
  3858. var c = -(f + n) / (f - n);
  3859. var d = -2 * f * n / (f - n);
  3860. 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);
  3861. };
  3862. /**
  3863. * 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.
  3864. */
  3865. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3866. if (rightHanded === void 0) { rightHanded = false; }
  3867. var rightHandedFactor = rightHanded ? -1 : 1;
  3868. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3869. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3870. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3871. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3872. var xScale = 2.0 / (leftTan + rightTan);
  3873. var yScale = 2.0 / (upTan + downTan);
  3874. result.m[0] = xScale;
  3875. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3876. result.m[5] = yScale;
  3877. result.m[6] = result.m[7] = 0.0;
  3878. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3879. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3880. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3881. result.m[10] = -zfar / (znear - zfar);
  3882. result.m[11] = 1.0 * rightHandedFactor;
  3883. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3884. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3885. // result.m[14] = (znear * zfar) / (znear - zfar);
  3886. result._markAsUpdated();
  3887. };
  3888. /**
  3889. * Returns the final transformation matrix : world * view * projection * viewport
  3890. */
  3891. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3892. var cw = viewport.width;
  3893. var ch = viewport.height;
  3894. var cx = viewport.x;
  3895. var cy = viewport.y;
  3896. 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);
  3897. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3898. };
  3899. /**
  3900. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3901. */
  3902. Matrix.GetAsMatrix2x2 = function (matrix) {
  3903. return new Float32Array([
  3904. matrix.m[0], matrix.m[1],
  3905. matrix.m[4], matrix.m[5]
  3906. ]);
  3907. };
  3908. /**
  3909. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3910. */
  3911. Matrix.GetAsMatrix3x3 = function (matrix) {
  3912. return new Float32Array([
  3913. matrix.m[0], matrix.m[1], matrix.m[2],
  3914. matrix.m[4], matrix.m[5], matrix.m[6],
  3915. matrix.m[8], matrix.m[9], matrix.m[10]
  3916. ]);
  3917. };
  3918. /**
  3919. * Compute the transpose of the passed Matrix.
  3920. * Returns a new Matrix.
  3921. */
  3922. Matrix.Transpose = function (matrix) {
  3923. var result = new Matrix();
  3924. Matrix.TransposeToRef(matrix, result);
  3925. return result;
  3926. };
  3927. /**
  3928. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3929. */
  3930. Matrix.TransposeToRef = function (matrix, result) {
  3931. result.m[0] = matrix.m[0];
  3932. result.m[1] = matrix.m[4];
  3933. result.m[2] = matrix.m[8];
  3934. result.m[3] = matrix.m[12];
  3935. result.m[4] = matrix.m[1];
  3936. result.m[5] = matrix.m[5];
  3937. result.m[6] = matrix.m[9];
  3938. result.m[7] = matrix.m[13];
  3939. result.m[8] = matrix.m[2];
  3940. result.m[9] = matrix.m[6];
  3941. result.m[10] = matrix.m[10];
  3942. result.m[11] = matrix.m[14];
  3943. result.m[12] = matrix.m[3];
  3944. result.m[13] = matrix.m[7];
  3945. result.m[14] = matrix.m[11];
  3946. result.m[15] = matrix.m[15];
  3947. };
  3948. /**
  3949. * Returns a new Matrix as the reflection matrix across the passed plane.
  3950. */
  3951. Matrix.Reflection = function (plane) {
  3952. var matrix = new Matrix();
  3953. Matrix.ReflectionToRef(plane, matrix);
  3954. return matrix;
  3955. };
  3956. /**
  3957. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3958. */
  3959. Matrix.ReflectionToRef = function (plane, result) {
  3960. plane.normalize();
  3961. var x = plane.normal.x;
  3962. var y = plane.normal.y;
  3963. var z = plane.normal.z;
  3964. var temp = -2 * x;
  3965. var temp2 = -2 * y;
  3966. var temp3 = -2 * z;
  3967. result.m[0] = (temp * x) + 1;
  3968. result.m[1] = temp2 * x;
  3969. result.m[2] = temp3 * x;
  3970. result.m[3] = 0.0;
  3971. result.m[4] = temp * y;
  3972. result.m[5] = (temp2 * y) + 1;
  3973. result.m[6] = temp3 * y;
  3974. result.m[7] = 0.0;
  3975. result.m[8] = temp * z;
  3976. result.m[9] = temp2 * z;
  3977. result.m[10] = (temp3 * z) + 1;
  3978. result.m[11] = 0.0;
  3979. result.m[12] = temp * plane.d;
  3980. result.m[13] = temp2 * plane.d;
  3981. result.m[14] = temp3 * plane.d;
  3982. result.m[15] = 1.0;
  3983. result._markAsUpdated();
  3984. };
  3985. /**
  3986. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3987. */
  3988. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3989. result.m[0] = xaxis.x;
  3990. result.m[1] = xaxis.y;
  3991. result.m[2] = xaxis.z;
  3992. result.m[3] = 0.0;
  3993. result.m[4] = yaxis.x;
  3994. result.m[5] = yaxis.y;
  3995. result.m[6] = yaxis.z;
  3996. result.m[7] = 0.0;
  3997. result.m[8] = zaxis.x;
  3998. result.m[9] = zaxis.y;
  3999. result.m[10] = zaxis.z;
  4000. result.m[11] = 0.0;
  4001. result.m[12] = 0.0;
  4002. result.m[13] = 0.0;
  4003. result.m[14] = 0.0;
  4004. result.m[15] = 1.0;
  4005. result._markAsUpdated();
  4006. };
  4007. /**
  4008. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4009. */
  4010. Matrix.FromQuaternionToRef = function (quat, result) {
  4011. var xx = quat.x * quat.x;
  4012. var yy = quat.y * quat.y;
  4013. var zz = quat.z * quat.z;
  4014. var xy = quat.x * quat.y;
  4015. var zw = quat.z * quat.w;
  4016. var zx = quat.z * quat.x;
  4017. var yw = quat.y * quat.w;
  4018. var yz = quat.y * quat.z;
  4019. var xw = quat.x * quat.w;
  4020. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4021. result.m[1] = 2.0 * (xy + zw);
  4022. result.m[2] = 2.0 * (zx - yw);
  4023. result.m[3] = 0.0;
  4024. result.m[4] = 2.0 * (xy - zw);
  4025. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4026. result.m[6] = 2.0 * (yz + xw);
  4027. result.m[7] = 0.0;
  4028. result.m[8] = 2.0 * (zx + yw);
  4029. result.m[9] = 2.0 * (yz - xw);
  4030. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4031. result.m[11] = 0.0;
  4032. result.m[12] = 0.0;
  4033. result.m[13] = 0.0;
  4034. result.m[14] = 0.0;
  4035. result.m[15] = 1.0;
  4036. result._markAsUpdated();
  4037. };
  4038. Matrix._tempQuaternion = new Quaternion();
  4039. Matrix._xAxis = Vector3.Zero();
  4040. Matrix._yAxis = Vector3.Zero();
  4041. Matrix._zAxis = Vector3.Zero();
  4042. Matrix._updateFlagSeed = 0;
  4043. Matrix._identityReadOnly = Matrix.Identity();
  4044. return Matrix;
  4045. }());
  4046. BABYLON.Matrix = Matrix;
  4047. var Plane = /** @class */ (function () {
  4048. /**
  4049. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4050. */
  4051. function Plane(a, b, c, d) {
  4052. this.normal = new Vector3(a, b, c);
  4053. this.d = d;
  4054. }
  4055. /**
  4056. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4057. */
  4058. Plane.prototype.asArray = function () {
  4059. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4060. };
  4061. // Methods
  4062. /**
  4063. * Returns a new plane copied from the current Plane.
  4064. */
  4065. Plane.prototype.clone = function () {
  4066. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4067. };
  4068. /**
  4069. * Returns the string "Plane".
  4070. */
  4071. Plane.prototype.getClassName = function () {
  4072. return "Plane";
  4073. };
  4074. /**
  4075. * Returns the Plane hash code.
  4076. */
  4077. Plane.prototype.getHashCode = function () {
  4078. var hash = this.normal.getHashCode();
  4079. hash = (hash * 397) ^ (this.d || 0);
  4080. return hash;
  4081. };
  4082. /**
  4083. * Normalize the current Plane in place.
  4084. * Returns the updated Plane.
  4085. */
  4086. Plane.prototype.normalize = function () {
  4087. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4088. var magnitude = 0.0;
  4089. if (norm !== 0) {
  4090. magnitude = 1.0 / norm;
  4091. }
  4092. this.normal.x *= magnitude;
  4093. this.normal.y *= magnitude;
  4094. this.normal.z *= magnitude;
  4095. this.d *= magnitude;
  4096. return this;
  4097. };
  4098. /**
  4099. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4100. */
  4101. Plane.prototype.transform = function (transformation) {
  4102. var transposedMatrix = Matrix.Transpose(transformation);
  4103. var x = this.normal.x;
  4104. var y = this.normal.y;
  4105. var z = this.normal.z;
  4106. var d = this.d;
  4107. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4108. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4109. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4110. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4111. return new Plane(normalX, normalY, normalZ, finalD);
  4112. };
  4113. /**
  4114. * Returns the dot product (float) of the point coordinates and the plane normal.
  4115. */
  4116. Plane.prototype.dotCoordinate = function (point) {
  4117. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4118. };
  4119. /**
  4120. * Updates the current Plane from the plane defined by the three passed points.
  4121. * Returns the updated Plane.
  4122. */
  4123. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4124. var x1 = point2.x - point1.x;
  4125. var y1 = point2.y - point1.y;
  4126. var z1 = point2.z - point1.z;
  4127. var x2 = point3.x - point1.x;
  4128. var y2 = point3.y - point1.y;
  4129. var z2 = point3.z - point1.z;
  4130. var yz = (y1 * z2) - (z1 * y2);
  4131. var xz = (z1 * x2) - (x1 * z2);
  4132. var xy = (x1 * y2) - (y1 * x2);
  4133. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4134. var invPyth;
  4135. if (pyth !== 0) {
  4136. invPyth = 1.0 / pyth;
  4137. }
  4138. else {
  4139. invPyth = 0.0;
  4140. }
  4141. this.normal.x = yz * invPyth;
  4142. this.normal.y = xz * invPyth;
  4143. this.normal.z = xy * invPyth;
  4144. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4145. return this;
  4146. };
  4147. /**
  4148. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4149. */
  4150. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4151. var dot = Vector3.Dot(this.normal, direction);
  4152. return (dot <= epsilon);
  4153. };
  4154. /**
  4155. * Returns the signed distance (float) from the passed point to the Plane.
  4156. */
  4157. Plane.prototype.signedDistanceTo = function (point) {
  4158. return Vector3.Dot(point, this.normal) + this.d;
  4159. };
  4160. // Statics
  4161. /**
  4162. * Returns a new Plane from the passed array.
  4163. */
  4164. Plane.FromArray = function (array) {
  4165. return new Plane(array[0], array[1], array[2], array[3]);
  4166. };
  4167. /**
  4168. * Returns a new Plane defined by the three passed points.
  4169. */
  4170. Plane.FromPoints = function (point1, point2, point3) {
  4171. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4172. result.copyFromPoints(point1, point2, point3);
  4173. return result;
  4174. };
  4175. /**
  4176. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4177. * Note : the vector "normal" is updated because normalized.
  4178. */
  4179. Plane.FromPositionAndNormal = function (origin, normal) {
  4180. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4181. normal.normalize();
  4182. result.normal = normal;
  4183. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4184. return result;
  4185. };
  4186. /**
  4187. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4188. */
  4189. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4190. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4191. return Vector3.Dot(point, normal) + d;
  4192. };
  4193. return Plane;
  4194. }());
  4195. BABYLON.Plane = Plane;
  4196. var Viewport = /** @class */ (function () {
  4197. /**
  4198. * Creates a Viewport object located at (x, y) and sized (width, height).
  4199. */
  4200. function Viewport(x, y, width, height) {
  4201. this.x = x;
  4202. this.y = y;
  4203. this.width = width;
  4204. this.height = height;
  4205. }
  4206. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4207. if (renderWidthOrEngine.getRenderWidth) {
  4208. var engine = renderWidthOrEngine;
  4209. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4210. }
  4211. var renderWidth = renderWidthOrEngine;
  4212. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4213. };
  4214. /**
  4215. * Returns a new Viewport copied from the current one.
  4216. */
  4217. Viewport.prototype.clone = function () {
  4218. return new Viewport(this.x, this.y, this.width, this.height);
  4219. };
  4220. return Viewport;
  4221. }());
  4222. BABYLON.Viewport = Viewport;
  4223. var Frustum = /** @class */ (function () {
  4224. function Frustum() {
  4225. }
  4226. /**
  4227. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4228. */
  4229. Frustum.GetPlanes = function (transform) {
  4230. var frustumPlanes = [];
  4231. for (var index = 0; index < 6; index++) {
  4232. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4233. }
  4234. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4235. return frustumPlanes;
  4236. };
  4237. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4238. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4239. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4240. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4241. frustumPlane.d = transform.m[15] + transform.m[14];
  4242. frustumPlane.normalize();
  4243. };
  4244. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4245. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4246. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4247. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4248. frustumPlane.d = transform.m[15] - transform.m[14];
  4249. frustumPlane.normalize();
  4250. };
  4251. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4252. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4253. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4254. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4255. frustumPlane.d = transform.m[15] + transform.m[12];
  4256. frustumPlane.normalize();
  4257. };
  4258. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4259. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4260. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4261. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4262. frustumPlane.d = transform.m[15] - transform.m[12];
  4263. frustumPlane.normalize();
  4264. };
  4265. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4266. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4267. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4268. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4269. frustumPlane.d = transform.m[15] - transform.m[13];
  4270. frustumPlane.normalize();
  4271. };
  4272. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4273. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4274. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4275. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4276. frustumPlane.d = transform.m[15] + transform.m[13];
  4277. frustumPlane.normalize();
  4278. };
  4279. /**
  4280. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4281. */
  4282. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4283. // Near
  4284. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4285. // Far
  4286. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4287. // Left
  4288. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4289. // Right
  4290. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4291. // Top
  4292. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4293. // Bottom
  4294. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4295. };
  4296. return Frustum;
  4297. }());
  4298. BABYLON.Frustum = Frustum;
  4299. var Space;
  4300. (function (Space) {
  4301. Space[Space["LOCAL"] = 0] = "LOCAL";
  4302. Space[Space["WORLD"] = 1] = "WORLD";
  4303. Space[Space["BONE"] = 2] = "BONE";
  4304. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4305. var Axis = /** @class */ (function () {
  4306. function Axis() {
  4307. }
  4308. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4309. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4310. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4311. return Axis;
  4312. }());
  4313. BABYLON.Axis = Axis;
  4314. ;
  4315. var BezierCurve = /** @class */ (function () {
  4316. function BezierCurve() {
  4317. }
  4318. /**
  4319. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4320. */
  4321. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4322. // Extract X (which is equal to time here)
  4323. var f0 = 1 - 3 * x2 + 3 * x1;
  4324. var f1 = 3 * x2 - 6 * x1;
  4325. var f2 = 3 * x1;
  4326. var refinedT = t;
  4327. for (var i = 0; i < 5; i++) {
  4328. var refinedT2 = refinedT * refinedT;
  4329. var refinedT3 = refinedT2 * refinedT;
  4330. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4331. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4332. refinedT -= (x - t) * slope;
  4333. refinedT = Math.min(1, Math.max(0, refinedT));
  4334. }
  4335. // Resolve cubic bezier for the given x
  4336. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4337. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4338. Math.pow(refinedT, 3);
  4339. };
  4340. return BezierCurve;
  4341. }());
  4342. BABYLON.BezierCurve = BezierCurve;
  4343. var Orientation;
  4344. (function (Orientation) {
  4345. Orientation[Orientation["CW"] = 0] = "CW";
  4346. Orientation[Orientation["CCW"] = 1] = "CCW";
  4347. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4348. var Angle = /** @class */ (function () {
  4349. /**
  4350. * Creates an Angle object of "radians" radians (float).
  4351. */
  4352. function Angle(radians) {
  4353. var _this = this;
  4354. /**
  4355. * Returns the Angle value in degrees (float).
  4356. */
  4357. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4358. /**
  4359. * Returns the Angle value in radians (float).
  4360. */
  4361. this.radians = function () { return _this._radians; };
  4362. this._radians = radians;
  4363. if (this._radians < 0.0)
  4364. this._radians += (2.0 * Math.PI);
  4365. }
  4366. /**
  4367. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4368. */
  4369. Angle.BetweenTwoPoints = function (a, b) {
  4370. var delta = b.subtract(a);
  4371. var theta = Math.atan2(delta.y, delta.x);
  4372. return new Angle(theta);
  4373. };
  4374. /**
  4375. * Returns a new Angle object from the passed float in radians.
  4376. */
  4377. Angle.FromRadians = function (radians) {
  4378. return new Angle(radians);
  4379. };
  4380. /**
  4381. * Returns a new Angle object from the passed float in degrees.
  4382. */
  4383. Angle.FromDegrees = function (degrees) {
  4384. return new Angle(degrees * Math.PI / 180.0);
  4385. };
  4386. return Angle;
  4387. }());
  4388. BABYLON.Angle = Angle;
  4389. var Arc2 = /** @class */ (function () {
  4390. /**
  4391. * Creates an Arc object from the three passed points : start, middle and end.
  4392. */
  4393. function Arc2(startPoint, midPoint, endPoint) {
  4394. this.startPoint = startPoint;
  4395. this.midPoint = midPoint;
  4396. this.endPoint = endPoint;
  4397. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4398. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4399. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4400. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4401. 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);
  4402. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4403. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4404. var a1 = this.startAngle.degrees();
  4405. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4406. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4407. // angles correction
  4408. if (a2 - a1 > +180.0)
  4409. a2 -= 360.0;
  4410. if (a2 - a1 < -180.0)
  4411. a2 += 360.0;
  4412. if (a3 - a2 > +180.0)
  4413. a3 -= 360.0;
  4414. if (a3 - a2 < -180.0)
  4415. a3 += 360.0;
  4416. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4417. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4418. }
  4419. return Arc2;
  4420. }());
  4421. BABYLON.Arc2 = Arc2;
  4422. var Path2 = /** @class */ (function () {
  4423. /**
  4424. * Creates a Path2 object from the starting 2D coordinates x and y.
  4425. */
  4426. function Path2(x, y) {
  4427. this._points = new Array();
  4428. this._length = 0.0;
  4429. this.closed = false;
  4430. this._points.push(new Vector2(x, y));
  4431. }
  4432. /**
  4433. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4434. * Returns the updated Path2.
  4435. */
  4436. Path2.prototype.addLineTo = function (x, y) {
  4437. if (closed) {
  4438. //Tools.Error("cannot add lines to closed paths");
  4439. return this;
  4440. }
  4441. var newPoint = new Vector2(x, y);
  4442. var previousPoint = this._points[this._points.length - 1];
  4443. this._points.push(newPoint);
  4444. this._length += newPoint.subtract(previousPoint).length();
  4445. return this;
  4446. };
  4447. /**
  4448. * 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.
  4449. * Returns the updated Path2.
  4450. */
  4451. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4452. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4453. if (closed) {
  4454. //Tools.Error("cannot add arcs to closed paths");
  4455. return this;
  4456. }
  4457. var startPoint = this._points[this._points.length - 1];
  4458. var midPoint = new Vector2(midX, midY);
  4459. var endPoint = new Vector2(endX, endY);
  4460. var arc = new Arc2(startPoint, midPoint, endPoint);
  4461. var increment = arc.angle.radians() / numberOfSegments;
  4462. if (arc.orientation === Orientation.CW)
  4463. increment *= -1;
  4464. var currentAngle = arc.startAngle.radians() + increment;
  4465. for (var i = 0; i < numberOfSegments; i++) {
  4466. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4467. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4468. this.addLineTo(x, y);
  4469. currentAngle += increment;
  4470. }
  4471. return this;
  4472. };
  4473. /**
  4474. * Closes the Path2.
  4475. * Returns the Path2.
  4476. */
  4477. Path2.prototype.close = function () {
  4478. this.closed = true;
  4479. return this;
  4480. };
  4481. /**
  4482. * Returns the Path2 total length (float).
  4483. */
  4484. Path2.prototype.length = function () {
  4485. var result = this._length;
  4486. if (!this.closed) {
  4487. var lastPoint = this._points[this._points.length - 1];
  4488. var firstPoint = this._points[0];
  4489. result += (firstPoint.subtract(lastPoint).length());
  4490. }
  4491. return result;
  4492. };
  4493. /**
  4494. * Returns the Path2 internal array of points.
  4495. */
  4496. Path2.prototype.getPoints = function () {
  4497. return this._points;
  4498. };
  4499. /**
  4500. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4501. */
  4502. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4503. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4504. //Tools.Error("normalized length position should be between 0 and 1.");
  4505. return Vector2.Zero();
  4506. }
  4507. var lengthPosition = normalizedLengthPosition * this.length();
  4508. var previousOffset = 0;
  4509. for (var i = 0; i < this._points.length; i++) {
  4510. var j = (i + 1) % this._points.length;
  4511. var a = this._points[i];
  4512. var b = this._points[j];
  4513. var bToA = b.subtract(a);
  4514. var nextOffset = (bToA.length() + previousOffset);
  4515. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4516. var dir = bToA.normalize();
  4517. var localOffset = lengthPosition - previousOffset;
  4518. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4519. }
  4520. previousOffset = nextOffset;
  4521. }
  4522. //Tools.Error("internal error");
  4523. return Vector2.Zero();
  4524. };
  4525. /**
  4526. * Returns a new Path2 starting at the coordinates (x, y).
  4527. */
  4528. Path2.StartingAt = function (x, y) {
  4529. return new Path2(x, y);
  4530. };
  4531. return Path2;
  4532. }());
  4533. BABYLON.Path2 = Path2;
  4534. var Path3D = /** @class */ (function () {
  4535. /**
  4536. * new Path3D(path, normal, raw)
  4537. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4538. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4539. * path : an array of Vector3, the curve axis of the Path3D
  4540. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4541. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4542. */
  4543. function Path3D(path, firstNormal, raw) {
  4544. if (firstNormal === void 0) { firstNormal = null; }
  4545. this.path = path;
  4546. this._curve = new Array();
  4547. this._distances = new Array();
  4548. this._tangents = new Array();
  4549. this._normals = new Array();
  4550. this._binormals = new Array();
  4551. for (var p = 0; p < path.length; p++) {
  4552. this._curve[p] = path[p].clone(); // hard copy
  4553. }
  4554. this._raw = raw || false;
  4555. this._compute(firstNormal);
  4556. }
  4557. /**
  4558. * Returns the Path3D array of successive Vector3 designing its curve.
  4559. */
  4560. Path3D.prototype.getCurve = function () {
  4561. return this._curve;
  4562. };
  4563. /**
  4564. * Returns an array populated with tangent vectors on each Path3D curve point.
  4565. */
  4566. Path3D.prototype.getTangents = function () {
  4567. return this._tangents;
  4568. };
  4569. /**
  4570. * Returns an array populated with normal vectors on each Path3D curve point.
  4571. */
  4572. Path3D.prototype.getNormals = function () {
  4573. return this._normals;
  4574. };
  4575. /**
  4576. * Returns an array populated with binormal vectors on each Path3D curve point.
  4577. */
  4578. Path3D.prototype.getBinormals = function () {
  4579. return this._binormals;
  4580. };
  4581. /**
  4582. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4583. */
  4584. Path3D.prototype.getDistances = function () {
  4585. return this._distances;
  4586. };
  4587. /**
  4588. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4589. * Returns the same object updated.
  4590. */
  4591. Path3D.prototype.update = function (path, firstNormal) {
  4592. if (firstNormal === void 0) { firstNormal = null; }
  4593. for (var p = 0; p < path.length; p++) {
  4594. this._curve[p].x = path[p].x;
  4595. this._curve[p].y = path[p].y;
  4596. this._curve[p].z = path[p].z;
  4597. }
  4598. this._compute(firstNormal);
  4599. return this;
  4600. };
  4601. // private function compute() : computes tangents, normals and binormals
  4602. Path3D.prototype._compute = function (firstNormal) {
  4603. var l = this._curve.length;
  4604. // first and last tangents
  4605. this._tangents[0] = this._getFirstNonNullVector(0);
  4606. if (!this._raw) {
  4607. this._tangents[0].normalize();
  4608. }
  4609. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4610. if (!this._raw) {
  4611. this._tangents[l - 1].normalize();
  4612. }
  4613. // normals and binormals at first point : arbitrary vector with _normalVector()
  4614. var tg0 = this._tangents[0];
  4615. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4616. this._normals[0] = pp0;
  4617. if (!this._raw) {
  4618. this._normals[0].normalize();
  4619. }
  4620. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4621. if (!this._raw) {
  4622. this._binormals[0].normalize();
  4623. }
  4624. this._distances[0] = 0.0;
  4625. // normals and binormals : next points
  4626. var prev; // previous vector (segment)
  4627. var cur; // current vector (segment)
  4628. var curTang; // current tangent
  4629. // previous normal
  4630. var prevBinor; // previous binormal
  4631. for (var i = 1; i < l; i++) {
  4632. // tangents
  4633. prev = this._getLastNonNullVector(i);
  4634. if (i < l - 1) {
  4635. cur = this._getFirstNonNullVector(i);
  4636. this._tangents[i] = prev.add(cur);
  4637. this._tangents[i].normalize();
  4638. }
  4639. this._distances[i] = this._distances[i - 1] + prev.length();
  4640. // normals and binormals
  4641. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4642. curTang = this._tangents[i];
  4643. prevBinor = this._binormals[i - 1];
  4644. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4645. if (!this._raw) {
  4646. this._normals[i].normalize();
  4647. }
  4648. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4649. if (!this._raw) {
  4650. this._binormals[i].normalize();
  4651. }
  4652. }
  4653. };
  4654. // private function getFirstNonNullVector(index)
  4655. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4656. Path3D.prototype._getFirstNonNullVector = function (index) {
  4657. var i = 1;
  4658. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4659. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4660. i++;
  4661. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4662. }
  4663. return nNVector;
  4664. };
  4665. // private function getLastNonNullVector(index)
  4666. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4667. Path3D.prototype._getLastNonNullVector = function (index) {
  4668. var i = 1;
  4669. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4670. while (nLVector.length() === 0 && index > i + 1) {
  4671. i++;
  4672. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4673. }
  4674. return nLVector;
  4675. };
  4676. // private function normalVector(v0, vt, va) :
  4677. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4678. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4679. Path3D.prototype._normalVector = function (v0, vt, va) {
  4680. var normal0;
  4681. var tgl = vt.length();
  4682. if (tgl === 0.0) {
  4683. tgl = 1.0;
  4684. }
  4685. if (va === undefined || va === null) {
  4686. var point;
  4687. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4688. point = new Vector3(0.0, -1.0, 0.0);
  4689. }
  4690. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4691. point = new Vector3(1.0, 0.0, 0.0);
  4692. }
  4693. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4694. point = new Vector3(0.0, 0.0, 1.0);
  4695. }
  4696. else {
  4697. point = Vector3.Zero();
  4698. }
  4699. normal0 = Vector3.Cross(vt, point);
  4700. }
  4701. else {
  4702. normal0 = Vector3.Cross(vt, va);
  4703. Vector3.CrossToRef(normal0, vt, normal0);
  4704. }
  4705. normal0.normalize();
  4706. return normal0;
  4707. };
  4708. return Path3D;
  4709. }());
  4710. BABYLON.Path3D = Path3D;
  4711. var Curve3 = /** @class */ (function () {
  4712. /**
  4713. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4714. * A Curve3 is designed from a series of successive Vector3.
  4715. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4716. */
  4717. function Curve3(points) {
  4718. this._length = 0.0;
  4719. this._points = points;
  4720. this._length = this._computeLength(points);
  4721. }
  4722. /**
  4723. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4724. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4725. * @param v1 (Vector3) the control point
  4726. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4727. * @param nbPoints (integer) the wanted number of points in the curve
  4728. */
  4729. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4730. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4731. var bez = new Array();
  4732. var equation = function (t, val0, val1, val2) {
  4733. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4734. return res;
  4735. };
  4736. for (var i = 0; i <= nbPoints; i++) {
  4737. 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)));
  4738. }
  4739. return new Curve3(bez);
  4740. };
  4741. /**
  4742. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4743. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4744. * @param v1 (Vector3) the first control point
  4745. * @param v2 (Vector3) the second control point
  4746. * @param v3 (Vector3) the end point of the Cubic Bezier
  4747. * @param nbPoints (integer) the wanted number of points in the curve
  4748. */
  4749. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4750. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4751. var bez = new Array();
  4752. var equation = function (t, val0, val1, val2, val3) {
  4753. 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;
  4754. return res;
  4755. };
  4756. for (var i = 0; i <= nbPoints; i++) {
  4757. 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)));
  4758. }
  4759. return new Curve3(bez);
  4760. };
  4761. /**
  4762. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4763. * @param p1 (Vector3) the origin point of the Hermite Spline
  4764. * @param t1 (Vector3) the tangent vector at the origin point
  4765. * @param p2 (Vector3) the end point of the Hermite Spline
  4766. * @param t2 (Vector3) the tangent vector at the end point
  4767. * @param nbPoints (integer) the wanted number of points in the curve
  4768. */
  4769. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4770. var hermite = new Array();
  4771. var step = 1.0 / nbPoints;
  4772. for (var i = 0; i <= nbPoints; i++) {
  4773. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4774. }
  4775. return new Curve3(hermite);
  4776. };
  4777. /**
  4778. * Returns a Curve3 object along a CatmullRom Spline curve :
  4779. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4780. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4781. */
  4782. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4783. var totalPoints = new Array();
  4784. totalPoints.push(points[0].clone());
  4785. Array.prototype.push.apply(totalPoints, points);
  4786. totalPoints.push(points[points.length - 1].clone());
  4787. var catmullRom = new Array();
  4788. var step = 1.0 / nbPoints;
  4789. var amount = 0.0;
  4790. for (var i = 0; i < totalPoints.length - 3; i++) {
  4791. amount = 0;
  4792. for (var c = 0; c < nbPoints; c++) {
  4793. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4794. amount += step;
  4795. }
  4796. }
  4797. i--;
  4798. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4799. return new Curve3(catmullRom);
  4800. };
  4801. /**
  4802. * Returns the Curve3 stored array of successive Vector3
  4803. */
  4804. Curve3.prototype.getPoints = function () {
  4805. return this._points;
  4806. };
  4807. /**
  4808. * Returns the computed length (float) of the curve.
  4809. */
  4810. Curve3.prototype.length = function () {
  4811. return this._length;
  4812. };
  4813. /**
  4814. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4815. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4816. * curveA and curveB keep unchanged.
  4817. */
  4818. Curve3.prototype.continue = function (curve) {
  4819. var lastPoint = this._points[this._points.length - 1];
  4820. var continuedPoints = this._points.slice();
  4821. var curvePoints = curve.getPoints();
  4822. for (var i = 1; i < curvePoints.length; i++) {
  4823. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4824. }
  4825. var continuedCurve = new Curve3(continuedPoints);
  4826. return continuedCurve;
  4827. };
  4828. Curve3.prototype._computeLength = function (path) {
  4829. var l = 0;
  4830. for (var i = 1; i < path.length; i++) {
  4831. l += (path[i].subtract(path[i - 1])).length();
  4832. }
  4833. return l;
  4834. };
  4835. return Curve3;
  4836. }());
  4837. BABYLON.Curve3 = Curve3;
  4838. // Vertex formats
  4839. var PositionNormalVertex = /** @class */ (function () {
  4840. function PositionNormalVertex(position, normal) {
  4841. if (position === void 0) { position = Vector3.Zero(); }
  4842. if (normal === void 0) { normal = Vector3.Up(); }
  4843. this.position = position;
  4844. this.normal = normal;
  4845. }
  4846. PositionNormalVertex.prototype.clone = function () {
  4847. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4848. };
  4849. return PositionNormalVertex;
  4850. }());
  4851. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4852. var PositionNormalTextureVertex = /** @class */ (function () {
  4853. function PositionNormalTextureVertex(position, normal, uv) {
  4854. if (position === void 0) { position = Vector3.Zero(); }
  4855. if (normal === void 0) { normal = Vector3.Up(); }
  4856. if (uv === void 0) { uv = Vector2.Zero(); }
  4857. this.position = position;
  4858. this.normal = normal;
  4859. this.uv = uv;
  4860. }
  4861. PositionNormalTextureVertex.prototype.clone = function () {
  4862. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4863. };
  4864. return PositionNormalTextureVertex;
  4865. }());
  4866. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4867. // Temporary pre-allocated objects for engine internal use
  4868. // usage in any internal function :
  4869. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4870. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4871. var Tmp = /** @class */ (function () {
  4872. function Tmp() {
  4873. }
  4874. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4875. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4876. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4877. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4878. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4879. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4880. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4881. Matrix.Zero(), Matrix.Zero(),
  4882. Matrix.Zero(), Matrix.Zero(),
  4883. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4884. return Tmp;
  4885. }());
  4886. BABYLON.Tmp = Tmp;
  4887. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4888. var MathTmp = /** @class */ (function () {
  4889. function MathTmp() {
  4890. }
  4891. MathTmp.Vector3 = [Vector3.Zero()];
  4892. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4893. MathTmp.Quaternion = [Quaternion.Zero()];
  4894. return MathTmp;
  4895. }());
  4896. })(BABYLON || (BABYLON = {}));
  4897. //# sourceMappingURL=babylon.math.js.map
  4898. var BABYLON;
  4899. (function (BABYLON) {
  4900. var Scalar = /** @class */ (function () {
  4901. function Scalar() {
  4902. }
  4903. /**
  4904. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4905. */
  4906. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4907. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4908. var num = a - b;
  4909. return -epsilon <= num && num <= epsilon;
  4910. };
  4911. /**
  4912. * Returns a string : the upper case translation of the number i to hexadecimal.
  4913. */
  4914. Scalar.ToHex = function (i) {
  4915. var str = i.toString(16);
  4916. if (i <= 15) {
  4917. return ("0" + str).toUpperCase();
  4918. }
  4919. return str.toUpperCase();
  4920. };
  4921. /**
  4922. * Returns -1 if value is negative and +1 is value is positive.
  4923. * Returns the value itself if it's equal to zero.
  4924. */
  4925. Scalar.Sign = function (value) {
  4926. value = +value; // convert to a number
  4927. if (value === 0 || isNaN(value))
  4928. return value;
  4929. return value > 0 ? 1 : -1;
  4930. };
  4931. /**
  4932. * Returns the value itself if it's between min and max.
  4933. * Returns min if the value is lower than min.
  4934. * Returns max if the value is greater than max.
  4935. */
  4936. Scalar.Clamp = function (value, min, max) {
  4937. if (min === void 0) { min = 0; }
  4938. if (max === void 0) { max = 1; }
  4939. return Math.min(max, Math.max(min, value));
  4940. };
  4941. /**
  4942. * Returns the log2 of value.
  4943. */
  4944. Scalar.Log2 = function (value) {
  4945. return Math.log(value) * Math.LOG2E;
  4946. };
  4947. /**
  4948. * Loops the value, so that it is never larger than length and never smaller than 0.
  4949. *
  4950. * This is similar to the modulo operator but it works with floating point numbers.
  4951. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4952. * With t = 5 and length = 2.5, the result would be 0.0.
  4953. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4954. */
  4955. Scalar.Repeat = function (value, length) {
  4956. return value - Math.floor(value / length) * length;
  4957. };
  4958. /**
  4959. * Normalize the value between 0.0 and 1.0 using min and max values
  4960. */
  4961. Scalar.Normalize = function (value, min, max) {
  4962. return (value - min) / (max - min);
  4963. };
  4964. /**
  4965. * Denormalize the value from 0.0 and 1.0 using min and max values
  4966. */
  4967. Scalar.Denormalize = function (normalized, min, max) {
  4968. return (normalized * (max - min) + min);
  4969. };
  4970. /**
  4971. * Calculates the shortest difference between two given angles given in degrees.
  4972. */
  4973. Scalar.DeltaAngle = function (current, target) {
  4974. var num = Scalar.Repeat(target - current, 360.0);
  4975. if (num > 180.0) {
  4976. num -= 360.0;
  4977. }
  4978. return num;
  4979. };
  4980. /**
  4981. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4982. *
  4983. * The returned value will move back and forth between 0 and length
  4984. */
  4985. Scalar.PingPong = function (tx, length) {
  4986. var t = Scalar.Repeat(tx, length * 2.0);
  4987. return length - Math.abs(t - length);
  4988. };
  4989. /**
  4990. * Interpolates between min and max with smoothing at the limits.
  4991. *
  4992. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4993. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4994. */
  4995. Scalar.SmoothStep = function (from, to, tx) {
  4996. var t = Scalar.Clamp(tx);
  4997. t = -2.0 * t * t * t + 3.0 * t * t;
  4998. return to * t + from * (1.0 - t);
  4999. };
  5000. /**
  5001. * Moves a value current towards target.
  5002. *
  5003. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5004. * Negative values of maxDelta pushes the value away from target.
  5005. */
  5006. Scalar.MoveTowards = function (current, target, maxDelta) {
  5007. var result = 0;
  5008. if (Math.abs(target - current) <= maxDelta) {
  5009. result = target;
  5010. }
  5011. else {
  5012. result = current + Scalar.Sign(target - current) * maxDelta;
  5013. }
  5014. return result;
  5015. };
  5016. /**
  5017. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5018. *
  5019. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5020. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5021. */
  5022. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5023. var num = Scalar.DeltaAngle(current, target);
  5024. var result = 0;
  5025. if (-maxDelta < num && num < maxDelta) {
  5026. result = target;
  5027. }
  5028. else {
  5029. target = current + num;
  5030. result = Scalar.MoveTowards(current, target, maxDelta);
  5031. }
  5032. return result;
  5033. };
  5034. /**
  5035. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5036. */
  5037. Scalar.Lerp = function (start, end, amount) {
  5038. return start + ((end - start) * amount);
  5039. };
  5040. /**
  5041. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5042. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5043. */
  5044. Scalar.LerpAngle = function (start, end, amount) {
  5045. var num = Scalar.Repeat(end - start, 360.0);
  5046. if (num > 180.0) {
  5047. num -= 360.0;
  5048. }
  5049. return start + num * Scalar.Clamp(amount);
  5050. };
  5051. /**
  5052. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5053. */
  5054. Scalar.InverseLerp = function (a, b, value) {
  5055. var result = 0;
  5056. if (a != b) {
  5057. result = Scalar.Clamp((value - a) / (b - a));
  5058. }
  5059. else {
  5060. result = 0.0;
  5061. }
  5062. return result;
  5063. };
  5064. /**
  5065. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5066. */
  5067. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5068. var squared = amount * amount;
  5069. var cubed = amount * squared;
  5070. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5071. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5072. var part3 = (cubed - (2.0 * squared)) + amount;
  5073. var part4 = cubed - squared;
  5074. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5075. };
  5076. /**
  5077. * Returns a random float number between and min and max values
  5078. */
  5079. Scalar.RandomRange = function (min, max) {
  5080. if (min === max)
  5081. return min;
  5082. return ((Math.random() * (max - min)) + min);
  5083. };
  5084. /**
  5085. * This function returns percentage of a number in a given range.
  5086. *
  5087. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5088. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5089. */
  5090. Scalar.RangeToPercent = function (number, min, max) {
  5091. return ((number - min) / (max - min));
  5092. };
  5093. /**
  5094. * This function returns number that corresponds to the percentage in a given range.
  5095. *
  5096. * PercentToRange(0.34,0,100) will return 34.
  5097. */
  5098. Scalar.PercentToRange = function (percent, min, max) {
  5099. return ((max - min) * percent + min);
  5100. };
  5101. return Scalar;
  5102. }());
  5103. BABYLON.Scalar = Scalar;
  5104. })(BABYLON || (BABYLON = {}));
  5105. //# sourceMappingURL=babylon.math.scalar.js.map
  5106. //# sourceMappingURL=babylon.mixins.js.map
  5107. var BABYLON;
  5108. (function (BABYLON) {
  5109. var __decoratorInitialStore = {};
  5110. var __mergedStore = {};
  5111. var _copySource = function (creationFunction, source, instanciate) {
  5112. var destination = creationFunction();
  5113. // Tags
  5114. if (BABYLON.Tags) {
  5115. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5116. }
  5117. var classStore = getMergedStore(destination);
  5118. // Properties
  5119. for (var property in classStore) {
  5120. var propertyDescriptor = classStore[property];
  5121. var sourceProperty = source[property];
  5122. var propertyType = propertyDescriptor.type;
  5123. if (sourceProperty !== undefined && sourceProperty !== null) {
  5124. switch (propertyType) {
  5125. case 0: // Value
  5126. case 6:// Mesh reference
  5127. destination[property] = sourceProperty;
  5128. break;
  5129. case 1:// Texture
  5130. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5131. break;
  5132. case 2: // Color3
  5133. case 3: // FresnelParameters
  5134. case 4: // Vector2
  5135. case 5: // Vector3
  5136. case 7:// Color Curves
  5137. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5138. break;
  5139. }
  5140. }
  5141. }
  5142. return destination;
  5143. };
  5144. function getDirectStore(target) {
  5145. var classKey = target.getClassName();
  5146. if (!__decoratorInitialStore[classKey]) {
  5147. __decoratorInitialStore[classKey] = {};
  5148. }
  5149. return __decoratorInitialStore[classKey];
  5150. }
  5151. /**
  5152. * Return the list of properties flagged as serializable
  5153. * @param target: host object
  5154. */
  5155. function getMergedStore(target) {
  5156. var classKey = target.getClassName();
  5157. if (__mergedStore[classKey]) {
  5158. return __mergedStore[classKey];
  5159. }
  5160. __mergedStore[classKey] = {};
  5161. var store = __mergedStore[classKey];
  5162. var currentTarget = target;
  5163. var currentKey = classKey;
  5164. while (currentKey) {
  5165. var initialStore = __decoratorInitialStore[currentKey];
  5166. for (var property in initialStore) {
  5167. store[property] = initialStore[property];
  5168. }
  5169. var parent_1 = void 0;
  5170. var done = false;
  5171. do {
  5172. parent_1 = Object.getPrototypeOf(currentTarget);
  5173. if (!parent_1.getClassName) {
  5174. done = true;
  5175. break;
  5176. }
  5177. if (parent_1.getClassName() !== currentKey) {
  5178. break;
  5179. }
  5180. currentTarget = parent_1;
  5181. } while (parent_1);
  5182. if (done) {
  5183. break;
  5184. }
  5185. currentKey = parent_1.getClassName();
  5186. currentTarget = parent_1;
  5187. }
  5188. return store;
  5189. }
  5190. function generateSerializableMember(type, sourceName) {
  5191. return function (target, propertyKey) {
  5192. var classStore = getDirectStore(target);
  5193. if (!classStore[propertyKey]) {
  5194. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5195. }
  5196. };
  5197. }
  5198. function generateExpandMember(setCallback, targetKey) {
  5199. if (targetKey === void 0) { targetKey = null; }
  5200. return function (target, propertyKey) {
  5201. var key = targetKey || ("_" + propertyKey);
  5202. Object.defineProperty(target, propertyKey, {
  5203. get: function () {
  5204. return this[key];
  5205. },
  5206. set: function (value) {
  5207. if (this[key] === value) {
  5208. return;
  5209. }
  5210. this[key] = value;
  5211. target[setCallback].apply(this);
  5212. },
  5213. enumerable: true,
  5214. configurable: true
  5215. });
  5216. };
  5217. }
  5218. function expandToProperty(callback, targetKey) {
  5219. if (targetKey === void 0) { targetKey = null; }
  5220. return generateExpandMember(callback, targetKey);
  5221. }
  5222. BABYLON.expandToProperty = expandToProperty;
  5223. function serialize(sourceName) {
  5224. return generateSerializableMember(0, sourceName); // value member
  5225. }
  5226. BABYLON.serialize = serialize;
  5227. function serializeAsTexture(sourceName) {
  5228. return generateSerializableMember(1, sourceName); // texture member
  5229. }
  5230. BABYLON.serializeAsTexture = serializeAsTexture;
  5231. function serializeAsColor3(sourceName) {
  5232. return generateSerializableMember(2, sourceName); // color3 member
  5233. }
  5234. BABYLON.serializeAsColor3 = serializeAsColor3;
  5235. function serializeAsFresnelParameters(sourceName) {
  5236. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5237. }
  5238. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5239. function serializeAsVector2(sourceName) {
  5240. return generateSerializableMember(4, sourceName); // vector2 member
  5241. }
  5242. BABYLON.serializeAsVector2 = serializeAsVector2;
  5243. function serializeAsVector3(sourceName) {
  5244. return generateSerializableMember(5, sourceName); // vector3 member
  5245. }
  5246. BABYLON.serializeAsVector3 = serializeAsVector3;
  5247. function serializeAsMeshReference(sourceName) {
  5248. return generateSerializableMember(6, sourceName); // mesh reference member
  5249. }
  5250. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5251. function serializeAsColorCurves(sourceName) {
  5252. return generateSerializableMember(7, sourceName); // color curves
  5253. }
  5254. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5255. function serializeAsColor4(sourceName) {
  5256. return generateSerializableMember(8, sourceName); // color 4
  5257. }
  5258. BABYLON.serializeAsColor4 = serializeAsColor4;
  5259. function serializeAsImageProcessingConfiguration(sourceName) {
  5260. return generateSerializableMember(9, sourceName); // image processing
  5261. }
  5262. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5263. var SerializationHelper = /** @class */ (function () {
  5264. function SerializationHelper() {
  5265. }
  5266. SerializationHelper.Serialize = function (entity, serializationObject) {
  5267. if (!serializationObject) {
  5268. serializationObject = {};
  5269. }
  5270. // Tags
  5271. if (BABYLON.Tags) {
  5272. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5273. }
  5274. var serializedProperties = getMergedStore(entity);
  5275. // Properties
  5276. for (var property in serializedProperties) {
  5277. var propertyDescriptor = serializedProperties[property];
  5278. var targetPropertyName = propertyDescriptor.sourceName || property;
  5279. var propertyType = propertyDescriptor.type;
  5280. var sourceProperty = entity[property];
  5281. if (sourceProperty !== undefined && sourceProperty !== null) {
  5282. switch (propertyType) {
  5283. case 0:// Value
  5284. serializationObject[targetPropertyName] = sourceProperty;
  5285. break;
  5286. case 1:// Texture
  5287. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5288. break;
  5289. case 2:// Color3
  5290. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5291. break;
  5292. case 3:// FresnelParameters
  5293. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5294. break;
  5295. case 4:// Vector2
  5296. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5297. break;
  5298. case 5:// Vector3
  5299. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5300. break;
  5301. case 6:// Mesh reference
  5302. serializationObject[targetPropertyName] = sourceProperty.id;
  5303. break;
  5304. case 7:// Color Curves
  5305. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5306. break;
  5307. case 8:// Color 4
  5308. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5309. break;
  5310. case 9:// Image Processing
  5311. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5312. break;
  5313. }
  5314. }
  5315. }
  5316. return serializationObject;
  5317. };
  5318. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5319. if (rootUrl === void 0) { rootUrl = null; }
  5320. var destination = creationFunction();
  5321. if (!rootUrl) {
  5322. rootUrl = "";
  5323. }
  5324. // Tags
  5325. if (BABYLON.Tags) {
  5326. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5327. }
  5328. var classStore = getMergedStore(destination);
  5329. // Properties
  5330. for (var property in classStore) {
  5331. var propertyDescriptor = classStore[property];
  5332. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5333. var propertyType = propertyDescriptor.type;
  5334. if (sourceProperty !== undefined && sourceProperty !== null) {
  5335. var dest = destination;
  5336. switch (propertyType) {
  5337. case 0:// Value
  5338. dest[property] = sourceProperty;
  5339. break;
  5340. case 1:// Texture
  5341. if (scene) {
  5342. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5343. }
  5344. break;
  5345. case 2:// Color3
  5346. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5347. break;
  5348. case 3:// FresnelParameters
  5349. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5350. break;
  5351. case 4:// Vector2
  5352. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5353. break;
  5354. case 5:// Vector3
  5355. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5356. break;
  5357. case 6:// Mesh reference
  5358. if (scene) {
  5359. dest[property] = scene.getLastMeshByID(sourceProperty);
  5360. }
  5361. break;
  5362. case 7:// Color Curves
  5363. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5364. break;
  5365. case 8:// Color 4
  5366. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5367. break;
  5368. case 9:// Image Processing
  5369. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5370. break;
  5371. }
  5372. }
  5373. }
  5374. return destination;
  5375. };
  5376. SerializationHelper.Clone = function (creationFunction, source) {
  5377. return _copySource(creationFunction, source, false);
  5378. };
  5379. SerializationHelper.Instanciate = function (creationFunction, source) {
  5380. return _copySource(creationFunction, source, true);
  5381. };
  5382. return SerializationHelper;
  5383. }());
  5384. BABYLON.SerializationHelper = SerializationHelper;
  5385. })(BABYLON || (BABYLON = {}));
  5386. //# sourceMappingURL=babylon.decorators.js.map
  5387. var BABYLON;
  5388. (function (BABYLON) {
  5389. /**
  5390. * A class serves as a medium between the observable and its observers
  5391. */
  5392. var EventState = /** @class */ (function () {
  5393. /**
  5394. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5395. */
  5396. function EventState(mask, skipNextObservers, target, currentTarget) {
  5397. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5398. this.initalize(mask, skipNextObservers, target, currentTarget);
  5399. }
  5400. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5401. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5402. this.mask = mask;
  5403. this.skipNextObservers = skipNextObservers;
  5404. this.target = target;
  5405. this.currentTarget = currentTarget;
  5406. return this;
  5407. };
  5408. return EventState;
  5409. }());
  5410. BABYLON.EventState = EventState;
  5411. /**
  5412. * Represent an Observer registered to a given Observable object.
  5413. */
  5414. var Observer = /** @class */ (function () {
  5415. function Observer(callback, mask, scope) {
  5416. if (scope === void 0) { scope = null; }
  5417. this.callback = callback;
  5418. this.mask = mask;
  5419. this.scope = scope;
  5420. }
  5421. return Observer;
  5422. }());
  5423. BABYLON.Observer = Observer;
  5424. /**
  5425. * Represent a list of observers registered to multiple Observables object.
  5426. */
  5427. var MultiObserver = /** @class */ (function () {
  5428. function MultiObserver() {
  5429. }
  5430. MultiObserver.prototype.dispose = function () {
  5431. if (this._observers && this._observables) {
  5432. for (var index = 0; index < this._observers.length; index++) {
  5433. this._observables[index].remove(this._observers[index]);
  5434. }
  5435. }
  5436. this._observers = null;
  5437. this._observables = null;
  5438. };
  5439. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5440. if (mask === void 0) { mask = -1; }
  5441. if (scope === void 0) { scope = null; }
  5442. var result = new MultiObserver();
  5443. result._observers = new Array();
  5444. result._observables = observables;
  5445. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5446. var observable = observables_1[_i];
  5447. var observer = observable.add(callback, mask, false, scope);
  5448. if (observer) {
  5449. result._observers.push(observer);
  5450. }
  5451. }
  5452. return result;
  5453. };
  5454. return MultiObserver;
  5455. }());
  5456. BABYLON.MultiObserver = MultiObserver;
  5457. /**
  5458. * The Observable class is a simple implementation of the Observable pattern.
  5459. * 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.
  5460. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5461. * 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).
  5462. * 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.
  5463. */
  5464. var Observable = /** @class */ (function () {
  5465. function Observable(onObserverAdded) {
  5466. this._observers = new Array();
  5467. this._eventState = new EventState(0);
  5468. if (onObserverAdded) {
  5469. this._onObserverAdded = onObserverAdded;
  5470. }
  5471. }
  5472. /**
  5473. * Create a new Observer with the specified callback
  5474. * @param callback the callback that will be executed for that Observer
  5475. * @param mask the mask used to filter observers
  5476. * @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.
  5477. * @param scope optional scope for the callback to be called from
  5478. */
  5479. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5480. if (mask === void 0) { mask = -1; }
  5481. if (insertFirst === void 0) { insertFirst = false; }
  5482. if (scope === void 0) { scope = null; }
  5483. if (!callback) {
  5484. return null;
  5485. }
  5486. var observer = new Observer(callback, mask, scope);
  5487. if (insertFirst) {
  5488. this._observers.unshift(observer);
  5489. }
  5490. else {
  5491. this._observers.push(observer);
  5492. }
  5493. if (this._onObserverAdded) {
  5494. this._onObserverAdded(observer);
  5495. }
  5496. return observer;
  5497. };
  5498. /**
  5499. * Remove an Observer from the Observable object
  5500. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5501. */
  5502. Observable.prototype.remove = function (observer) {
  5503. if (!observer) {
  5504. return false;
  5505. }
  5506. var index = this._observers.indexOf(observer);
  5507. if (index !== -1) {
  5508. this._observers.splice(index, 1);
  5509. return true;
  5510. }
  5511. return false;
  5512. };
  5513. /**
  5514. * Remove a callback from the Observable object
  5515. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5516. */
  5517. Observable.prototype.removeCallback = function (callback) {
  5518. for (var index = 0; index < this._observers.length; index++) {
  5519. if (this._observers[index].callback === callback) {
  5520. this._observers.splice(index, 1);
  5521. return true;
  5522. }
  5523. }
  5524. return false;
  5525. };
  5526. /**
  5527. * Notify all Observers by calling their respective callback with the given data
  5528. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5529. * @param eventData
  5530. * @param mask
  5531. */
  5532. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5533. if (mask === void 0) { mask = -1; }
  5534. if (!this._observers.length) {
  5535. return true;
  5536. }
  5537. var state = this._eventState;
  5538. state.mask = mask;
  5539. state.target = target;
  5540. state.currentTarget = currentTarget;
  5541. state.skipNextObservers = false;
  5542. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5543. var obs = _a[_i];
  5544. if (obs.mask & mask) {
  5545. if (obs.scope) {
  5546. obs.callback.apply(obs.scope, [eventData, state]);
  5547. }
  5548. else {
  5549. obs.callback(eventData, state);
  5550. }
  5551. }
  5552. if (state.skipNextObservers) {
  5553. return false;
  5554. }
  5555. }
  5556. return true;
  5557. };
  5558. /**
  5559. * Notify a specific observer
  5560. * @param eventData
  5561. * @param mask
  5562. */
  5563. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5564. if (mask === void 0) { mask = -1; }
  5565. var state = this._eventState;
  5566. state.mask = mask;
  5567. state.skipNextObservers = false;
  5568. observer.callback(eventData, state);
  5569. };
  5570. /**
  5571. * return true is the Observable has at least one Observer registered
  5572. */
  5573. Observable.prototype.hasObservers = function () {
  5574. return this._observers.length > 0;
  5575. };
  5576. /**
  5577. * Clear the list of observers
  5578. */
  5579. Observable.prototype.clear = function () {
  5580. this._observers = new Array();
  5581. this._onObserverAdded = null;
  5582. };
  5583. /**
  5584. * Clone the current observable
  5585. */
  5586. Observable.prototype.clone = function () {
  5587. var result = new Observable();
  5588. result._observers = this._observers.slice(0);
  5589. return result;
  5590. };
  5591. /**
  5592. * Does this observable handles observer registered with a given mask
  5593. * @param {number} trigger - the mask to be tested
  5594. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5595. **/
  5596. Observable.prototype.hasSpecificMask = function (mask) {
  5597. if (mask === void 0) { mask = -1; }
  5598. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5599. var obs = _a[_i];
  5600. if (obs.mask & mask || obs.mask === mask) {
  5601. return true;
  5602. }
  5603. }
  5604. return false;
  5605. };
  5606. return Observable;
  5607. }());
  5608. BABYLON.Observable = Observable;
  5609. })(BABYLON || (BABYLON = {}));
  5610. //# sourceMappingURL=babylon.observable.js.map
  5611. var BABYLON;
  5612. (function (BABYLON) {
  5613. var SmartArray = /** @class */ (function () {
  5614. function SmartArray(capacity) {
  5615. this.length = 0;
  5616. this.data = new Array(capacity);
  5617. this._id = SmartArray._GlobalId++;
  5618. }
  5619. SmartArray.prototype.push = function (value) {
  5620. this.data[this.length++] = value;
  5621. if (this.length > this.data.length) {
  5622. this.data.length *= 2;
  5623. }
  5624. };
  5625. SmartArray.prototype.forEach = function (func) {
  5626. for (var index = 0; index < this.length; index++) {
  5627. func(this.data[index]);
  5628. }
  5629. };
  5630. SmartArray.prototype.sort = function (compareFn) {
  5631. this.data.sort(compareFn);
  5632. };
  5633. SmartArray.prototype.reset = function () {
  5634. this.length = 0;
  5635. };
  5636. SmartArray.prototype.dispose = function () {
  5637. this.reset();
  5638. if (this.data) {
  5639. this.data.length = 0;
  5640. this.data = [];
  5641. }
  5642. };
  5643. SmartArray.prototype.concat = function (array) {
  5644. if (array.length === 0) {
  5645. return;
  5646. }
  5647. if (this.length + array.length > this.data.length) {
  5648. this.data.length = (this.length + array.length) * 2;
  5649. }
  5650. for (var index = 0; index < array.length; index++) {
  5651. this.data[this.length++] = (array.data || array)[index];
  5652. }
  5653. };
  5654. SmartArray.prototype.indexOf = function (value) {
  5655. var position = this.data.indexOf(value);
  5656. if (position >= this.length) {
  5657. return -1;
  5658. }
  5659. return position;
  5660. };
  5661. SmartArray.prototype.contains = function (value) {
  5662. return this.data.indexOf(value) !== -1;
  5663. };
  5664. // Statics
  5665. SmartArray._GlobalId = 0;
  5666. return SmartArray;
  5667. }());
  5668. BABYLON.SmartArray = SmartArray;
  5669. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5670. __extends(SmartArrayNoDuplicate, _super);
  5671. function SmartArrayNoDuplicate() {
  5672. var _this = _super !== null && _super.apply(this, arguments) || this;
  5673. _this._duplicateId = 0;
  5674. return _this;
  5675. }
  5676. SmartArrayNoDuplicate.prototype.push = function (value) {
  5677. _super.prototype.push.call(this, value);
  5678. if (!value.__smartArrayFlags) {
  5679. value.__smartArrayFlags = {};
  5680. }
  5681. value.__smartArrayFlags[this._id] = this._duplicateId;
  5682. };
  5683. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5684. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5685. return false;
  5686. }
  5687. this.push(value);
  5688. return true;
  5689. };
  5690. SmartArrayNoDuplicate.prototype.reset = function () {
  5691. _super.prototype.reset.call(this);
  5692. this._duplicateId++;
  5693. };
  5694. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5695. if (array.length === 0) {
  5696. return;
  5697. }
  5698. if (this.length + array.length > this.data.length) {
  5699. this.data.length = (this.length + array.length) * 2;
  5700. }
  5701. for (var index = 0; index < array.length; index++) {
  5702. var item = (array.data || array)[index];
  5703. this.pushNoDuplicate(item);
  5704. }
  5705. };
  5706. return SmartArrayNoDuplicate;
  5707. }(SmartArray));
  5708. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5709. })(BABYLON || (BABYLON = {}));
  5710. //# sourceMappingURL=babylon.smartArray.js.map
  5711. var BABYLON;
  5712. (function (BABYLON) {
  5713. // Screenshots
  5714. var screenshotCanvas;
  5715. var cloneValue = function (source, destinationObject) {
  5716. if (!source)
  5717. return null;
  5718. if (source instanceof BABYLON.Mesh) {
  5719. return null;
  5720. }
  5721. if (source instanceof BABYLON.SubMesh) {
  5722. return source.clone(destinationObject);
  5723. }
  5724. else if (source.clone) {
  5725. return source.clone();
  5726. }
  5727. return null;
  5728. };
  5729. var Tools = /** @class */ (function () {
  5730. function Tools() {
  5731. }
  5732. ;
  5733. /**
  5734. * Interpolates between a and b via alpha
  5735. * @param a The lower value (returned when alpha = 0)
  5736. * @param b The upper value (returned when alpha = 1)
  5737. * @param alpha The interpolation-factor
  5738. * @return The mixed value
  5739. */
  5740. Tools.Mix = function (a, b, alpha) {
  5741. return a * (1 - alpha) + b * alpha;
  5742. };
  5743. Tools.Instantiate = function (className) {
  5744. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5745. return Tools.RegisteredExternalClasses[className];
  5746. }
  5747. var arr = className.split(".");
  5748. var fn = (window || this);
  5749. for (var i = 0, len = arr.length; i < len; i++) {
  5750. fn = fn[arr[i]];
  5751. }
  5752. if (typeof fn !== "function") {
  5753. return null;
  5754. }
  5755. return fn;
  5756. };
  5757. Tools.SetImmediate = function (action) {
  5758. if (window.setImmediate) {
  5759. window.setImmediate(action);
  5760. }
  5761. else {
  5762. setTimeout(action, 1);
  5763. }
  5764. };
  5765. Tools.IsExponentOfTwo = function (value) {
  5766. var count = 1;
  5767. do {
  5768. count *= 2;
  5769. } while (count < value);
  5770. return count === value;
  5771. };
  5772. /**
  5773. * Find the next highest power of two.
  5774. * @param x Number to start search from.
  5775. * @return Next highest power of two.
  5776. */
  5777. Tools.CeilingPOT = function (x) {
  5778. x--;
  5779. x |= x >> 1;
  5780. x |= x >> 2;
  5781. x |= x >> 4;
  5782. x |= x >> 8;
  5783. x |= x >> 16;
  5784. x++;
  5785. return x;
  5786. };
  5787. /**
  5788. * Find the next lowest power of two.
  5789. * @param x Number to start search from.
  5790. * @return Next lowest power of two.
  5791. */
  5792. Tools.FloorPOT = function (x) {
  5793. x = x | (x >> 1);
  5794. x = x | (x >> 2);
  5795. x = x | (x >> 4);
  5796. x = x | (x >> 8);
  5797. x = x | (x >> 16);
  5798. return x - (x >> 1);
  5799. };
  5800. /**
  5801. * Find the nearest power of two.
  5802. * @param x Number to start search from.
  5803. * @return Next nearest power of two.
  5804. */
  5805. Tools.NearestPOT = function (x) {
  5806. var c = Tools.CeilingPOT(x);
  5807. var f = Tools.FloorPOT(x);
  5808. return (c - x) > (x - f) ? f : c;
  5809. };
  5810. Tools.GetExponentOfTwo = function (value, max, mode) {
  5811. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5812. var pot;
  5813. switch (mode) {
  5814. case BABYLON.Engine.SCALEMODE_FLOOR:
  5815. pot = Tools.FloorPOT(value);
  5816. break;
  5817. case BABYLON.Engine.SCALEMODE_NEAREST:
  5818. pot = Tools.NearestPOT(value);
  5819. break;
  5820. case BABYLON.Engine.SCALEMODE_CEILING:
  5821. default:
  5822. pot = Tools.CeilingPOT(value);
  5823. break;
  5824. }
  5825. return Math.min(pot, max);
  5826. };
  5827. Tools.GetFilename = function (path) {
  5828. var index = path.lastIndexOf("/");
  5829. if (index < 0)
  5830. return path;
  5831. return path.substring(index + 1);
  5832. };
  5833. Tools.GetDOMTextContent = function (element) {
  5834. var result = "";
  5835. var child = element.firstChild;
  5836. while (child) {
  5837. if (child.nodeType === 3) {
  5838. result += child.textContent;
  5839. }
  5840. child = child.nextSibling;
  5841. }
  5842. return result;
  5843. };
  5844. Tools.ToDegrees = function (angle) {
  5845. return angle * 180 / Math.PI;
  5846. };
  5847. Tools.ToRadians = function (angle) {
  5848. return angle * Math.PI / 180;
  5849. };
  5850. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5851. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5852. var output = "";
  5853. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5854. var i = 0;
  5855. var bytes = new Uint8Array(buffer);
  5856. while (i < bytes.length) {
  5857. chr1 = bytes[i++];
  5858. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5859. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5860. enc1 = chr1 >> 2;
  5861. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5862. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5863. enc4 = chr3 & 63;
  5864. if (isNaN(chr2)) {
  5865. enc3 = enc4 = 64;
  5866. }
  5867. else if (isNaN(chr3)) {
  5868. enc4 = 64;
  5869. }
  5870. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5871. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5872. }
  5873. return "data:image/png;base64," + output;
  5874. };
  5875. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5876. if (bias === void 0) { bias = null; }
  5877. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5878. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5879. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5880. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5881. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5882. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5883. }
  5884. if (bias) {
  5885. minimum.x -= minimum.x * bias.x + bias.y;
  5886. minimum.y -= minimum.y * bias.x + bias.y;
  5887. minimum.z -= minimum.z * bias.x + bias.y;
  5888. maximum.x += maximum.x * bias.x + bias.y;
  5889. maximum.y += maximum.y * bias.x + bias.y;
  5890. maximum.z += maximum.z * bias.x + bias.y;
  5891. }
  5892. return {
  5893. minimum: minimum,
  5894. maximum: maximum
  5895. };
  5896. };
  5897. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5898. if (bias === void 0) { bias = null; }
  5899. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5900. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5901. if (!stride) {
  5902. stride = 3;
  5903. }
  5904. for (var index = start; index < start + count; index++) {
  5905. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5906. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5907. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5908. }
  5909. if (bias) {
  5910. minimum.x -= minimum.x * bias.x + bias.y;
  5911. minimum.y -= minimum.y * bias.x + bias.y;
  5912. minimum.z -= minimum.z * bias.x + bias.y;
  5913. maximum.x += maximum.x * bias.x + bias.y;
  5914. maximum.y += maximum.y * bias.x + bias.y;
  5915. maximum.z += maximum.z * bias.x + bias.y;
  5916. }
  5917. return {
  5918. minimum: minimum,
  5919. maximum: maximum
  5920. };
  5921. };
  5922. Tools.Vector2ArrayFeeder = function (array) {
  5923. return function (index) {
  5924. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5925. var length = isFloatArray ? array.length / 2 : array.length;
  5926. if (index >= length) {
  5927. return null;
  5928. }
  5929. if (isFloatArray) {
  5930. var fa = array;
  5931. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5932. }
  5933. var a = array;
  5934. return a[index];
  5935. };
  5936. };
  5937. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5938. if (bias === void 0) { bias = null; }
  5939. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5940. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5941. var i = 0;
  5942. var cur = feeder(i++);
  5943. while (cur) {
  5944. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5945. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5946. cur = feeder(i++);
  5947. }
  5948. if (bias) {
  5949. minimum.x -= minimum.x * bias.x + bias.y;
  5950. minimum.y -= minimum.y * bias.x + bias.y;
  5951. maximum.x += maximum.x * bias.x + bias.y;
  5952. maximum.y += maximum.y * bias.x + bias.y;
  5953. }
  5954. return {
  5955. minimum: minimum,
  5956. maximum: maximum
  5957. };
  5958. };
  5959. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5960. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5961. return null;
  5962. return Array.isArray(obj) ? obj : [obj];
  5963. };
  5964. // Misc.
  5965. Tools.GetPointerPrefix = function () {
  5966. var eventPrefix = "pointer";
  5967. // Check if pointer events are supported
  5968. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5969. eventPrefix = "mouse";
  5970. }
  5971. return eventPrefix;
  5972. };
  5973. /**
  5974. * @param func - the function to be called
  5975. * @param requester - the object that will request the next frame. Falls back to window.
  5976. */
  5977. Tools.QueueNewFrame = function (func, requester) {
  5978. if (!Tools.IsWindowObjectExist()) {
  5979. return setTimeout(func, 16);
  5980. }
  5981. if (!requester) {
  5982. requester = window;
  5983. }
  5984. if (requester.requestAnimationFrame) {
  5985. return requester.requestAnimationFrame(func);
  5986. }
  5987. else if (requester.msRequestAnimationFrame) {
  5988. return requester.msRequestAnimationFrame(func);
  5989. }
  5990. else if (requester.webkitRequestAnimationFrame) {
  5991. return requester.webkitRequestAnimationFrame(func);
  5992. }
  5993. else if (requester.mozRequestAnimationFrame) {
  5994. return requester.mozRequestAnimationFrame(func);
  5995. }
  5996. else if (requester.oRequestAnimationFrame) {
  5997. return requester.oRequestAnimationFrame(func);
  5998. }
  5999. else {
  6000. return window.setTimeout(func, 16);
  6001. }
  6002. };
  6003. Tools.RequestFullscreen = function (element) {
  6004. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6005. if (!requestFunction)
  6006. return;
  6007. requestFunction.call(element);
  6008. };
  6009. Tools.ExitFullscreen = function () {
  6010. if (document.exitFullscreen) {
  6011. document.exitFullscreen();
  6012. }
  6013. else if (document.mozCancelFullScreen) {
  6014. document.mozCancelFullScreen();
  6015. }
  6016. else if (document.webkitCancelFullScreen) {
  6017. document.webkitCancelFullScreen();
  6018. }
  6019. else if (document.msCancelFullScreen) {
  6020. document.msCancelFullScreen();
  6021. }
  6022. };
  6023. Tools.SetCorsBehavior = function (url, img) {
  6024. if (Tools.CorsBehavior) {
  6025. switch (typeof (Tools.CorsBehavior)) {
  6026. case "function":
  6027. var result = Tools.CorsBehavior(url);
  6028. if (result) {
  6029. img.crossOrigin = result;
  6030. }
  6031. break;
  6032. case "string":
  6033. default:
  6034. img.crossOrigin = Tools.CorsBehavior;
  6035. break;
  6036. }
  6037. }
  6038. };
  6039. // External files
  6040. Tools.CleanUrl = function (url) {
  6041. url = url.replace(/#/mg, "%23");
  6042. return url;
  6043. };
  6044. Tools.LoadImage = function (url, onLoad, onError, database) {
  6045. if (url instanceof ArrayBuffer) {
  6046. url = Tools.EncodeArrayBufferTobase64(url);
  6047. }
  6048. url = Tools.CleanUrl(url);
  6049. url = Tools.PreprocessUrl(url);
  6050. var img = new Image();
  6051. if (url.substr(0, 5) !== "data:") {
  6052. Tools.SetCorsBehavior(url, img);
  6053. }
  6054. img.onload = function () {
  6055. onLoad(img);
  6056. };
  6057. img.onerror = function (err) {
  6058. Tools.Error("Error while trying to load image: " + url);
  6059. if (Tools.UseFallbackTexture) {
  6060. img.src = Tools.fallbackTexture;
  6061. onLoad(img);
  6062. }
  6063. else {
  6064. onError("Error while trying to load image: " + url, err);
  6065. }
  6066. };
  6067. var noIndexedDB = function () {
  6068. img.src = url;
  6069. };
  6070. var loadFromIndexedDB = function () {
  6071. if (database) {
  6072. database.loadImageFromDB(url, img);
  6073. }
  6074. };
  6075. //ANY database to do!
  6076. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6077. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6078. }
  6079. else {
  6080. if (url.indexOf("file:") !== 0) {
  6081. noIndexedDB();
  6082. }
  6083. else {
  6084. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6085. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6086. try {
  6087. var blobURL;
  6088. try {
  6089. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6090. }
  6091. catch (ex) {
  6092. // Chrome doesn't support oneTimeOnly parameter
  6093. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6094. }
  6095. img.src = blobURL;
  6096. }
  6097. catch (e) {
  6098. img.src = "";
  6099. }
  6100. }
  6101. else {
  6102. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6103. img.src = Tools.fallbackTexture;
  6104. }
  6105. }
  6106. }
  6107. return img;
  6108. };
  6109. //ANY
  6110. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6111. url = Tools.CleanUrl(url);
  6112. url = Tools.PreprocessUrl(url);
  6113. var request = null;
  6114. var noIndexedDB = function () {
  6115. request = new XMLHttpRequest();
  6116. var loadUrl = Tools.BaseUrl + url;
  6117. request.open('GET', loadUrl, true);
  6118. if (useArrayBuffer) {
  6119. request.responseType = "arraybuffer";
  6120. }
  6121. if (progressCallBack) {
  6122. request.onprogress = progressCallBack;
  6123. }
  6124. request.onreadystatechange = function () {
  6125. var req = request;
  6126. // In case of undefined state in some browsers.
  6127. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6128. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6129. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6130. callback(!useArrayBuffer ? req.responseText : req.response);
  6131. }
  6132. else {
  6133. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6134. if (onError) {
  6135. onError(req, e);
  6136. }
  6137. else {
  6138. throw e;
  6139. }
  6140. }
  6141. }
  6142. };
  6143. request.send(null);
  6144. };
  6145. var loadFromIndexedDB = function () {
  6146. if (database) {
  6147. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6148. }
  6149. };
  6150. if (url.indexOf("file:") !== -1) {
  6151. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6152. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6153. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6154. }
  6155. else {
  6156. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6157. if (onError) {
  6158. var e = new Error(errorMessage);
  6159. onError(undefined, e);
  6160. }
  6161. else {
  6162. Tools.Error(errorMessage);
  6163. }
  6164. }
  6165. }
  6166. else {
  6167. // Caching all files
  6168. if (database && database.enableSceneOffline) {
  6169. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6170. }
  6171. else {
  6172. noIndexedDB();
  6173. }
  6174. }
  6175. return request;
  6176. };
  6177. /**
  6178. * Load a script (identified by an url). When the url returns, the
  6179. * content of this file is added into a new script element, attached to the DOM (body element)
  6180. */
  6181. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6182. var head = document.getElementsByTagName('head')[0];
  6183. var script = document.createElement('script');
  6184. script.type = 'text/javascript';
  6185. script.src = scriptUrl;
  6186. script.onload = function () {
  6187. if (onSuccess) {
  6188. onSuccess();
  6189. }
  6190. };
  6191. script.onerror = function (e) {
  6192. if (onError) {
  6193. onError("Unable to load script", e);
  6194. }
  6195. };
  6196. head.appendChild(script);
  6197. };
  6198. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6199. var reader = new FileReader();
  6200. reader.onload = function (e) {
  6201. //target doesn't have result from ts 1.3
  6202. callback(e.target['result']);
  6203. };
  6204. reader.onprogress = progressCallback;
  6205. reader.readAsDataURL(fileToLoad);
  6206. };
  6207. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6208. var reader = new FileReader();
  6209. reader.onerror = function (e) {
  6210. Tools.Log("Error while reading file: " + fileToLoad.name);
  6211. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6212. };
  6213. reader.onload = function (e) {
  6214. //target doesn't have result from ts 1.3
  6215. callback(e.target['result']);
  6216. };
  6217. if (progressCallBack) {
  6218. reader.onprogress = progressCallBack;
  6219. }
  6220. if (!useArrayBuffer) {
  6221. // Asynchronous read
  6222. reader.readAsText(fileToLoad);
  6223. }
  6224. else {
  6225. reader.readAsArrayBuffer(fileToLoad);
  6226. }
  6227. };
  6228. //returns a downloadable url to a file content.
  6229. Tools.FileAsURL = function (content) {
  6230. var fileBlob = new Blob([content]);
  6231. var url = window.URL || window.webkitURL;
  6232. var link = url.createObjectURL(fileBlob);
  6233. return link;
  6234. };
  6235. // Misc.
  6236. Tools.Format = function (value, decimals) {
  6237. if (decimals === void 0) { decimals = 2; }
  6238. return value.toFixed(decimals);
  6239. };
  6240. Tools.CheckExtends = function (v, min, max) {
  6241. if (v.x < min.x)
  6242. min.x = v.x;
  6243. if (v.y < min.y)
  6244. min.y = v.y;
  6245. if (v.z < min.z)
  6246. min.z = v.z;
  6247. if (v.x > max.x)
  6248. max.x = v.x;
  6249. if (v.y > max.y)
  6250. max.y = v.y;
  6251. if (v.z > max.z)
  6252. max.z = v.z;
  6253. };
  6254. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6255. for (var prop in source) {
  6256. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6257. continue;
  6258. }
  6259. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6260. continue;
  6261. }
  6262. var sourceValue = source[prop];
  6263. var typeOfSourceValue = typeof sourceValue;
  6264. if (typeOfSourceValue === "function") {
  6265. continue;
  6266. }
  6267. if (typeOfSourceValue === "object") {
  6268. if (sourceValue instanceof Array) {
  6269. destination[prop] = [];
  6270. if (sourceValue.length > 0) {
  6271. if (typeof sourceValue[0] == "object") {
  6272. for (var index = 0; index < sourceValue.length; index++) {
  6273. var clonedValue = cloneValue(sourceValue[index], destination);
  6274. if (destination[prop].indexOf(clonedValue) === -1) {
  6275. destination[prop].push(clonedValue);
  6276. }
  6277. }
  6278. }
  6279. else {
  6280. destination[prop] = sourceValue.slice(0);
  6281. }
  6282. }
  6283. }
  6284. else {
  6285. destination[prop] = cloneValue(sourceValue, destination);
  6286. }
  6287. }
  6288. else {
  6289. destination[prop] = sourceValue;
  6290. }
  6291. }
  6292. };
  6293. Tools.IsEmpty = function (obj) {
  6294. for (var i in obj) {
  6295. if (obj.hasOwnProperty(i)) {
  6296. return false;
  6297. }
  6298. }
  6299. return true;
  6300. };
  6301. Tools.RegisterTopRootEvents = function (events) {
  6302. for (var index = 0; index < events.length; index++) {
  6303. var event = events[index];
  6304. window.addEventListener(event.name, event.handler, false);
  6305. try {
  6306. if (window.parent) {
  6307. window.parent.addEventListener(event.name, event.handler, false);
  6308. }
  6309. }
  6310. catch (e) {
  6311. // Silently fails...
  6312. }
  6313. }
  6314. };
  6315. Tools.UnregisterTopRootEvents = function (events) {
  6316. for (var index = 0; index < events.length; index++) {
  6317. var event = events[index];
  6318. window.removeEventListener(event.name, event.handler);
  6319. try {
  6320. if (window.parent) {
  6321. window.parent.removeEventListener(event.name, event.handler);
  6322. }
  6323. }
  6324. catch (e) {
  6325. // Silently fails...
  6326. }
  6327. }
  6328. };
  6329. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6330. if (mimeType === void 0) { mimeType = "image/png"; }
  6331. // Read the contents of the framebuffer
  6332. var numberOfChannelsByLine = width * 4;
  6333. var halfHeight = height / 2;
  6334. //Reading datas from WebGL
  6335. var data = engine.readPixels(0, 0, width, height);
  6336. //To flip image on Y axis.
  6337. for (var i = 0; i < halfHeight; i++) {
  6338. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6339. var currentCell = j + i * numberOfChannelsByLine;
  6340. var targetLine = height - i - 1;
  6341. var targetCell = j + targetLine * numberOfChannelsByLine;
  6342. var temp = data[currentCell];
  6343. data[currentCell] = data[targetCell];
  6344. data[targetCell] = temp;
  6345. }
  6346. }
  6347. // Create a 2D canvas to store the result
  6348. if (!screenshotCanvas) {
  6349. screenshotCanvas = document.createElement('canvas');
  6350. }
  6351. screenshotCanvas.width = width;
  6352. screenshotCanvas.height = height;
  6353. var context = screenshotCanvas.getContext('2d');
  6354. if (context) {
  6355. // Copy the pixels to a 2D canvas
  6356. var imageData = context.createImageData(width, height);
  6357. var castData = (imageData.data);
  6358. castData.set(data);
  6359. context.putImageData(imageData, 0, 0);
  6360. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6361. }
  6362. };
  6363. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6364. if (mimeType === void 0) { mimeType = "image/png"; }
  6365. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6366. if (successCallback) {
  6367. successCallback(base64Image);
  6368. }
  6369. else {
  6370. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6371. if (("download" in document.createElement("a"))) {
  6372. var a = window.document.createElement("a");
  6373. a.href = base64Image;
  6374. var date = new Date();
  6375. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6376. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6377. window.document.body.appendChild(a);
  6378. a.addEventListener("click", function () {
  6379. if (a.parentElement) {
  6380. a.parentElement.removeChild(a);
  6381. }
  6382. });
  6383. a.click();
  6384. //Or opening a new tab with the image if it is not possible to automatically start download.
  6385. }
  6386. else {
  6387. var newWindow = window.open("");
  6388. var img = newWindow.document.createElement("img");
  6389. img.src = base64Image;
  6390. newWindow.document.body.appendChild(img);
  6391. }
  6392. }
  6393. };
  6394. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6395. if (mimeType === void 0) { mimeType = "image/png"; }
  6396. var width;
  6397. var height;
  6398. // If a precision value is specified
  6399. if (size.precision) {
  6400. width = Math.round(engine.getRenderWidth() * size.precision);
  6401. height = Math.round(width / engine.getAspectRatio(camera));
  6402. }
  6403. else if (size.width && size.height) {
  6404. width = size.width;
  6405. height = size.height;
  6406. }
  6407. else if (size.width && !size.height) {
  6408. width = size.width;
  6409. height = Math.round(width / engine.getAspectRatio(camera));
  6410. }
  6411. else if (size.height && !size.width) {
  6412. height = size.height;
  6413. width = Math.round(height * engine.getAspectRatio(camera));
  6414. }
  6415. else if (!isNaN(size)) {
  6416. height = size;
  6417. width = size;
  6418. }
  6419. else {
  6420. Tools.Error("Invalid 'size' parameter !");
  6421. return;
  6422. }
  6423. if (!screenshotCanvas) {
  6424. screenshotCanvas = document.createElement('canvas');
  6425. }
  6426. screenshotCanvas.width = width;
  6427. screenshotCanvas.height = height;
  6428. var renderContext = screenshotCanvas.getContext("2d");
  6429. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6430. var newWidth = width;
  6431. var newHeight = newWidth / ratio;
  6432. if (newHeight > height) {
  6433. newHeight = height;
  6434. newWidth = newHeight * ratio;
  6435. }
  6436. var offsetX = Math.max(0, width - newWidth) / 2;
  6437. var offsetY = Math.max(0, height - newHeight) / 2;
  6438. var renderingCanvas = engine.getRenderingCanvas();
  6439. if (renderContext && renderingCanvas) {
  6440. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6441. }
  6442. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6443. };
  6444. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6445. if (mimeType === void 0) { mimeType = "image/png"; }
  6446. if (samples === void 0) { samples = 1; }
  6447. var width;
  6448. var height;
  6449. //If a precision value is specified
  6450. if (size.precision) {
  6451. width = Math.round(engine.getRenderWidth() * size.precision);
  6452. height = Math.round(width / engine.getAspectRatio(camera));
  6453. size = { width: width, height: height };
  6454. }
  6455. else if (size.width && size.height) {
  6456. width = size.width;
  6457. height = size.height;
  6458. }
  6459. else if (size.width && !size.height) {
  6460. width = size.width;
  6461. height = Math.round(width / engine.getAspectRatio(camera));
  6462. size = { width: width, height: height };
  6463. }
  6464. else if (size.height && !size.width) {
  6465. height = size.height;
  6466. width = Math.round(height * engine.getAspectRatio(camera));
  6467. size = { width: width, height: height };
  6468. }
  6469. else if (!isNaN(size)) {
  6470. height = size;
  6471. width = size;
  6472. }
  6473. else {
  6474. Tools.Error("Invalid 'size' parameter !");
  6475. return;
  6476. }
  6477. var scene = camera.getScene();
  6478. var previousCamera = null;
  6479. if (scene.activeCamera !== camera) {
  6480. previousCamera = scene.activeCamera;
  6481. scene.activeCamera = camera;
  6482. }
  6483. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6484. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6485. texture.renderList = null;
  6486. texture.samples = samples;
  6487. texture.onAfterRenderObservable.add(function () {
  6488. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6489. });
  6490. scene.incrementRenderId();
  6491. scene.resetCachedMaterial();
  6492. texture.render(true);
  6493. texture.dispose();
  6494. if (previousCamera) {
  6495. scene.activeCamera = previousCamera;
  6496. }
  6497. camera.getProjectionMatrix(true); // Force cache refresh;
  6498. };
  6499. // XHR response validator for local file scenario
  6500. Tools.ValidateXHRData = function (xhr, dataType) {
  6501. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6502. if (dataType === void 0) { dataType = 7; }
  6503. try {
  6504. if (dataType & 1) {
  6505. if (xhr.responseText && xhr.responseText.length > 0) {
  6506. return true;
  6507. }
  6508. else if (dataType === 1) {
  6509. return false;
  6510. }
  6511. }
  6512. if (dataType & 2) {
  6513. // Check header width and height since there is no "TGA" magic number
  6514. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6515. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6516. return true;
  6517. }
  6518. else if (dataType === 2) {
  6519. return false;
  6520. }
  6521. }
  6522. if (dataType & 4) {
  6523. // Check for the "DDS" magic number
  6524. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6525. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6526. return true;
  6527. }
  6528. else {
  6529. return false;
  6530. }
  6531. }
  6532. }
  6533. catch (e) {
  6534. // Global protection
  6535. }
  6536. return false;
  6537. };
  6538. /**
  6539. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6540. * Be aware Math.random() could cause collisions, but:
  6541. * "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"
  6542. */
  6543. Tools.RandomId = function () {
  6544. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6545. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6546. return v.toString(16);
  6547. });
  6548. };
  6549. Object.defineProperty(Tools, "NoneLogLevel", {
  6550. get: function () {
  6551. return Tools._NoneLogLevel;
  6552. },
  6553. enumerable: true,
  6554. configurable: true
  6555. });
  6556. Object.defineProperty(Tools, "MessageLogLevel", {
  6557. get: function () {
  6558. return Tools._MessageLogLevel;
  6559. },
  6560. enumerable: true,
  6561. configurable: true
  6562. });
  6563. Object.defineProperty(Tools, "WarningLogLevel", {
  6564. get: function () {
  6565. return Tools._WarningLogLevel;
  6566. },
  6567. enumerable: true,
  6568. configurable: true
  6569. });
  6570. Object.defineProperty(Tools, "ErrorLogLevel", {
  6571. get: function () {
  6572. return Tools._ErrorLogLevel;
  6573. },
  6574. enumerable: true,
  6575. configurable: true
  6576. });
  6577. Object.defineProperty(Tools, "AllLogLevel", {
  6578. get: function () {
  6579. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6580. },
  6581. enumerable: true,
  6582. configurable: true
  6583. });
  6584. Tools._AddLogEntry = function (entry) {
  6585. Tools._LogCache = entry + Tools._LogCache;
  6586. if (Tools.OnNewCacheEntry) {
  6587. Tools.OnNewCacheEntry(entry);
  6588. }
  6589. };
  6590. Tools._FormatMessage = function (message) {
  6591. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6592. var date = new Date();
  6593. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6594. };
  6595. Tools._LogDisabled = function (message) {
  6596. // nothing to do
  6597. };
  6598. Tools._LogEnabled = function (message) {
  6599. var formattedMessage = Tools._FormatMessage(message);
  6600. console.log("BJS - " + formattedMessage);
  6601. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6602. Tools._AddLogEntry(entry);
  6603. };
  6604. Tools._WarnDisabled = function (message) {
  6605. // nothing to do
  6606. };
  6607. Tools._WarnEnabled = function (message) {
  6608. var formattedMessage = Tools._FormatMessage(message);
  6609. console.warn("BJS - " + formattedMessage);
  6610. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6611. Tools._AddLogEntry(entry);
  6612. };
  6613. Tools._ErrorDisabled = function (message) {
  6614. // nothing to do
  6615. };
  6616. Tools._ErrorEnabled = function (message) {
  6617. Tools.errorsCount++;
  6618. var formattedMessage = Tools._FormatMessage(message);
  6619. console.error("BJS - " + formattedMessage);
  6620. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6621. Tools._AddLogEntry(entry);
  6622. };
  6623. Object.defineProperty(Tools, "LogCache", {
  6624. get: function () {
  6625. return Tools._LogCache;
  6626. },
  6627. enumerable: true,
  6628. configurable: true
  6629. });
  6630. Tools.ClearLogCache = function () {
  6631. Tools._LogCache = "";
  6632. Tools.errorsCount = 0;
  6633. };
  6634. Object.defineProperty(Tools, "LogLevels", {
  6635. set: function (level) {
  6636. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6637. Tools.Log = Tools._LogEnabled;
  6638. }
  6639. else {
  6640. Tools.Log = Tools._LogDisabled;
  6641. }
  6642. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6643. Tools.Warn = Tools._WarnEnabled;
  6644. }
  6645. else {
  6646. Tools.Warn = Tools._WarnDisabled;
  6647. }
  6648. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6649. Tools.Error = Tools._ErrorEnabled;
  6650. }
  6651. else {
  6652. Tools.Error = Tools._ErrorDisabled;
  6653. }
  6654. },
  6655. enumerable: true,
  6656. configurable: true
  6657. });
  6658. Tools.IsWindowObjectExist = function () {
  6659. return (typeof window) !== "undefined";
  6660. };
  6661. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6662. get: function () {
  6663. return Tools._PerformanceNoneLogLevel;
  6664. },
  6665. enumerable: true,
  6666. configurable: true
  6667. });
  6668. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6669. get: function () {
  6670. return Tools._PerformanceUserMarkLogLevel;
  6671. },
  6672. enumerable: true,
  6673. configurable: true
  6674. });
  6675. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6676. get: function () {
  6677. return Tools._PerformanceConsoleLogLevel;
  6678. },
  6679. enumerable: true,
  6680. configurable: true
  6681. });
  6682. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6683. set: function (level) {
  6684. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6685. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6686. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6687. return;
  6688. }
  6689. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6690. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6691. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6692. return;
  6693. }
  6694. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6695. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6696. },
  6697. enumerable: true,
  6698. configurable: true
  6699. });
  6700. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6701. };
  6702. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6703. };
  6704. Tools._StartUserMark = function (counterName, condition) {
  6705. if (condition === void 0) { condition = true; }
  6706. if (!Tools._performance) {
  6707. if (!Tools.IsWindowObjectExist()) {
  6708. return;
  6709. }
  6710. Tools._performance = window.performance;
  6711. }
  6712. if (!condition || !Tools._performance.mark) {
  6713. return;
  6714. }
  6715. Tools._performance.mark(counterName + "-Begin");
  6716. };
  6717. Tools._EndUserMark = function (counterName, condition) {
  6718. if (condition === void 0) { condition = true; }
  6719. if (!condition || !Tools._performance.mark) {
  6720. return;
  6721. }
  6722. Tools._performance.mark(counterName + "-End");
  6723. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6724. };
  6725. Tools._StartPerformanceConsole = function (counterName, condition) {
  6726. if (condition === void 0) { condition = true; }
  6727. if (!condition) {
  6728. return;
  6729. }
  6730. Tools._StartUserMark(counterName, condition);
  6731. if (console.time) {
  6732. console.time(counterName);
  6733. }
  6734. };
  6735. Tools._EndPerformanceConsole = function (counterName, condition) {
  6736. if (condition === void 0) { condition = true; }
  6737. if (!condition) {
  6738. return;
  6739. }
  6740. Tools._EndUserMark(counterName, condition);
  6741. if (console.time) {
  6742. console.timeEnd(counterName);
  6743. }
  6744. };
  6745. Object.defineProperty(Tools, "Now", {
  6746. get: function () {
  6747. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6748. return window.performance.now();
  6749. }
  6750. return new Date().getTime();
  6751. },
  6752. enumerable: true,
  6753. configurable: true
  6754. });
  6755. /**
  6756. * This method will return the name of the class used to create the instance of the given object.
  6757. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6758. * @param object the object to get the class name from
  6759. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6760. */
  6761. Tools.GetClassName = function (object, isType) {
  6762. if (isType === void 0) { isType = false; }
  6763. var name = null;
  6764. if (!isType && object.getClassName) {
  6765. name = object.getClassName();
  6766. }
  6767. else {
  6768. if (object instanceof Object) {
  6769. var classObj = isType ? object : Object.getPrototypeOf(object);
  6770. name = classObj.constructor["__bjsclassName__"];
  6771. }
  6772. if (!name) {
  6773. name = typeof object;
  6774. }
  6775. }
  6776. return name;
  6777. };
  6778. Tools.First = function (array, predicate) {
  6779. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6780. var el = array_1[_i];
  6781. if (predicate(el)) {
  6782. return el;
  6783. }
  6784. }
  6785. return null;
  6786. };
  6787. /**
  6788. * This method will return the name of the full name of the class, including its owning module (if any).
  6789. * 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).
  6790. * @param object the object to get the class name from
  6791. * @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.
  6792. */
  6793. Tools.getFullClassName = function (object, isType) {
  6794. if (isType === void 0) { isType = false; }
  6795. var className = null;
  6796. var moduleName = null;
  6797. if (!isType && object.getClassName) {
  6798. className = object.getClassName();
  6799. }
  6800. else {
  6801. if (object instanceof Object) {
  6802. var classObj = isType ? object : Object.getPrototypeOf(object);
  6803. className = classObj.constructor["__bjsclassName__"];
  6804. moduleName = classObj.constructor["__bjsmoduleName__"];
  6805. }
  6806. if (!className) {
  6807. className = typeof object;
  6808. }
  6809. }
  6810. if (!className) {
  6811. return null;
  6812. }
  6813. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6814. };
  6815. /**
  6816. * 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.
  6817. * @param array
  6818. */
  6819. Tools.arrayOrStringFeeder = function (array) {
  6820. return function (index) {
  6821. if (index >= array.length) {
  6822. return null;
  6823. }
  6824. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6825. if (val && val.getHashCode) {
  6826. val = val.getHashCode();
  6827. }
  6828. if (typeof val === "string") {
  6829. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6830. }
  6831. return val;
  6832. };
  6833. };
  6834. /**
  6835. * Compute the hashCode of a stream of number
  6836. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6837. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6838. * @return the hash code computed
  6839. */
  6840. Tools.hashCodeFromStream = function (feeder) {
  6841. // Based from here: http://stackoverflow.com/a/7616484/802124
  6842. var hash = 0;
  6843. var index = 0;
  6844. var chr = feeder(index++);
  6845. while (chr != null) {
  6846. hash = ((hash << 5) - hash) + chr;
  6847. hash |= 0; // Convert to 32bit integer
  6848. chr = feeder(index++);
  6849. }
  6850. return hash;
  6851. };
  6852. Tools.BaseUrl = "";
  6853. Tools.CorsBehavior = "anonymous";
  6854. Tools.UseFallbackTexture = true;
  6855. /**
  6856. * Use this object to register external classes like custom textures or material
  6857. * to allow the laoders to instantiate them
  6858. */
  6859. Tools.RegisteredExternalClasses = {};
  6860. // Used in case of a texture loading problem
  6861. 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";
  6862. Tools.PreprocessUrl = function (url) {
  6863. return url;
  6864. };
  6865. // Logs
  6866. Tools._NoneLogLevel = 0;
  6867. Tools._MessageLogLevel = 1;
  6868. Tools._WarningLogLevel = 2;
  6869. Tools._ErrorLogLevel = 4;
  6870. Tools._LogCache = "";
  6871. Tools.errorsCount = 0;
  6872. Tools.Log = Tools._LogEnabled;
  6873. Tools.Warn = Tools._WarnEnabled;
  6874. Tools.Error = Tools._ErrorEnabled;
  6875. // Performances
  6876. Tools._PerformanceNoneLogLevel = 0;
  6877. Tools._PerformanceUserMarkLogLevel = 1;
  6878. Tools._PerformanceConsoleLogLevel = 2;
  6879. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6880. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6881. return Tools;
  6882. }());
  6883. BABYLON.Tools = Tools;
  6884. /**
  6885. * This class is used to track a performance counter which is number based.
  6886. * The user has access to many properties which give statistics of different nature
  6887. *
  6888. * The implementer can track two kinds of Performance Counter: time and count
  6889. * 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.
  6890. * 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.
  6891. */
  6892. var PerfCounter = /** @class */ (function () {
  6893. function PerfCounter() {
  6894. this._startMonitoringTime = 0;
  6895. this._min = 0;
  6896. this._max = 0;
  6897. this._average = 0;
  6898. this._lastSecAverage = 0;
  6899. this._current = 0;
  6900. this._totalValueCount = 0;
  6901. this._totalAccumulated = 0;
  6902. this._lastSecAccumulated = 0;
  6903. this._lastSecTime = 0;
  6904. this._lastSecValueCount = 0;
  6905. }
  6906. Object.defineProperty(PerfCounter.prototype, "min", {
  6907. /**
  6908. * Returns the smallest value ever
  6909. */
  6910. get: function () {
  6911. return this._min;
  6912. },
  6913. enumerable: true,
  6914. configurable: true
  6915. });
  6916. Object.defineProperty(PerfCounter.prototype, "max", {
  6917. /**
  6918. * Returns the biggest value ever
  6919. */
  6920. get: function () {
  6921. return this._max;
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. Object.defineProperty(PerfCounter.prototype, "average", {
  6927. /**
  6928. * Returns the average value since the performance counter is running
  6929. */
  6930. get: function () {
  6931. return this._average;
  6932. },
  6933. enumerable: true,
  6934. configurable: true
  6935. });
  6936. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6937. /**
  6938. * Returns the average value of the last second the counter was monitored
  6939. */
  6940. get: function () {
  6941. return this._lastSecAverage;
  6942. },
  6943. enumerable: true,
  6944. configurable: true
  6945. });
  6946. Object.defineProperty(PerfCounter.prototype, "current", {
  6947. /**
  6948. * Returns the current value
  6949. */
  6950. get: function () {
  6951. return this._current;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(PerfCounter.prototype, "total", {
  6957. get: function () {
  6958. return this._totalAccumulated;
  6959. },
  6960. enumerable: true,
  6961. configurable: true
  6962. });
  6963. Object.defineProperty(PerfCounter.prototype, "count", {
  6964. get: function () {
  6965. return this._totalValueCount;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. /**
  6971. * Call this method to start monitoring a new frame.
  6972. * 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.
  6973. */
  6974. PerfCounter.prototype.fetchNewFrame = function () {
  6975. this._totalValueCount++;
  6976. this._current = 0;
  6977. this._lastSecValueCount++;
  6978. };
  6979. /**
  6980. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6981. * @param newCount the count value to add to the monitored count
  6982. * @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.
  6983. */
  6984. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6985. if (!PerfCounter.Enabled) {
  6986. return;
  6987. }
  6988. this._current += newCount;
  6989. if (fetchResult) {
  6990. this._fetchResult();
  6991. }
  6992. };
  6993. /**
  6994. * Start monitoring this performance counter
  6995. */
  6996. PerfCounter.prototype.beginMonitoring = function () {
  6997. if (!PerfCounter.Enabled) {
  6998. return;
  6999. }
  7000. this._startMonitoringTime = Tools.Now;
  7001. };
  7002. /**
  7003. * Compute the time lapsed since the previous beginMonitoring() call.
  7004. * @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
  7005. */
  7006. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7007. if (newFrame === void 0) { newFrame = true; }
  7008. if (!PerfCounter.Enabled) {
  7009. return;
  7010. }
  7011. if (newFrame) {
  7012. this.fetchNewFrame();
  7013. }
  7014. var currentTime = Tools.Now;
  7015. this._current = currentTime - this._startMonitoringTime;
  7016. if (newFrame) {
  7017. this._fetchResult();
  7018. }
  7019. };
  7020. PerfCounter.prototype._fetchResult = function () {
  7021. this._totalAccumulated += this._current;
  7022. this._lastSecAccumulated += this._current;
  7023. // Min/Max update
  7024. this._min = Math.min(this._min, this._current);
  7025. this._max = Math.max(this._max, this._current);
  7026. this._average = this._totalAccumulated / this._totalValueCount;
  7027. // Reset last sec?
  7028. var now = Tools.Now;
  7029. if ((now - this._lastSecTime) > 1000) {
  7030. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7031. this._lastSecTime = now;
  7032. this._lastSecAccumulated = 0;
  7033. this._lastSecValueCount = 0;
  7034. }
  7035. };
  7036. PerfCounter.Enabled = true;
  7037. return PerfCounter;
  7038. }());
  7039. BABYLON.PerfCounter = PerfCounter;
  7040. /**
  7041. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7042. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7043. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7044. * @param name The name of the class, case should be preserved
  7045. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7046. */
  7047. function className(name, module) {
  7048. return function (target) {
  7049. target["__bjsclassName__"] = name;
  7050. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7051. };
  7052. }
  7053. BABYLON.className = className;
  7054. /**
  7055. * An implementation of a loop for asynchronous functions.
  7056. */
  7057. var AsyncLoop = /** @class */ (function () {
  7058. /**
  7059. * Constroctor.
  7060. * @param iterations the number of iterations.
  7061. * @param _fn the function to run each iteration
  7062. * @param _successCallback the callback that will be called upon succesful execution
  7063. * @param offset starting offset.
  7064. */
  7065. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7066. if (offset === void 0) { offset = 0; }
  7067. this.iterations = iterations;
  7068. this._fn = _fn;
  7069. this._successCallback = _successCallback;
  7070. this.index = offset - 1;
  7071. this._done = false;
  7072. }
  7073. /**
  7074. * Execute the next iteration. Must be called after the last iteration was finished.
  7075. */
  7076. AsyncLoop.prototype.executeNext = function () {
  7077. if (!this._done) {
  7078. if (this.index + 1 < this.iterations) {
  7079. ++this.index;
  7080. this._fn(this);
  7081. }
  7082. else {
  7083. this.breakLoop();
  7084. }
  7085. }
  7086. };
  7087. /**
  7088. * Break the loop and run the success callback.
  7089. */
  7090. AsyncLoop.prototype.breakLoop = function () {
  7091. this._done = true;
  7092. this._successCallback();
  7093. };
  7094. /**
  7095. * Helper function
  7096. */
  7097. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7098. if (offset === void 0) { offset = 0; }
  7099. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7100. loop.executeNext();
  7101. return loop;
  7102. };
  7103. /**
  7104. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7105. * @param iterations total number of iterations
  7106. * @param syncedIterations number of synchronous iterations in each async iteration.
  7107. * @param fn the function to call each iteration.
  7108. * @param callback a success call back that will be called when iterating stops.
  7109. * @param breakFunction a break condition (optional)
  7110. * @param timeout timeout settings for the setTimeout function. default - 0.
  7111. * @constructor
  7112. */
  7113. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7114. if (timeout === void 0) { timeout = 0; }
  7115. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7116. if (breakFunction && breakFunction())
  7117. loop.breakLoop();
  7118. else {
  7119. setTimeout(function () {
  7120. for (var i = 0; i < syncedIterations; ++i) {
  7121. var iteration = (loop.index * syncedIterations) + i;
  7122. if (iteration >= iterations)
  7123. break;
  7124. fn(iteration);
  7125. if (breakFunction && breakFunction()) {
  7126. loop.breakLoop();
  7127. break;
  7128. }
  7129. }
  7130. loop.executeNext();
  7131. }, timeout);
  7132. }
  7133. }, callback);
  7134. };
  7135. return AsyncLoop;
  7136. }());
  7137. BABYLON.AsyncLoop = AsyncLoop;
  7138. })(BABYLON || (BABYLON = {}));
  7139. //# sourceMappingURL=babylon.tools.js.map
  7140. var BABYLON;
  7141. (function (BABYLON) {
  7142. var Internals;
  7143. (function (Internals) {
  7144. var _AlphaState = /** @class */ (function () {
  7145. /**
  7146. * Initializes the state.
  7147. */
  7148. function _AlphaState() {
  7149. this._isAlphaBlendDirty = false;
  7150. this._isBlendFunctionParametersDirty = false;
  7151. this._isBlendEquationParametersDirty = false;
  7152. this._isBlendConstantsDirty = false;
  7153. this._alphaBlend = false;
  7154. this._blendFunctionParameters = new Array(4);
  7155. this._blendEquationParameters = new Array(2);
  7156. this._blendConstants = new Array(4);
  7157. this.reset();
  7158. }
  7159. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7160. get: function () {
  7161. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7162. },
  7163. enumerable: true,
  7164. configurable: true
  7165. });
  7166. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7167. get: function () {
  7168. return this._alphaBlend;
  7169. },
  7170. set: function (value) {
  7171. if (this._alphaBlend === value) {
  7172. return;
  7173. }
  7174. this._alphaBlend = value;
  7175. this._isAlphaBlendDirty = true;
  7176. },
  7177. enumerable: true,
  7178. configurable: true
  7179. });
  7180. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7181. if (this._blendConstants[0] === r &&
  7182. this._blendConstants[1] === g &&
  7183. this._blendConstants[2] === b &&
  7184. this._blendConstants[3] === a) {
  7185. return;
  7186. }
  7187. this._blendConstants[0] = r;
  7188. this._blendConstants[1] = g;
  7189. this._blendConstants[2] = b;
  7190. this._blendConstants[3] = a;
  7191. this._isBlendConstantsDirty = true;
  7192. };
  7193. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7194. if (this._blendFunctionParameters[0] === value0 &&
  7195. this._blendFunctionParameters[1] === value1 &&
  7196. this._blendFunctionParameters[2] === value2 &&
  7197. this._blendFunctionParameters[3] === value3) {
  7198. return;
  7199. }
  7200. this._blendFunctionParameters[0] = value0;
  7201. this._blendFunctionParameters[1] = value1;
  7202. this._blendFunctionParameters[2] = value2;
  7203. this._blendFunctionParameters[3] = value3;
  7204. this._isBlendFunctionParametersDirty = true;
  7205. };
  7206. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7207. if (this._blendEquationParameters[0] === rgb &&
  7208. this._blendEquationParameters[1] === alpha) {
  7209. return;
  7210. }
  7211. this._blendEquationParameters[0] = rgb;
  7212. this._blendEquationParameters[1] = alpha;
  7213. this._isBlendEquationParametersDirty = true;
  7214. };
  7215. _AlphaState.prototype.reset = function () {
  7216. this._alphaBlend = false;
  7217. this._blendFunctionParameters[0] = null;
  7218. this._blendFunctionParameters[1] = null;
  7219. this._blendFunctionParameters[2] = null;
  7220. this._blendFunctionParameters[3] = null;
  7221. this._blendEquationParameters[0] = null;
  7222. this._blendEquationParameters[1] = null;
  7223. this._blendConstants[0] = null;
  7224. this._blendConstants[1] = null;
  7225. this._blendConstants[2] = null;
  7226. this._blendConstants[3] = null;
  7227. this._isAlphaBlendDirty = true;
  7228. this._isBlendFunctionParametersDirty = false;
  7229. this._isBlendEquationParametersDirty = false;
  7230. this._isBlendConstantsDirty = false;
  7231. };
  7232. _AlphaState.prototype.apply = function (gl) {
  7233. if (!this.isDirty) {
  7234. return;
  7235. }
  7236. // Alpha blend
  7237. if (this._isAlphaBlendDirty) {
  7238. if (this._alphaBlend) {
  7239. gl.enable(gl.BLEND);
  7240. }
  7241. else {
  7242. gl.disable(gl.BLEND);
  7243. }
  7244. this._isAlphaBlendDirty = false;
  7245. }
  7246. // Alpha function
  7247. if (this._isBlendFunctionParametersDirty) {
  7248. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7249. this._isBlendFunctionParametersDirty = false;
  7250. }
  7251. // Alpha equation
  7252. if (this._isBlendEquationParametersDirty) {
  7253. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7254. this._isBlendEquationParametersDirty = false;
  7255. }
  7256. // Constants
  7257. if (this._isBlendConstantsDirty) {
  7258. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7259. this._isBlendConstantsDirty = false;
  7260. }
  7261. };
  7262. return _AlphaState;
  7263. }());
  7264. Internals._AlphaState = _AlphaState;
  7265. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7266. })(BABYLON || (BABYLON = {}));
  7267. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7268. var BABYLON;
  7269. (function (BABYLON) {
  7270. var Internals;
  7271. (function (Internals) {
  7272. var _DepthCullingState = /** @class */ (function () {
  7273. /**
  7274. * Initializes the state.
  7275. */
  7276. function _DepthCullingState() {
  7277. this._isDepthTestDirty = false;
  7278. this._isDepthMaskDirty = false;
  7279. this._isDepthFuncDirty = false;
  7280. this._isCullFaceDirty = false;
  7281. this._isCullDirty = false;
  7282. this._isZOffsetDirty = false;
  7283. this.reset();
  7284. }
  7285. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7286. get: function () {
  7287. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7288. },
  7289. enumerable: true,
  7290. configurable: true
  7291. });
  7292. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7293. get: function () {
  7294. return this._zOffset;
  7295. },
  7296. set: function (value) {
  7297. if (this._zOffset === value) {
  7298. return;
  7299. }
  7300. this._zOffset = value;
  7301. this._isZOffsetDirty = true;
  7302. },
  7303. enumerable: true,
  7304. configurable: true
  7305. });
  7306. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7307. get: function () {
  7308. return this._cullFace;
  7309. },
  7310. set: function (value) {
  7311. if (this._cullFace === value) {
  7312. return;
  7313. }
  7314. this._cullFace = value;
  7315. this._isCullFaceDirty = true;
  7316. },
  7317. enumerable: true,
  7318. configurable: true
  7319. });
  7320. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7321. get: function () {
  7322. return this._cull;
  7323. },
  7324. set: function (value) {
  7325. if (this._cull === value) {
  7326. return;
  7327. }
  7328. this._cull = value;
  7329. this._isCullDirty = true;
  7330. },
  7331. enumerable: true,
  7332. configurable: true
  7333. });
  7334. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7335. get: function () {
  7336. return this._depthFunc;
  7337. },
  7338. set: function (value) {
  7339. if (this._depthFunc === value) {
  7340. return;
  7341. }
  7342. this._depthFunc = value;
  7343. this._isDepthFuncDirty = true;
  7344. },
  7345. enumerable: true,
  7346. configurable: true
  7347. });
  7348. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7349. get: function () {
  7350. return this._depthMask;
  7351. },
  7352. set: function (value) {
  7353. if (this._depthMask === value) {
  7354. return;
  7355. }
  7356. this._depthMask = value;
  7357. this._isDepthMaskDirty = true;
  7358. },
  7359. enumerable: true,
  7360. configurable: true
  7361. });
  7362. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7363. get: function () {
  7364. return this._depthTest;
  7365. },
  7366. set: function (value) {
  7367. if (this._depthTest === value) {
  7368. return;
  7369. }
  7370. this._depthTest = value;
  7371. this._isDepthTestDirty = true;
  7372. },
  7373. enumerable: true,
  7374. configurable: true
  7375. });
  7376. _DepthCullingState.prototype.reset = function () {
  7377. this._depthMask = true;
  7378. this._depthTest = true;
  7379. this._depthFunc = null;
  7380. this._cullFace = null;
  7381. this._cull = null;
  7382. this._zOffset = 0;
  7383. this._isDepthTestDirty = true;
  7384. this._isDepthMaskDirty = true;
  7385. this._isDepthFuncDirty = false;
  7386. this._isCullFaceDirty = false;
  7387. this._isCullDirty = false;
  7388. this._isZOffsetDirty = false;
  7389. };
  7390. _DepthCullingState.prototype.apply = function (gl) {
  7391. if (!this.isDirty) {
  7392. return;
  7393. }
  7394. // Cull
  7395. if (this._isCullDirty) {
  7396. if (this.cull) {
  7397. gl.enable(gl.CULL_FACE);
  7398. }
  7399. else {
  7400. gl.disable(gl.CULL_FACE);
  7401. }
  7402. this._isCullDirty = false;
  7403. }
  7404. // Cull face
  7405. if (this._isCullFaceDirty) {
  7406. gl.cullFace(this.cullFace);
  7407. this._isCullFaceDirty = false;
  7408. }
  7409. // Depth mask
  7410. if (this._isDepthMaskDirty) {
  7411. gl.depthMask(this.depthMask);
  7412. this._isDepthMaskDirty = false;
  7413. }
  7414. // Depth test
  7415. if (this._isDepthTestDirty) {
  7416. if (this.depthTest) {
  7417. gl.enable(gl.DEPTH_TEST);
  7418. }
  7419. else {
  7420. gl.disable(gl.DEPTH_TEST);
  7421. }
  7422. this._isDepthTestDirty = false;
  7423. }
  7424. // Depth func
  7425. if (this._isDepthFuncDirty) {
  7426. gl.depthFunc(this.depthFunc);
  7427. this._isDepthFuncDirty = false;
  7428. }
  7429. // zOffset
  7430. if (this._isZOffsetDirty) {
  7431. if (this.zOffset) {
  7432. gl.enable(gl.POLYGON_OFFSET_FILL);
  7433. gl.polygonOffset(this.zOffset, 0);
  7434. }
  7435. else {
  7436. gl.disable(gl.POLYGON_OFFSET_FILL);
  7437. }
  7438. this._isZOffsetDirty = false;
  7439. }
  7440. };
  7441. return _DepthCullingState;
  7442. }());
  7443. Internals._DepthCullingState = _DepthCullingState;
  7444. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7445. })(BABYLON || (BABYLON = {}));
  7446. //# sourceMappingURL=babylon.depthCullingState.js.map
  7447. var BABYLON;
  7448. (function (BABYLON) {
  7449. var Internals;
  7450. (function (Internals) {
  7451. var _StencilState = /** @class */ (function () {
  7452. function _StencilState() {
  7453. this._isStencilTestDirty = false;
  7454. this._isStencilMaskDirty = false;
  7455. this._isStencilFuncDirty = false;
  7456. this._isStencilOpDirty = false;
  7457. this.reset();
  7458. }
  7459. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7460. get: function () {
  7461. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7462. },
  7463. enumerable: true,
  7464. configurable: true
  7465. });
  7466. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7467. get: function () {
  7468. return this._stencilFunc;
  7469. },
  7470. set: function (value) {
  7471. if (this._stencilFunc === value) {
  7472. return;
  7473. }
  7474. this._stencilFunc = value;
  7475. this._isStencilFuncDirty = true;
  7476. },
  7477. enumerable: true,
  7478. configurable: true
  7479. });
  7480. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7481. get: function () {
  7482. return this._stencilFuncRef;
  7483. },
  7484. set: function (value) {
  7485. if (this._stencilFuncRef === value) {
  7486. return;
  7487. }
  7488. this._stencilFuncRef = value;
  7489. this._isStencilFuncDirty = true;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7495. get: function () {
  7496. return this._stencilFuncMask;
  7497. },
  7498. set: function (value) {
  7499. if (this._stencilFuncMask === value) {
  7500. return;
  7501. }
  7502. this._stencilFuncMask = value;
  7503. this._isStencilFuncDirty = true;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7509. get: function () {
  7510. return this._stencilOpStencilFail;
  7511. },
  7512. set: function (value) {
  7513. if (this._stencilOpStencilFail === value) {
  7514. return;
  7515. }
  7516. this._stencilOpStencilFail = value;
  7517. this._isStencilOpDirty = true;
  7518. },
  7519. enumerable: true,
  7520. configurable: true
  7521. });
  7522. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7523. get: function () {
  7524. return this._stencilOpDepthFail;
  7525. },
  7526. set: function (value) {
  7527. if (this._stencilOpDepthFail === value) {
  7528. return;
  7529. }
  7530. this._stencilOpDepthFail = value;
  7531. this._isStencilOpDirty = true;
  7532. },
  7533. enumerable: true,
  7534. configurable: true
  7535. });
  7536. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7537. get: function () {
  7538. return this._stencilOpStencilDepthPass;
  7539. },
  7540. set: function (value) {
  7541. if (this._stencilOpStencilDepthPass === value) {
  7542. return;
  7543. }
  7544. this._stencilOpStencilDepthPass = value;
  7545. this._isStencilOpDirty = true;
  7546. },
  7547. enumerable: true,
  7548. configurable: true
  7549. });
  7550. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7551. get: function () {
  7552. return this._stencilMask;
  7553. },
  7554. set: function (value) {
  7555. if (this._stencilMask === value) {
  7556. return;
  7557. }
  7558. this._stencilMask = value;
  7559. this._isStencilMaskDirty = true;
  7560. },
  7561. enumerable: true,
  7562. configurable: true
  7563. });
  7564. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7565. get: function () {
  7566. return this._stencilTest;
  7567. },
  7568. set: function (value) {
  7569. if (this._stencilTest === value) {
  7570. return;
  7571. }
  7572. this._stencilTest = value;
  7573. this._isStencilTestDirty = true;
  7574. },
  7575. enumerable: true,
  7576. configurable: true
  7577. });
  7578. _StencilState.prototype.reset = function () {
  7579. this._stencilTest = false;
  7580. this._stencilMask = 0xFF;
  7581. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7582. this._stencilFuncRef = 1;
  7583. this._stencilFuncMask = 0xFF;
  7584. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7585. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7586. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7587. this._isStencilTestDirty = true;
  7588. this._isStencilMaskDirty = true;
  7589. this._isStencilFuncDirty = true;
  7590. this._isStencilOpDirty = true;
  7591. };
  7592. _StencilState.prototype.apply = function (gl) {
  7593. if (!this.isDirty) {
  7594. return;
  7595. }
  7596. // Stencil test
  7597. if (this._isStencilTestDirty) {
  7598. if (this.stencilTest) {
  7599. gl.enable(gl.STENCIL_TEST);
  7600. }
  7601. else {
  7602. gl.disable(gl.STENCIL_TEST);
  7603. }
  7604. this._isStencilTestDirty = false;
  7605. }
  7606. // Stencil mask
  7607. if (this._isStencilMaskDirty) {
  7608. gl.stencilMask(this.stencilMask);
  7609. this._isStencilMaskDirty = false;
  7610. }
  7611. // Stencil func
  7612. if (this._isStencilFuncDirty) {
  7613. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7614. this._isStencilFuncDirty = false;
  7615. }
  7616. // Stencil op
  7617. if (this._isStencilOpDirty) {
  7618. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7619. this._isStencilOpDirty = false;
  7620. }
  7621. };
  7622. return _StencilState;
  7623. }());
  7624. Internals._StencilState = _StencilState;
  7625. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7626. })(BABYLON || (BABYLON = {}));
  7627. //# sourceMappingURL=babylon.stencilState.js.map
  7628. var BABYLON;
  7629. (function (BABYLON) {
  7630. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7631. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7632. };
  7633. var compileRawShader = function (gl, source, type) {
  7634. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7635. gl.shaderSource(shader, source);
  7636. gl.compileShader(shader);
  7637. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7638. var log = gl.getShaderInfoLog(shader);
  7639. if (log) {
  7640. throw new Error(log);
  7641. }
  7642. }
  7643. if (!shader) {
  7644. throw new Error("Something went wrong while compile the shader.");
  7645. }
  7646. return shader;
  7647. };
  7648. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7649. var magFilter = gl.NEAREST;
  7650. var minFilter = gl.NEAREST;
  7651. switch (samplingMode) {
  7652. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7653. magFilter = gl.LINEAR;
  7654. if (generateMipMaps) {
  7655. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7656. }
  7657. else {
  7658. minFilter = gl.LINEAR;
  7659. }
  7660. break;
  7661. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7662. magFilter = gl.LINEAR;
  7663. if (generateMipMaps) {
  7664. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7665. }
  7666. else {
  7667. minFilter = gl.LINEAR;
  7668. }
  7669. break;
  7670. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7671. magFilter = gl.NEAREST;
  7672. if (generateMipMaps) {
  7673. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7674. }
  7675. else {
  7676. minFilter = gl.NEAREST;
  7677. }
  7678. break;
  7679. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7680. magFilter = gl.NEAREST;
  7681. if (generateMipMaps) {
  7682. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7683. }
  7684. else {
  7685. minFilter = gl.NEAREST;
  7686. }
  7687. break;
  7688. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7689. magFilter = gl.NEAREST;
  7690. if (generateMipMaps) {
  7691. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7692. }
  7693. else {
  7694. minFilter = gl.LINEAR;
  7695. }
  7696. break;
  7697. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7698. magFilter = gl.NEAREST;
  7699. if (generateMipMaps) {
  7700. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7701. }
  7702. else {
  7703. minFilter = gl.LINEAR;
  7704. }
  7705. break;
  7706. case BABYLON.Texture.NEAREST_LINEAR:
  7707. magFilter = gl.NEAREST;
  7708. minFilter = gl.LINEAR;
  7709. break;
  7710. case BABYLON.Texture.NEAREST_NEAREST:
  7711. magFilter = gl.NEAREST;
  7712. minFilter = gl.NEAREST;
  7713. break;
  7714. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7715. magFilter = gl.LINEAR;
  7716. if (generateMipMaps) {
  7717. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7718. }
  7719. else {
  7720. minFilter = gl.NEAREST;
  7721. }
  7722. break;
  7723. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7724. magFilter = gl.LINEAR;
  7725. if (generateMipMaps) {
  7726. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7727. }
  7728. else {
  7729. minFilter = gl.NEAREST;
  7730. }
  7731. break;
  7732. case BABYLON.Texture.LINEAR_LINEAR:
  7733. magFilter = gl.LINEAR;
  7734. minFilter = gl.LINEAR;
  7735. break;
  7736. case BABYLON.Texture.LINEAR_NEAREST:
  7737. magFilter = gl.LINEAR;
  7738. minFilter = gl.NEAREST;
  7739. break;
  7740. }
  7741. return {
  7742. min: minFilter,
  7743. mag: magFilter
  7744. };
  7745. };
  7746. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7747. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7748. var img;
  7749. var onload = function () {
  7750. loadedImages[index] = img;
  7751. loadedImages._internalCount++;
  7752. if (scene) {
  7753. scene._removePendingData(img);
  7754. }
  7755. if (loadedImages._internalCount === 6) {
  7756. onfinish(loadedImages);
  7757. }
  7758. };
  7759. var onerror = function (message, exception) {
  7760. if (scene) {
  7761. scene._removePendingData(img);
  7762. }
  7763. if (onErrorCallBack) {
  7764. onErrorCallBack(message, exception);
  7765. }
  7766. };
  7767. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7768. if (scene) {
  7769. scene._addPendingData(img);
  7770. }
  7771. };
  7772. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7773. if (onError === void 0) { onError = null; }
  7774. var loadedImages = [];
  7775. loadedImages._internalCount = 0;
  7776. for (var index = 0; index < 6; index++) {
  7777. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7778. }
  7779. };
  7780. var BufferPointer = /** @class */ (function () {
  7781. function BufferPointer() {
  7782. }
  7783. return BufferPointer;
  7784. }());
  7785. var InstancingAttributeInfo = /** @class */ (function () {
  7786. function InstancingAttributeInfo() {
  7787. }
  7788. return InstancingAttributeInfo;
  7789. }());
  7790. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7791. /**
  7792. * Define options used to create a render target texture
  7793. */
  7794. var RenderTargetCreationOptions = /** @class */ (function () {
  7795. function RenderTargetCreationOptions() {
  7796. }
  7797. return RenderTargetCreationOptions;
  7798. }());
  7799. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7800. /**
  7801. * Regroup several parameters relative to the browser in use
  7802. */
  7803. var EngineCapabilities = /** @class */ (function () {
  7804. function EngineCapabilities() {
  7805. }
  7806. return EngineCapabilities;
  7807. }());
  7808. BABYLON.EngineCapabilities = EngineCapabilities;
  7809. /**
  7810. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7811. */
  7812. var Engine = /** @class */ (function () {
  7813. /**
  7814. * @constructor
  7815. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7816. * @param {boolean} [antialias] - enable antialias
  7817. * @param options - further options to be sent to the getContext function
  7818. */
  7819. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7820. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7821. var _this = this;
  7822. // Public members
  7823. this.forcePOTTextures = false;
  7824. this.isFullscreen = false;
  7825. this.isPointerLock = false;
  7826. this.cullBackFaces = true;
  7827. this.renderEvenInBackground = true;
  7828. this.preventCacheWipeBetweenFrames = false;
  7829. // To enable/disable IDB support and avoid XHR on .manifest
  7830. this.enableOfflineSupport = false;
  7831. this.scenes = new Array();
  7832. this.postProcesses = new Array();
  7833. // Observables
  7834. /**
  7835. * Observable event triggered each time the rendering canvas is resized
  7836. */
  7837. this.onResizeObservable = new BABYLON.Observable();
  7838. /**
  7839. * Observable event triggered each time the canvas loses focus
  7840. */
  7841. this.onCanvasBlurObservable = new BABYLON.Observable();
  7842. /**
  7843. * Observable event triggered each time the canvas gains focus
  7844. */
  7845. this.onCanvasFocusObservable = new BABYLON.Observable();
  7846. /**
  7847. * Observable event triggered each time the canvas receives pointerout event
  7848. */
  7849. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7850. /**
  7851. * Observable event triggered before each texture is initialized
  7852. */
  7853. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7854. //WebVR
  7855. this._vrDisplay = undefined;
  7856. this._vrSupported = false;
  7857. this._vrExclusivePointerMode = false;
  7858. // Uniform buffers list
  7859. this.disableUniformBuffers = false;
  7860. this._uniformBuffers = new Array();
  7861. // Observables
  7862. /**
  7863. * Observable raised when the engine begins a new frame
  7864. */
  7865. this.onBeginFrameObservable = new BABYLON.Observable();
  7866. /**
  7867. * Observable raised when the engine ends the current frame
  7868. */
  7869. this.onEndFrameObservable = new BABYLON.Observable();
  7870. /**
  7871. * Observable raised when the engine is about to compile a shader
  7872. */
  7873. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7874. /**
  7875. * Observable raised when the engine has jsut compiled a shader
  7876. */
  7877. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7878. this._windowIsBackground = false;
  7879. this._webGLVersion = 1.0;
  7880. this._badOS = false;
  7881. this._badDesktopOS = false;
  7882. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7883. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7884. this.onVRRequestPresentStart = new BABYLON.Observable();
  7885. this._colorWrite = true;
  7886. this._drawCalls = new BABYLON.PerfCounter();
  7887. this._renderingQueueLaunched = false;
  7888. this._activeRenderLoops = new Array();
  7889. // Deterministic lockstepMaxSteps
  7890. this._deterministicLockstep = false;
  7891. this._lockstepMaxSteps = 4;
  7892. // Lost context
  7893. this.onContextLostObservable = new BABYLON.Observable();
  7894. this.onContextRestoredObservable = new BABYLON.Observable();
  7895. this._contextWasLost = false;
  7896. this._doNotHandleContextLost = false;
  7897. // FPS
  7898. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7899. this._fps = 60;
  7900. this._deltaTime = 0;
  7901. /**
  7902. * Turn this value on if you want to pause FPS computation when in background
  7903. */
  7904. this.disablePerformanceMonitorInBackground = false;
  7905. // States
  7906. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7907. this._stencilState = new BABYLON.Internals._StencilState();
  7908. this._alphaState = new BABYLON.Internals._AlphaState();
  7909. this._alphaMode = Engine.ALPHA_DISABLE;
  7910. // Cache
  7911. this._internalTexturesCache = new Array();
  7912. this._activeTexturesCache = {};
  7913. this._compiledEffects = {};
  7914. this._vertexAttribArraysEnabled = [];
  7915. this._uintIndicesCurrentlySet = false;
  7916. this._currentBoundBuffer = new Array();
  7917. this._currentBufferPointers = new Array();
  7918. this._currentInstanceLocations = new Array();
  7919. this._currentInstanceBuffers = new Array();
  7920. this._vaoRecordInProgress = false;
  7921. this._mustWipeVertexAttributes = false;
  7922. // Hardware supported Compressed Textures
  7923. this._texturesSupported = new Array();
  7924. this._onVRFullScreenTriggered = function () {
  7925. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7926. //get the old size before we change
  7927. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7928. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7929. //get the width and height, change the render size
  7930. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7931. _this.setHardwareScalingLevel(1);
  7932. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7933. }
  7934. else {
  7935. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7936. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7937. }
  7938. };
  7939. var canvas = null;
  7940. Engine.Instances.push(this);
  7941. if (!canvasOrContext) {
  7942. return;
  7943. }
  7944. options = options || {};
  7945. if (canvasOrContext.getContext) {
  7946. canvas = canvasOrContext;
  7947. this._renderingCanvas = canvas;
  7948. if (antialias != null) {
  7949. options.antialias = antialias;
  7950. }
  7951. if (options.deterministicLockstep === undefined) {
  7952. options.deterministicLockstep = false;
  7953. }
  7954. if (options.lockstepMaxSteps === undefined) {
  7955. options.lockstepMaxSteps = 4;
  7956. }
  7957. if (options.preserveDrawingBuffer === undefined) {
  7958. options.preserveDrawingBuffer = false;
  7959. }
  7960. if (options.audioEngine === undefined) {
  7961. options.audioEngine = true;
  7962. }
  7963. if (options.stencil === undefined) {
  7964. options.stencil = true;
  7965. }
  7966. this._deterministicLockstep = options.deterministicLockstep;
  7967. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7968. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  7969. // GL
  7970. if (!options.disableWebGL2Support) {
  7971. try {
  7972. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7973. if (this._gl) {
  7974. this._webGLVersion = 2.0;
  7975. }
  7976. }
  7977. catch (e) {
  7978. // Do nothing
  7979. }
  7980. }
  7981. if (!this._gl) {
  7982. if (!canvas) {
  7983. throw new Error("The provided canvas is null or undefined.");
  7984. }
  7985. try {
  7986. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7987. }
  7988. catch (e) {
  7989. throw new Error("WebGL not supported");
  7990. }
  7991. }
  7992. if (!this._gl) {
  7993. throw new Error("WebGL not supported");
  7994. }
  7995. this._onCanvasFocus = function () {
  7996. _this.onCanvasFocusObservable.notifyObservers(_this);
  7997. };
  7998. this._onCanvasBlur = function () {
  7999. _this.onCanvasBlurObservable.notifyObservers(_this);
  8000. };
  8001. canvas.addEventListener("focus", this._onCanvasFocus);
  8002. canvas.addEventListener("blur", this._onCanvasBlur);
  8003. this._onBlur = function () {
  8004. if (_this.disablePerformanceMonitorInBackground) {
  8005. _this._performanceMonitor.disable();
  8006. }
  8007. _this._windowIsBackground = true;
  8008. };
  8009. this._onFocus = function () {
  8010. if (_this.disablePerformanceMonitorInBackground) {
  8011. _this._performanceMonitor.enable();
  8012. }
  8013. _this._windowIsBackground = false;
  8014. };
  8015. this._onCanvasPointerOut = function () {
  8016. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8017. };
  8018. window.addEventListener("blur", this._onBlur);
  8019. window.addEventListener("focus", this._onFocus);
  8020. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8021. // Context lost
  8022. if (!this._doNotHandleContextLost) {
  8023. this._onContextLost = function (evt) {
  8024. evt.preventDefault();
  8025. _this._contextWasLost = true;
  8026. BABYLON.Tools.Warn("WebGL context lost.");
  8027. _this.onContextLostObservable.notifyObservers(_this);
  8028. };
  8029. this._onContextRestored = function (evt) {
  8030. // Adding a timeout to avoid race condition at browser level
  8031. setTimeout(function () {
  8032. // Rebuild gl context
  8033. _this._initGLContext();
  8034. // Rebuild effects
  8035. _this._rebuildEffects();
  8036. // Rebuild textures
  8037. _this._rebuildInternalTextures();
  8038. // Rebuild buffers
  8039. _this._rebuildBuffers();
  8040. // Cache
  8041. _this.wipeCaches(true);
  8042. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8043. _this.onContextRestoredObservable.notifyObservers(_this);
  8044. _this._contextWasLost = false;
  8045. }, 0);
  8046. };
  8047. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8048. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8049. }
  8050. }
  8051. else {
  8052. this._gl = canvasOrContext;
  8053. this._renderingCanvas = this._gl.canvas;
  8054. if (this._gl.renderbufferStorageMultisample) {
  8055. this._webGLVersion = 2.0;
  8056. }
  8057. options.stencil = this._gl.getContextAttributes().stencil;
  8058. }
  8059. // Viewport
  8060. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8061. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8062. this.resize();
  8063. this._isStencilEnable = options.stencil ? true : false;
  8064. this._initGLContext();
  8065. if (canvas) {
  8066. // Fullscreen
  8067. this._onFullscreenChange = function () {
  8068. if (document.fullscreen !== undefined) {
  8069. _this.isFullscreen = document.fullscreen;
  8070. }
  8071. else if (document.mozFullScreen !== undefined) {
  8072. _this.isFullscreen = document.mozFullScreen;
  8073. }
  8074. else if (document.webkitIsFullScreen !== undefined) {
  8075. _this.isFullscreen = document.webkitIsFullScreen;
  8076. }
  8077. else if (document.msIsFullScreen !== undefined) {
  8078. _this.isFullscreen = document.msIsFullScreen;
  8079. }
  8080. // Pointer lock
  8081. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8082. canvas.requestPointerLock = canvas.requestPointerLock ||
  8083. canvas.msRequestPointerLock ||
  8084. canvas.mozRequestPointerLock ||
  8085. canvas.webkitRequestPointerLock;
  8086. if (canvas.requestPointerLock) {
  8087. canvas.requestPointerLock();
  8088. }
  8089. }
  8090. };
  8091. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8092. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8093. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8094. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8095. // Pointer lock
  8096. this._onPointerLockChange = function () {
  8097. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8098. document.webkitPointerLockElement === canvas ||
  8099. document.msPointerLockElement === canvas ||
  8100. document.pointerLockElement === canvas);
  8101. };
  8102. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8103. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8104. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8105. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8106. this._onVRDisplayPointerRestricted = function () {
  8107. if (canvas) {
  8108. canvas.requestPointerLock();
  8109. }
  8110. };
  8111. this._onVRDisplayPointerUnrestricted = function () {
  8112. document.exitPointerLock();
  8113. };
  8114. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8115. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8116. }
  8117. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8118. Engine.audioEngine = new BABYLON.AudioEngine();
  8119. }
  8120. // Prepare buffer pointers
  8121. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8122. this._currentBufferPointers[i] = new BufferPointer();
  8123. }
  8124. // Load WebVR Devices
  8125. if (options.autoEnableWebVR) {
  8126. this.initWebVR();
  8127. }
  8128. // Detect if we are running on a faulty buggy OS.
  8129. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8130. // Detect if we are running on a faulty buggy desktop OS.
  8131. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8132. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8133. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8134. }
  8135. Object.defineProperty(Engine, "LastCreatedEngine", {
  8136. get: function () {
  8137. if (Engine.Instances.length === 0) {
  8138. return null;
  8139. }
  8140. return Engine.Instances[Engine.Instances.length - 1];
  8141. },
  8142. enumerable: true,
  8143. configurable: true
  8144. });
  8145. Object.defineProperty(Engine, "LastCreatedScene", {
  8146. get: function () {
  8147. var lastCreatedEngine = Engine.LastCreatedEngine;
  8148. if (!lastCreatedEngine) {
  8149. return null;
  8150. }
  8151. if (lastCreatedEngine.scenes.length === 0) {
  8152. return null;
  8153. }
  8154. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8155. },
  8156. enumerable: true,
  8157. configurable: true
  8158. });
  8159. /**
  8160. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8161. */
  8162. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8163. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8164. var engine = Engine.Instances[engineIndex];
  8165. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8166. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8167. }
  8168. }
  8169. };
  8170. Object.defineProperty(Engine, "NEVER", {
  8171. get: function () {
  8172. return Engine._NEVER;
  8173. },
  8174. enumerable: true,
  8175. configurable: true
  8176. });
  8177. Object.defineProperty(Engine, "ALWAYS", {
  8178. get: function () {
  8179. return Engine._ALWAYS;
  8180. },
  8181. enumerable: true,
  8182. configurable: true
  8183. });
  8184. Object.defineProperty(Engine, "LESS", {
  8185. get: function () {
  8186. return Engine._LESS;
  8187. },
  8188. enumerable: true,
  8189. configurable: true
  8190. });
  8191. Object.defineProperty(Engine, "EQUAL", {
  8192. get: function () {
  8193. return Engine._EQUAL;
  8194. },
  8195. enumerable: true,
  8196. configurable: true
  8197. });
  8198. Object.defineProperty(Engine, "LEQUAL", {
  8199. get: function () {
  8200. return Engine._LEQUAL;
  8201. },
  8202. enumerable: true,
  8203. configurable: true
  8204. });
  8205. Object.defineProperty(Engine, "GREATER", {
  8206. get: function () {
  8207. return Engine._GREATER;
  8208. },
  8209. enumerable: true,
  8210. configurable: true
  8211. });
  8212. Object.defineProperty(Engine, "GEQUAL", {
  8213. get: function () {
  8214. return Engine._GEQUAL;
  8215. },
  8216. enumerable: true,
  8217. configurable: true
  8218. });
  8219. Object.defineProperty(Engine, "NOTEQUAL", {
  8220. get: function () {
  8221. return Engine._NOTEQUAL;
  8222. },
  8223. enumerable: true,
  8224. configurable: true
  8225. });
  8226. Object.defineProperty(Engine, "KEEP", {
  8227. get: function () {
  8228. return Engine._KEEP;
  8229. },
  8230. enumerable: true,
  8231. configurable: true
  8232. });
  8233. Object.defineProperty(Engine, "REPLACE", {
  8234. get: function () {
  8235. return Engine._REPLACE;
  8236. },
  8237. enumerable: true,
  8238. configurable: true
  8239. });
  8240. Object.defineProperty(Engine, "INCR", {
  8241. get: function () {
  8242. return Engine._INCR;
  8243. },
  8244. enumerable: true,
  8245. configurable: true
  8246. });
  8247. Object.defineProperty(Engine, "DECR", {
  8248. get: function () {
  8249. return Engine._DECR;
  8250. },
  8251. enumerable: true,
  8252. configurable: true
  8253. });
  8254. Object.defineProperty(Engine, "INVERT", {
  8255. get: function () {
  8256. return Engine._INVERT;
  8257. },
  8258. enumerable: true,
  8259. configurable: true
  8260. });
  8261. Object.defineProperty(Engine, "INCR_WRAP", {
  8262. get: function () {
  8263. return Engine._INCR_WRAP;
  8264. },
  8265. enumerable: true,
  8266. configurable: true
  8267. });
  8268. Object.defineProperty(Engine, "DECR_WRAP", {
  8269. get: function () {
  8270. return Engine._DECR_WRAP;
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8276. get: function () {
  8277. return Engine._ALPHA_DISABLE;
  8278. },
  8279. enumerable: true,
  8280. configurable: true
  8281. });
  8282. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8283. get: function () {
  8284. return Engine._ALPHA_ONEONE;
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. Object.defineProperty(Engine, "ALPHA_ADD", {
  8290. get: function () {
  8291. return Engine._ALPHA_ADD;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8297. get: function () {
  8298. return Engine._ALPHA_COMBINE;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8304. get: function () {
  8305. return Engine._ALPHA_SUBTRACT;
  8306. },
  8307. enumerable: true,
  8308. configurable: true
  8309. });
  8310. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8311. get: function () {
  8312. return Engine._ALPHA_MULTIPLY;
  8313. },
  8314. enumerable: true,
  8315. configurable: true
  8316. });
  8317. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8318. get: function () {
  8319. return Engine._ALPHA_MAXIMIZED;
  8320. },
  8321. enumerable: true,
  8322. configurable: true
  8323. });
  8324. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8325. get: function () {
  8326. return Engine._ALPHA_PREMULTIPLIED;
  8327. },
  8328. enumerable: true,
  8329. configurable: true
  8330. });
  8331. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8332. get: function () {
  8333. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8339. get: function () {
  8340. return Engine._ALPHA_INTERPOLATE;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8346. get: function () {
  8347. return Engine._ALPHA_SCREENMODE;
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8353. get: function () {
  8354. return Engine._DELAYLOADSTATE_NONE;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8360. get: function () {
  8361. return Engine._DELAYLOADSTATE_LOADED;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8367. get: function () {
  8368. return Engine._DELAYLOADSTATE_LOADING;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8374. get: function () {
  8375. return Engine._DELAYLOADSTATE_NOTLOADED;
  8376. },
  8377. enumerable: true,
  8378. configurable: true
  8379. });
  8380. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8381. get: function () {
  8382. return Engine._TEXTUREFORMAT_ALPHA;
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8388. get: function () {
  8389. return Engine._TEXTUREFORMAT_LUMINANCE;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8395. get: function () {
  8396. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8402. get: function () {
  8403. return Engine._TEXTUREFORMAT_RGB;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8409. get: function () {
  8410. return Engine._TEXTUREFORMAT_RGBA;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8416. get: function () {
  8417. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8423. get: function () {
  8424. return Engine._TEXTURETYPE_FLOAT;
  8425. },
  8426. enumerable: true,
  8427. configurable: true
  8428. });
  8429. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8430. get: function () {
  8431. return Engine._TEXTURETYPE_HALF_FLOAT;
  8432. },
  8433. enumerable: true,
  8434. configurable: true
  8435. });
  8436. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8437. get: function () {
  8438. return Engine._SCALEMODE_FLOOR;
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8444. get: function () {
  8445. return Engine._SCALEMODE_NEAREST;
  8446. },
  8447. enumerable: true,
  8448. configurable: true
  8449. });
  8450. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8451. get: function () {
  8452. return Engine._SCALEMODE_CEILING;
  8453. },
  8454. enumerable: true,
  8455. configurable: true
  8456. });
  8457. Object.defineProperty(Engine, "Version", {
  8458. get: function () {
  8459. return "3.1-beta-2";
  8460. },
  8461. enumerable: true,
  8462. configurable: true
  8463. });
  8464. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8465. get: function () {
  8466. return this._vrExclusivePointerMode;
  8467. },
  8468. enumerable: true,
  8469. configurable: true
  8470. });
  8471. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8472. get: function () {
  8473. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8474. },
  8475. enumerable: true,
  8476. configurable: true
  8477. });
  8478. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8479. get: function () {
  8480. return this._webGLVersion < 2 || this.forcePOTTextures;
  8481. },
  8482. enumerable: true,
  8483. configurable: true
  8484. });
  8485. Object.defineProperty(Engine.prototype, "badOS", {
  8486. get: function () {
  8487. return this._badOS;
  8488. },
  8489. enumerable: true,
  8490. configurable: true
  8491. });
  8492. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8493. get: function () {
  8494. return this._badDesktopOS;
  8495. },
  8496. enumerable: true,
  8497. configurable: true
  8498. });
  8499. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8500. get: function () {
  8501. return this._performanceMonitor;
  8502. },
  8503. enumerable: true,
  8504. configurable: true
  8505. });
  8506. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8507. get: function () {
  8508. return this._texturesSupported;
  8509. },
  8510. enumerable: true,
  8511. configurable: true
  8512. });
  8513. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8514. get: function () {
  8515. return this._textureFormatInUse;
  8516. },
  8517. enumerable: true,
  8518. configurable: true
  8519. });
  8520. Object.defineProperty(Engine.prototype, "currentViewport", {
  8521. get: function () {
  8522. return this._cachedViewport;
  8523. },
  8524. enumerable: true,
  8525. configurable: true
  8526. });
  8527. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8528. // Empty texture
  8529. get: function () {
  8530. if (!this._emptyTexture) {
  8531. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8532. }
  8533. return this._emptyTexture;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8539. get: function () {
  8540. if (!this._emptyTexture3D) {
  8541. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8542. }
  8543. return this._emptyTexture3D;
  8544. },
  8545. enumerable: true,
  8546. configurable: true
  8547. });
  8548. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8549. get: function () {
  8550. if (!this._emptyCubeTexture) {
  8551. var faceData = new Uint8Array(4);
  8552. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8553. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8554. }
  8555. return this._emptyCubeTexture;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Engine.prototype._rebuildInternalTextures = function () {
  8561. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8562. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8563. var internalTexture = currentState_1[_i];
  8564. internalTexture._rebuild();
  8565. }
  8566. };
  8567. Engine.prototype._rebuildEffects = function () {
  8568. for (var key in this._compiledEffects) {
  8569. var effect = this._compiledEffects[key];
  8570. effect._prepareEffect();
  8571. }
  8572. BABYLON.Effect.ResetCache();
  8573. };
  8574. Engine.prototype._rebuildBuffers = function () {
  8575. // Index / Vertex
  8576. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8577. var scene = _a[_i];
  8578. scene.resetCachedMaterial();
  8579. scene._rebuildGeometries();
  8580. scene._rebuildTextures();
  8581. }
  8582. // Uniforms
  8583. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8584. var uniformBuffer = _c[_b];
  8585. uniformBuffer._rebuild();
  8586. }
  8587. };
  8588. Engine.prototype._initGLContext = function () {
  8589. // Caps
  8590. this._caps = new EngineCapabilities();
  8591. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8592. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8593. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8594. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8595. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8596. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8597. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8598. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8599. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8600. // Infos
  8601. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8602. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8603. if (rendererInfo != null) {
  8604. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8605. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8606. }
  8607. if (!this._glVendor) {
  8608. this._glVendor = "Unknown vendor";
  8609. }
  8610. if (!this._glRenderer) {
  8611. this._glRenderer = "Unknown renderer";
  8612. }
  8613. // Constants
  8614. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8615. if (this._gl.RGBA16F !== 0x881A) {
  8616. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8617. }
  8618. if (this._gl.RGBA32F !== 0x8814) {
  8619. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8620. }
  8621. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8622. this._gl.DEPTH24_STENCIL8 = 35056;
  8623. }
  8624. // Extensions
  8625. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8626. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8627. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8628. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8629. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8630. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8631. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8632. 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');
  8633. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8634. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8635. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8636. this._caps.highPrecisionShaderSupported = true;
  8637. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8638. if (this._caps.timerQuery) {
  8639. if (this._webGLVersion === 1) {
  8640. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8641. }
  8642. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8643. }
  8644. // Checks if some of the format renders first to allow the use of webgl inspector.
  8645. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8646. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8647. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8648. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8649. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8650. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8651. if (this._webGLVersion > 1) {
  8652. this._gl.HALF_FLOAT_OES = 0x140B;
  8653. }
  8654. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8655. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8656. // Draw buffers
  8657. if (this._webGLVersion > 1) {
  8658. this._caps.drawBuffersExtension = true;
  8659. }
  8660. else {
  8661. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8662. if (drawBuffersExtension !== null) {
  8663. this._caps.drawBuffersExtension = true;
  8664. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8665. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8666. for (var i = 0; i < 16; i++) {
  8667. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8668. }
  8669. }
  8670. else {
  8671. this._caps.drawBuffersExtension = false;
  8672. }
  8673. }
  8674. // Depth Texture
  8675. if (this._webGLVersion > 1) {
  8676. this._caps.depthTextureExtension = true;
  8677. }
  8678. else {
  8679. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8680. if (depthTextureExtension != null) {
  8681. this._caps.depthTextureExtension = true;
  8682. }
  8683. }
  8684. // Vertex array object
  8685. if (this._webGLVersion > 1) {
  8686. this._caps.vertexArrayObject = true;
  8687. }
  8688. else {
  8689. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8690. if (vertexArrayObjectExtension != null) {
  8691. this._caps.vertexArrayObject = true;
  8692. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8693. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8694. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8695. }
  8696. else {
  8697. this._caps.vertexArrayObject = false;
  8698. }
  8699. }
  8700. // Instances count
  8701. if (this._webGLVersion > 1) {
  8702. this._caps.instancedArrays = true;
  8703. }
  8704. else {
  8705. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8706. if (instanceExtension != null) {
  8707. this._caps.instancedArrays = true;
  8708. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8709. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8710. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8711. }
  8712. else {
  8713. this._caps.instancedArrays = false;
  8714. }
  8715. }
  8716. // Intelligently add supported compressed formats in order to check for.
  8717. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8718. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8719. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8720. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8721. if (this._caps.astc)
  8722. this.texturesSupported.push('-astc.ktx');
  8723. if (this._caps.s3tc)
  8724. this.texturesSupported.push('-dxt.ktx');
  8725. if (this._caps.pvrtc)
  8726. this.texturesSupported.push('-pvrtc.ktx');
  8727. if (this._caps.etc2)
  8728. this.texturesSupported.push('-etc2.ktx');
  8729. if (this._caps.etc1)
  8730. this.texturesSupported.push('-etc1.ktx');
  8731. if (this._gl.getShaderPrecisionFormat) {
  8732. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8733. if (highp) {
  8734. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8735. }
  8736. }
  8737. // Depth buffer
  8738. this.setDepthBuffer(true);
  8739. this.setDepthFunctionToLessOrEqual();
  8740. this.setDepthWrite(true);
  8741. };
  8742. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8743. get: function () {
  8744. return this._webGLVersion;
  8745. },
  8746. enumerable: true,
  8747. configurable: true
  8748. });
  8749. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8750. /**
  8751. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8752. */
  8753. get: function () {
  8754. return this._isStencilEnable;
  8755. },
  8756. enumerable: true,
  8757. configurable: true
  8758. });
  8759. Engine.prototype._prepareWorkingCanvas = function () {
  8760. if (this._workingCanvas) {
  8761. return;
  8762. }
  8763. this._workingCanvas = document.createElement("canvas");
  8764. var context = this._workingCanvas.getContext("2d");
  8765. if (context) {
  8766. this._workingContext = context;
  8767. }
  8768. };
  8769. Engine.prototype.resetTextureCache = function () {
  8770. for (var key in this._activeTexturesCache) {
  8771. this._activeTexturesCache[key] = null;
  8772. }
  8773. };
  8774. Engine.prototype.isDeterministicLockStep = function () {
  8775. return this._deterministicLockstep;
  8776. };
  8777. Engine.prototype.getLockstepMaxSteps = function () {
  8778. return this._lockstepMaxSteps;
  8779. };
  8780. Engine.prototype.getGlInfo = function () {
  8781. return {
  8782. vendor: this._glVendor,
  8783. renderer: this._glRenderer,
  8784. version: this._glVersion
  8785. };
  8786. };
  8787. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8788. if (useScreen === void 0) { useScreen = false; }
  8789. var viewport = camera.viewport;
  8790. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8791. };
  8792. Engine.prototype.getRenderWidth = function (useScreen) {
  8793. if (useScreen === void 0) { useScreen = false; }
  8794. if (!useScreen && this._currentRenderTarget) {
  8795. return this._currentRenderTarget.width;
  8796. }
  8797. return this._gl.drawingBufferWidth;
  8798. };
  8799. Engine.prototype.getRenderHeight = function (useScreen) {
  8800. if (useScreen === void 0) { useScreen = false; }
  8801. if (!useScreen && this._currentRenderTarget) {
  8802. return this._currentRenderTarget.height;
  8803. }
  8804. return this._gl.drawingBufferHeight;
  8805. };
  8806. Engine.prototype.getRenderingCanvas = function () {
  8807. return this._renderingCanvas;
  8808. };
  8809. Engine.prototype.getRenderingCanvasClientRect = function () {
  8810. if (!this._renderingCanvas) {
  8811. return null;
  8812. }
  8813. return this._renderingCanvas.getBoundingClientRect();
  8814. };
  8815. Engine.prototype.setHardwareScalingLevel = function (level) {
  8816. this._hardwareScalingLevel = level;
  8817. this.resize();
  8818. };
  8819. Engine.prototype.getHardwareScalingLevel = function () {
  8820. return this._hardwareScalingLevel;
  8821. };
  8822. Engine.prototype.getLoadedTexturesCache = function () {
  8823. return this._internalTexturesCache;
  8824. };
  8825. Engine.prototype.getCaps = function () {
  8826. return this._caps;
  8827. };
  8828. Object.defineProperty(Engine.prototype, "drawCalls", {
  8829. /** The number of draw calls submitted last frame */
  8830. get: function () {
  8831. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8832. return 0;
  8833. },
  8834. enumerable: true,
  8835. configurable: true
  8836. });
  8837. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8838. get: function () {
  8839. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8840. return null;
  8841. },
  8842. enumerable: true,
  8843. configurable: true
  8844. });
  8845. Engine.prototype.getDepthFunction = function () {
  8846. return this._depthCullingState.depthFunc;
  8847. };
  8848. Engine.prototype.setDepthFunction = function (depthFunc) {
  8849. this._depthCullingState.depthFunc = depthFunc;
  8850. };
  8851. Engine.prototype.setDepthFunctionToGreater = function () {
  8852. this._depthCullingState.depthFunc = this._gl.GREATER;
  8853. };
  8854. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8855. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8856. };
  8857. Engine.prototype.setDepthFunctionToLess = function () {
  8858. this._depthCullingState.depthFunc = this._gl.LESS;
  8859. };
  8860. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8861. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8862. };
  8863. Engine.prototype.getStencilBuffer = function () {
  8864. return this._stencilState.stencilTest;
  8865. };
  8866. Engine.prototype.setStencilBuffer = function (enable) {
  8867. this._stencilState.stencilTest = enable;
  8868. };
  8869. Engine.prototype.getStencilMask = function () {
  8870. return this._stencilState.stencilMask;
  8871. };
  8872. Engine.prototype.setStencilMask = function (mask) {
  8873. this._stencilState.stencilMask = mask;
  8874. };
  8875. Engine.prototype.getStencilFunction = function () {
  8876. return this._stencilState.stencilFunc;
  8877. };
  8878. Engine.prototype.getStencilFunctionReference = function () {
  8879. return this._stencilState.stencilFuncRef;
  8880. };
  8881. Engine.prototype.getStencilFunctionMask = function () {
  8882. return this._stencilState.stencilFuncMask;
  8883. };
  8884. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8885. this._stencilState.stencilFunc = stencilFunc;
  8886. };
  8887. Engine.prototype.setStencilFunctionReference = function (reference) {
  8888. this._stencilState.stencilFuncRef = reference;
  8889. };
  8890. Engine.prototype.setStencilFunctionMask = function (mask) {
  8891. this._stencilState.stencilFuncMask = mask;
  8892. };
  8893. Engine.prototype.getStencilOperationFail = function () {
  8894. return this._stencilState.stencilOpStencilFail;
  8895. };
  8896. Engine.prototype.getStencilOperationDepthFail = function () {
  8897. return this._stencilState.stencilOpDepthFail;
  8898. };
  8899. Engine.prototype.getStencilOperationPass = function () {
  8900. return this._stencilState.stencilOpStencilDepthPass;
  8901. };
  8902. Engine.prototype.setStencilOperationFail = function (operation) {
  8903. this._stencilState.stencilOpStencilFail = operation;
  8904. };
  8905. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8906. this._stencilState.stencilOpDepthFail = operation;
  8907. };
  8908. Engine.prototype.setStencilOperationPass = function (operation) {
  8909. this._stencilState.stencilOpStencilDepthPass = operation;
  8910. };
  8911. Engine.prototype.setDitheringState = function (value) {
  8912. if (value) {
  8913. this._gl.enable(this._gl.DITHER);
  8914. }
  8915. else {
  8916. this._gl.disable(this._gl.DITHER);
  8917. }
  8918. };
  8919. Engine.prototype.setRasterizerState = function (value) {
  8920. if (value) {
  8921. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  8922. }
  8923. else {
  8924. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  8925. }
  8926. };
  8927. /**
  8928. * stop executing a render loop function and remove it from the execution array
  8929. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8930. */
  8931. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8932. if (!renderFunction) {
  8933. this._activeRenderLoops = [];
  8934. return;
  8935. }
  8936. var index = this._activeRenderLoops.indexOf(renderFunction);
  8937. if (index >= 0) {
  8938. this._activeRenderLoops.splice(index, 1);
  8939. }
  8940. };
  8941. Engine.prototype._renderLoop = function () {
  8942. if (!this._contextWasLost) {
  8943. var shouldRender = true;
  8944. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8945. shouldRender = false;
  8946. }
  8947. if (shouldRender) {
  8948. // Start new frame
  8949. this.beginFrame();
  8950. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8951. var renderFunction = this._activeRenderLoops[index];
  8952. renderFunction();
  8953. }
  8954. // Present
  8955. this.endFrame();
  8956. }
  8957. }
  8958. if (this._activeRenderLoops.length > 0) {
  8959. // Register new frame
  8960. var requester = null;
  8961. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8962. requester = this._vrDisplay;
  8963. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8964. }
  8965. else {
  8966. this._renderingQueueLaunched = false;
  8967. }
  8968. };
  8969. /**
  8970. * Register and execute a render loop. The engine can have more than one render function.
  8971. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8972. * @example
  8973. * engine.runRenderLoop(function () {
  8974. * scene.render()
  8975. * })
  8976. */
  8977. Engine.prototype.runRenderLoop = function (renderFunction) {
  8978. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8979. return;
  8980. }
  8981. this._activeRenderLoops.push(renderFunction);
  8982. if (!this._renderingQueueLaunched) {
  8983. this._renderingQueueLaunched = true;
  8984. this._bindedRenderFunction = this._renderLoop.bind(this);
  8985. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8986. }
  8987. };
  8988. /**
  8989. * Toggle full screen mode.
  8990. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8991. * @param {any} options - an options object to be sent to the requestFullscreen function
  8992. */
  8993. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8994. if (this.isFullscreen) {
  8995. BABYLON.Tools.ExitFullscreen();
  8996. }
  8997. else {
  8998. this._pointerLockRequested = requestPointerLock;
  8999. if (this._renderingCanvas) {
  9000. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9001. }
  9002. }
  9003. };
  9004. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9005. if (stencil === void 0) { stencil = false; }
  9006. this.applyStates();
  9007. var mode = 0;
  9008. if (backBuffer && color) {
  9009. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9010. mode |= this._gl.COLOR_BUFFER_BIT;
  9011. }
  9012. if (depth) {
  9013. this._gl.clearDepth(1.0);
  9014. mode |= this._gl.DEPTH_BUFFER_BIT;
  9015. }
  9016. if (stencil) {
  9017. this._gl.clearStencil(0);
  9018. mode |= this._gl.STENCIL_BUFFER_BIT;
  9019. }
  9020. this._gl.clear(mode);
  9021. };
  9022. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9023. var gl = this._gl;
  9024. // Save state
  9025. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9026. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9027. // Change state
  9028. gl.enable(gl.SCISSOR_TEST);
  9029. gl.scissor(x, y, width, height);
  9030. // Clear
  9031. this.clear(clearColor, true, true, true);
  9032. // Restore state
  9033. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9034. if (curScissor === true) {
  9035. gl.enable(gl.SCISSOR_TEST);
  9036. }
  9037. else {
  9038. gl.disable(gl.SCISSOR_TEST);
  9039. }
  9040. };
  9041. /**
  9042. * Set the WebGL's viewport
  9043. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9044. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9045. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9046. */
  9047. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9048. var width = requiredWidth || this.getRenderWidth();
  9049. var height = requiredHeight || this.getRenderHeight();
  9050. var x = viewport.x || 0;
  9051. var y = viewport.y || 0;
  9052. this._cachedViewport = viewport;
  9053. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9054. };
  9055. /**
  9056. * Directly set the WebGL Viewport
  9057. * The x, y, width & height are directly passed to the WebGL call
  9058. * @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.
  9059. */
  9060. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9061. var currentViewport = this._cachedViewport;
  9062. this._cachedViewport = null;
  9063. this._gl.viewport(x, y, width, height);
  9064. return currentViewport;
  9065. };
  9066. Engine.prototype.beginFrame = function () {
  9067. this.onBeginFrameObservable.notifyObservers(this);
  9068. this._measureFps();
  9069. };
  9070. Engine.prototype.endFrame = function () {
  9071. //force a flush in case we are using a bad OS.
  9072. if (this._badOS) {
  9073. this.flushFramebuffer();
  9074. }
  9075. //submit frame to the vr device, if enabled
  9076. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9077. // TODO: We should only submit the frame if we read frameData successfully.
  9078. this._vrDisplay.submitFrame();
  9079. }
  9080. this.onEndFrameObservable.notifyObservers(this);
  9081. };
  9082. /**
  9083. * resize the view according to the canvas' size.
  9084. * @example
  9085. * window.addEventListener("resize", function () {
  9086. * engine.resize();
  9087. * });
  9088. */
  9089. Engine.prototype.resize = function () {
  9090. // We're not resizing the size of the canvas while in VR mode & presenting
  9091. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9092. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9093. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9094. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9095. }
  9096. };
  9097. /**
  9098. * force a specific size of the canvas
  9099. * @param {number} width - the new canvas' width
  9100. * @param {number} height - the new canvas' height
  9101. */
  9102. Engine.prototype.setSize = function (width, height) {
  9103. if (!this._renderingCanvas) {
  9104. return;
  9105. }
  9106. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9107. return;
  9108. }
  9109. this._renderingCanvas.width = width;
  9110. this._renderingCanvas.height = height;
  9111. for (var index = 0; index < this.scenes.length; index++) {
  9112. var scene = this.scenes[index];
  9113. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9114. var cam = scene.cameras[camIndex];
  9115. cam._currentRenderId = 0;
  9116. }
  9117. }
  9118. if (this.onResizeObservable.hasObservers) {
  9119. this.onResizeObservable.notifyObservers(this);
  9120. }
  9121. };
  9122. // WebVR functions
  9123. Engine.prototype.isVRDevicePresent = function () {
  9124. return !!this._vrDisplay;
  9125. };
  9126. Engine.prototype.getVRDevice = function () {
  9127. return this._vrDisplay;
  9128. };
  9129. Engine.prototype.initWebVR = function () {
  9130. var _this = this;
  9131. var notifyObservers = function () {
  9132. var eventArgs = {
  9133. vrDisplay: _this._vrDisplay,
  9134. vrSupported: _this._vrSupported
  9135. };
  9136. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9137. };
  9138. if (!this._onVrDisplayConnect) {
  9139. this._onVrDisplayConnect = function (event) {
  9140. _this._vrDisplay = event.display;
  9141. notifyObservers();
  9142. };
  9143. this._onVrDisplayDisconnect = function () {
  9144. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9145. _this._vrDisplay = undefined;
  9146. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9147. notifyObservers();
  9148. };
  9149. this._onVrDisplayPresentChange = function () {
  9150. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9151. };
  9152. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9153. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9154. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9155. }
  9156. this._getVRDisplays(notifyObservers);
  9157. return this.onVRDisplayChangedObservable;
  9158. };
  9159. Engine.prototype.enableVR = function () {
  9160. var _this = this;
  9161. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9162. var onResolved = function () {
  9163. _this.onVRRequestPresentComplete.notifyObservers(true);
  9164. _this._onVRFullScreenTriggered();
  9165. };
  9166. var onRejected = function () {
  9167. _this.onVRRequestPresentComplete.notifyObservers(false);
  9168. };
  9169. this.onVRRequestPresentStart.notifyObservers(this);
  9170. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9171. }
  9172. };
  9173. Engine.prototype.disableVR = function () {
  9174. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9175. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9176. }
  9177. };
  9178. Engine.prototype._getVRDisplays = function (callback) {
  9179. var _this = this;
  9180. var getWebVRDevices = function (devices) {
  9181. _this._vrSupported = true;
  9182. // note that devices may actually be an empty array. This is fine;
  9183. // we expect this._vrDisplay to be undefined in this case.
  9184. return _this._vrDisplay = devices[0];
  9185. };
  9186. if (navigator.getVRDisplays) {
  9187. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9188. // TODO: System CANNOT support WebVR, despite API presence.
  9189. _this._vrSupported = false;
  9190. callback();
  9191. });
  9192. }
  9193. else {
  9194. // TODO: Browser does not support WebVR
  9195. this._vrDisplay = undefined;
  9196. this._vrSupported = false;
  9197. callback();
  9198. }
  9199. };
  9200. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9201. if (this._currentRenderTarget) {
  9202. this.unBindFramebuffer(this._currentRenderTarget);
  9203. }
  9204. this._currentRenderTarget = texture;
  9205. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9206. var gl = this._gl;
  9207. if (texture.isCube) {
  9208. if (faceIndex === undefined) {
  9209. faceIndex = 0;
  9210. }
  9211. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9212. }
  9213. if (this._cachedViewport && !forceFullscreenViewport) {
  9214. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9215. }
  9216. else {
  9217. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9218. }
  9219. this.wipeCaches();
  9220. };
  9221. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9222. if (this._currentFramebuffer !== framebuffer) {
  9223. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9224. this._currentFramebuffer = framebuffer;
  9225. }
  9226. };
  9227. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9228. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9229. this._currentRenderTarget = null;
  9230. // If MSAA, we need to bitblt back to main texture
  9231. var gl = this._gl;
  9232. if (texture._MSAAFramebuffer) {
  9233. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9234. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9235. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9236. }
  9237. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9238. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9239. gl.generateMipmap(gl.TEXTURE_2D);
  9240. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9241. }
  9242. if (onBeforeUnbind) {
  9243. if (texture._MSAAFramebuffer) {
  9244. // Bind the correct framebuffer
  9245. this.bindUnboundFramebuffer(texture._framebuffer);
  9246. }
  9247. onBeforeUnbind();
  9248. }
  9249. this.bindUnboundFramebuffer(null);
  9250. };
  9251. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9252. if (texture.generateMipMaps) {
  9253. var gl = this._gl;
  9254. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9255. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9256. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9257. }
  9258. };
  9259. Engine.prototype.flushFramebuffer = function () {
  9260. this._gl.flush();
  9261. };
  9262. Engine.prototype.restoreDefaultFramebuffer = function () {
  9263. if (this._currentRenderTarget) {
  9264. this.unBindFramebuffer(this._currentRenderTarget);
  9265. }
  9266. else {
  9267. this.bindUnboundFramebuffer(null);
  9268. }
  9269. if (this._cachedViewport) {
  9270. this.setViewport(this._cachedViewport);
  9271. }
  9272. this.wipeCaches();
  9273. };
  9274. // UBOs
  9275. Engine.prototype.createUniformBuffer = function (elements) {
  9276. var ubo = this._gl.createBuffer();
  9277. if (!ubo) {
  9278. throw new Error("Unable to create uniform buffer");
  9279. }
  9280. this.bindUniformBuffer(ubo);
  9281. if (elements instanceof Float32Array) {
  9282. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9283. }
  9284. else {
  9285. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9286. }
  9287. this.bindUniformBuffer(null);
  9288. ubo.references = 1;
  9289. return ubo;
  9290. };
  9291. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9292. var ubo = this._gl.createBuffer();
  9293. if (!ubo) {
  9294. throw new Error("Unable to create dynamic uniform buffer");
  9295. }
  9296. this.bindUniformBuffer(ubo);
  9297. if (elements instanceof Float32Array) {
  9298. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9299. }
  9300. else {
  9301. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9302. }
  9303. this.bindUniformBuffer(null);
  9304. ubo.references = 1;
  9305. return ubo;
  9306. };
  9307. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9308. this.bindUniformBuffer(uniformBuffer);
  9309. if (offset === undefined) {
  9310. offset = 0;
  9311. }
  9312. if (count === undefined) {
  9313. if (elements instanceof Float32Array) {
  9314. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9315. }
  9316. else {
  9317. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9318. }
  9319. }
  9320. else {
  9321. if (elements instanceof Float32Array) {
  9322. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9323. }
  9324. else {
  9325. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9326. }
  9327. }
  9328. this.bindUniformBuffer(null);
  9329. };
  9330. // VBOs
  9331. Engine.prototype._resetVertexBufferBinding = function () {
  9332. this.bindArrayBuffer(null);
  9333. this._cachedVertexBuffers = null;
  9334. };
  9335. Engine.prototype.createVertexBuffer = function (vertices) {
  9336. var vbo = this._gl.createBuffer();
  9337. if (!vbo) {
  9338. throw new Error("Unable to create vertex buffer");
  9339. }
  9340. this.bindArrayBuffer(vbo);
  9341. if (vertices instanceof Float32Array) {
  9342. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9343. }
  9344. else {
  9345. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9346. }
  9347. this._resetVertexBufferBinding();
  9348. vbo.references = 1;
  9349. return vbo;
  9350. };
  9351. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9352. var vbo = this._gl.createBuffer();
  9353. if (!vbo) {
  9354. throw new Error("Unable to create dynamic vertex buffer");
  9355. }
  9356. this.bindArrayBuffer(vbo);
  9357. if (vertices instanceof Float32Array) {
  9358. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9359. }
  9360. else {
  9361. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9362. }
  9363. this._resetVertexBufferBinding();
  9364. vbo.references = 1;
  9365. return vbo;
  9366. };
  9367. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9368. if (offset === void 0) { offset = 0; }
  9369. // Force cache update
  9370. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9371. this.bindIndexBuffer(indexBuffer);
  9372. var arrayBuffer;
  9373. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9374. arrayBuffer = indices;
  9375. }
  9376. else {
  9377. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9378. }
  9379. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9380. this._resetIndexBufferBinding();
  9381. };
  9382. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9383. this.bindArrayBuffer(vertexBuffer);
  9384. if (offset === undefined) {
  9385. offset = 0;
  9386. }
  9387. if (count === undefined) {
  9388. if (vertices instanceof Float32Array) {
  9389. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9390. }
  9391. else {
  9392. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9393. }
  9394. }
  9395. else {
  9396. if (vertices instanceof Float32Array) {
  9397. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9398. }
  9399. else {
  9400. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9401. }
  9402. }
  9403. this._resetVertexBufferBinding();
  9404. };
  9405. Engine.prototype._resetIndexBufferBinding = function () {
  9406. this.bindIndexBuffer(null);
  9407. this._cachedIndexBuffer = null;
  9408. };
  9409. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9410. var vbo = this._gl.createBuffer();
  9411. if (!vbo) {
  9412. throw new Error("Unable to create index buffer");
  9413. }
  9414. this.bindIndexBuffer(vbo);
  9415. // Check for 32 bits indices
  9416. var arrayBuffer;
  9417. var need32Bits = false;
  9418. if (indices instanceof Uint16Array) {
  9419. arrayBuffer = indices;
  9420. }
  9421. else {
  9422. //check 32 bit support
  9423. if (this._caps.uintIndices) {
  9424. if (indices instanceof Uint32Array) {
  9425. arrayBuffer = indices;
  9426. need32Bits = true;
  9427. }
  9428. else {
  9429. //number[] or Int32Array, check if 32 bit is necessary
  9430. for (var index = 0; index < indices.length; index++) {
  9431. if (indices[index] > 65535) {
  9432. need32Bits = true;
  9433. break;
  9434. }
  9435. }
  9436. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9437. }
  9438. }
  9439. else {
  9440. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9441. arrayBuffer = new Uint16Array(indices);
  9442. }
  9443. }
  9444. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9445. this._resetIndexBufferBinding();
  9446. vbo.references = 1;
  9447. vbo.is32Bits = need32Bits;
  9448. return vbo;
  9449. };
  9450. Engine.prototype.bindArrayBuffer = function (buffer) {
  9451. if (!this._vaoRecordInProgress) {
  9452. this._unbindVertexArrayObject();
  9453. }
  9454. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9455. };
  9456. Engine.prototype.bindUniformBuffer = function (buffer) {
  9457. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9458. };
  9459. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9460. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9461. };
  9462. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9463. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9464. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9465. };
  9466. ;
  9467. Engine.prototype.bindIndexBuffer = function (buffer) {
  9468. if (!this._vaoRecordInProgress) {
  9469. this._unbindVertexArrayObject();
  9470. }
  9471. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9472. };
  9473. Engine.prototype.bindBuffer = function (buffer, target) {
  9474. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9475. this._gl.bindBuffer(target, buffer);
  9476. this._currentBoundBuffer[target] = buffer;
  9477. }
  9478. };
  9479. Engine.prototype.updateArrayBuffer = function (data) {
  9480. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9481. };
  9482. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9483. var pointer = this._currentBufferPointers[indx];
  9484. var changed = false;
  9485. if (!pointer.active) {
  9486. changed = true;
  9487. pointer.active = true;
  9488. pointer.index = indx;
  9489. pointer.size = size;
  9490. pointer.type = type;
  9491. pointer.normalized = normalized;
  9492. pointer.stride = stride;
  9493. pointer.offset = offset;
  9494. pointer.buffer = buffer;
  9495. }
  9496. else {
  9497. if (pointer.buffer !== buffer) {
  9498. pointer.buffer = buffer;
  9499. changed = true;
  9500. }
  9501. if (pointer.size !== size) {
  9502. pointer.size = size;
  9503. changed = true;
  9504. }
  9505. if (pointer.type !== type) {
  9506. pointer.type = type;
  9507. changed = true;
  9508. }
  9509. if (pointer.normalized !== normalized) {
  9510. pointer.normalized = normalized;
  9511. changed = true;
  9512. }
  9513. if (pointer.stride !== stride) {
  9514. pointer.stride = stride;
  9515. changed = true;
  9516. }
  9517. if (pointer.offset !== offset) {
  9518. pointer.offset = offset;
  9519. changed = true;
  9520. }
  9521. }
  9522. if (changed || this._vaoRecordInProgress) {
  9523. this.bindArrayBuffer(buffer);
  9524. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9525. }
  9526. };
  9527. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9528. if (indexBuffer == null) {
  9529. return;
  9530. }
  9531. if (this._cachedIndexBuffer !== indexBuffer) {
  9532. this._cachedIndexBuffer = indexBuffer;
  9533. this.bindIndexBuffer(indexBuffer);
  9534. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9535. }
  9536. };
  9537. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9538. var attributes = effect.getAttributesNames();
  9539. if (!this._vaoRecordInProgress) {
  9540. this._unbindVertexArrayObject();
  9541. }
  9542. this.unbindAllAttributes();
  9543. for (var index = 0; index < attributes.length; index++) {
  9544. var order = effect.getAttributeLocation(index);
  9545. if (order >= 0) {
  9546. var vertexBuffer = vertexBuffers[attributes[index]];
  9547. if (!vertexBuffer) {
  9548. continue;
  9549. }
  9550. this._gl.enableVertexAttribArray(order);
  9551. if (!this._vaoRecordInProgress) {
  9552. this._vertexAttribArraysEnabled[order] = true;
  9553. }
  9554. var buffer = vertexBuffer.getBuffer();
  9555. if (buffer) {
  9556. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9557. if (vertexBuffer.getIsInstanced()) {
  9558. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9559. if (!this._vaoRecordInProgress) {
  9560. this._currentInstanceLocations.push(order);
  9561. this._currentInstanceBuffers.push(buffer);
  9562. }
  9563. }
  9564. }
  9565. }
  9566. }
  9567. };
  9568. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9569. var vao = this._gl.createVertexArray();
  9570. this._vaoRecordInProgress = true;
  9571. this._gl.bindVertexArray(vao);
  9572. this._mustWipeVertexAttributes = true;
  9573. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9574. this.bindIndexBuffer(indexBuffer);
  9575. this._vaoRecordInProgress = false;
  9576. this._gl.bindVertexArray(null);
  9577. return vao;
  9578. };
  9579. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9580. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9581. this._cachedVertexArrayObject = vertexArrayObject;
  9582. this._gl.bindVertexArray(vertexArrayObject);
  9583. this._cachedVertexBuffers = null;
  9584. this._cachedIndexBuffer = null;
  9585. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9586. this._mustWipeVertexAttributes = true;
  9587. }
  9588. };
  9589. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9590. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9591. this._cachedVertexBuffers = vertexBuffer;
  9592. this._cachedEffectForVertexBuffers = effect;
  9593. var attributesCount = effect.getAttributesCount();
  9594. this._unbindVertexArrayObject();
  9595. this.unbindAllAttributes();
  9596. var offset = 0;
  9597. for (var index = 0; index < attributesCount; index++) {
  9598. if (index < vertexDeclaration.length) {
  9599. var order = effect.getAttributeLocation(index);
  9600. if (order >= 0) {
  9601. this._gl.enableVertexAttribArray(order);
  9602. this._vertexAttribArraysEnabled[order] = true;
  9603. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9604. }
  9605. offset += vertexDeclaration[index] * 4;
  9606. }
  9607. }
  9608. }
  9609. this._bindIndexBufferWithCache(indexBuffer);
  9610. };
  9611. Engine.prototype._unbindVertexArrayObject = function () {
  9612. if (!this._cachedVertexArrayObject) {
  9613. return;
  9614. }
  9615. this._cachedVertexArrayObject = null;
  9616. this._gl.bindVertexArray(null);
  9617. };
  9618. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9619. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9620. this._cachedVertexBuffers = vertexBuffers;
  9621. this._cachedEffectForVertexBuffers = effect;
  9622. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9623. }
  9624. this._bindIndexBufferWithCache(indexBuffer);
  9625. };
  9626. Engine.prototype.unbindInstanceAttributes = function () {
  9627. var boundBuffer;
  9628. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9629. var instancesBuffer = this._currentInstanceBuffers[i];
  9630. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9631. boundBuffer = instancesBuffer;
  9632. this.bindArrayBuffer(instancesBuffer);
  9633. }
  9634. var offsetLocation = this._currentInstanceLocations[i];
  9635. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9636. }
  9637. this._currentInstanceBuffers.length = 0;
  9638. this._currentInstanceLocations.length = 0;
  9639. };
  9640. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9641. this._gl.deleteVertexArray(vao);
  9642. };
  9643. Engine.prototype._releaseBuffer = function (buffer) {
  9644. buffer.references--;
  9645. if (buffer.references === 0) {
  9646. this._gl.deleteBuffer(buffer);
  9647. return true;
  9648. }
  9649. return false;
  9650. };
  9651. Engine.prototype.createInstancesBuffer = function (capacity) {
  9652. var buffer = this._gl.createBuffer();
  9653. if (!buffer) {
  9654. throw new Error("Unable to create instance buffer");
  9655. }
  9656. buffer.capacity = capacity;
  9657. this.bindArrayBuffer(buffer);
  9658. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9659. return buffer;
  9660. };
  9661. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9662. this._gl.deleteBuffer(buffer);
  9663. };
  9664. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9665. this.bindArrayBuffer(instancesBuffer);
  9666. if (data) {
  9667. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9668. }
  9669. if (offsetLocations[0].index !== undefined) {
  9670. var stride = 0;
  9671. for (var i = 0; i < offsetLocations.length; i++) {
  9672. var ai = offsetLocations[i];
  9673. stride += ai.attributeSize * 4;
  9674. }
  9675. for (var i = 0; i < offsetLocations.length; i++) {
  9676. var ai = offsetLocations[i];
  9677. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9678. this._gl.enableVertexAttribArray(ai.index);
  9679. this._vertexAttribArraysEnabled[ai.index] = true;
  9680. }
  9681. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9682. this._gl.vertexAttribDivisor(ai.index, 1);
  9683. this._currentInstanceLocations.push(ai.index);
  9684. this._currentInstanceBuffers.push(instancesBuffer);
  9685. }
  9686. }
  9687. else {
  9688. for (var index = 0; index < 4; index++) {
  9689. var offsetLocation = offsetLocations[index];
  9690. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9691. this._gl.enableVertexAttribArray(offsetLocation);
  9692. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9693. }
  9694. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9695. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9696. this._currentInstanceLocations.push(offsetLocation);
  9697. this._currentInstanceBuffers.push(instancesBuffer);
  9698. }
  9699. }
  9700. };
  9701. Engine.prototype.applyStates = function () {
  9702. this._depthCullingState.apply(this._gl);
  9703. this._stencilState.apply(this._gl);
  9704. this._alphaState.apply(this._gl);
  9705. };
  9706. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9707. // Apply states
  9708. this.applyStates();
  9709. this._drawCalls.addCount(1, false);
  9710. // Render
  9711. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9712. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9713. if (instancesCount) {
  9714. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9715. return;
  9716. }
  9717. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9718. };
  9719. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9720. // Apply states
  9721. this.applyStates();
  9722. this._drawCalls.addCount(1, false);
  9723. if (instancesCount) {
  9724. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9725. return;
  9726. }
  9727. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9728. };
  9729. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9730. // Apply states
  9731. this.applyStates();
  9732. this._drawCalls.addCount(1, false);
  9733. if (instancesCount) {
  9734. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9735. return;
  9736. }
  9737. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9738. };
  9739. // Shaders
  9740. Engine.prototype._releaseEffect = function (effect) {
  9741. if (this._compiledEffects[effect._key]) {
  9742. delete this._compiledEffects[effect._key];
  9743. this._deleteProgram(effect.getProgram());
  9744. }
  9745. };
  9746. Engine.prototype._deleteProgram = function (program) {
  9747. if (program) {
  9748. program.__SPECTOR_rebuildProgram = null;
  9749. if (program.transformFeedback) {
  9750. this.deleteTransformFeedback(program.transformFeedback);
  9751. program.transformFeedback = null;
  9752. }
  9753. this._gl.deleteProgram(program);
  9754. }
  9755. };
  9756. /**
  9757. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9758. * @param samplers An array of string used to represent textures
  9759. */
  9760. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9761. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9762. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9763. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9764. if (this._compiledEffects[name]) {
  9765. var compiledEffect = this._compiledEffects[name];
  9766. if (onCompiled && compiledEffect.isReady()) {
  9767. onCompiled(compiledEffect);
  9768. }
  9769. return compiledEffect;
  9770. }
  9771. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9772. effect._key = name;
  9773. this._compiledEffects[name] = effect;
  9774. return effect;
  9775. };
  9776. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9777. if (uniformsNames === void 0) { uniformsNames = []; }
  9778. if (samplers === void 0) { samplers = []; }
  9779. if (defines === void 0) { defines = ""; }
  9780. return this.createEffect({
  9781. vertex: "particles",
  9782. fragmentElement: fragmentName
  9783. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9784. };
  9785. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9786. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9787. context = context || this._gl;
  9788. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9789. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9790. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9791. };
  9792. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9793. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9794. context = context || this._gl;
  9795. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9796. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9797. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9798. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9799. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9800. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9801. return program;
  9802. };
  9803. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9804. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9805. var shaderProgram = context.createProgram();
  9806. if (!shaderProgram) {
  9807. throw new Error("Unable to create program");
  9808. }
  9809. context.attachShader(shaderProgram, vertexShader);
  9810. context.attachShader(shaderProgram, fragmentShader);
  9811. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9812. var transformFeedback = this.createTransformFeedback();
  9813. this.bindTransformFeedback(transformFeedback);
  9814. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9815. shaderProgram.transformFeedback = transformFeedback;
  9816. }
  9817. context.linkProgram(shaderProgram);
  9818. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9819. this.bindTransformFeedback(null);
  9820. }
  9821. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9822. if (!linked) {
  9823. context.validateProgram(shaderProgram);
  9824. var error = context.getProgramInfoLog(shaderProgram);
  9825. if (error) {
  9826. throw new Error(error);
  9827. }
  9828. }
  9829. context.deleteShader(vertexShader);
  9830. context.deleteShader(fragmentShader);
  9831. return shaderProgram;
  9832. };
  9833. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9834. var results = new Array();
  9835. for (var index = 0; index < uniformsNames.length; index++) {
  9836. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9837. }
  9838. return results;
  9839. };
  9840. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9841. var results = [];
  9842. for (var index = 0; index < attributesNames.length; index++) {
  9843. try {
  9844. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9845. }
  9846. catch (e) {
  9847. results.push(-1);
  9848. }
  9849. }
  9850. return results;
  9851. };
  9852. Engine.prototype.enableEffect = function (effect) {
  9853. if (!effect) {
  9854. return;
  9855. }
  9856. // Use program
  9857. this.setProgram(effect.getProgram());
  9858. this._currentEffect = effect;
  9859. if (effect.onBind) {
  9860. effect.onBind(effect);
  9861. }
  9862. effect.onBindObservable.notifyObservers(effect);
  9863. };
  9864. Engine.prototype.setIntArray = function (uniform, array) {
  9865. if (!uniform)
  9866. return;
  9867. this._gl.uniform1iv(uniform, array);
  9868. };
  9869. Engine.prototype.setIntArray2 = function (uniform, array) {
  9870. if (!uniform || array.length % 2 !== 0)
  9871. return;
  9872. this._gl.uniform2iv(uniform, array);
  9873. };
  9874. Engine.prototype.setIntArray3 = function (uniform, array) {
  9875. if (!uniform || array.length % 3 !== 0)
  9876. return;
  9877. this._gl.uniform3iv(uniform, array);
  9878. };
  9879. Engine.prototype.setIntArray4 = function (uniform, array) {
  9880. if (!uniform || array.length % 4 !== 0)
  9881. return;
  9882. this._gl.uniform4iv(uniform, array);
  9883. };
  9884. Engine.prototype.setFloatArray = function (uniform, array) {
  9885. if (!uniform)
  9886. return;
  9887. this._gl.uniform1fv(uniform, array);
  9888. };
  9889. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9890. if (!uniform || array.length % 2 !== 0)
  9891. return;
  9892. this._gl.uniform2fv(uniform, array);
  9893. };
  9894. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9895. if (!uniform || array.length % 3 !== 0)
  9896. return;
  9897. this._gl.uniform3fv(uniform, array);
  9898. };
  9899. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9900. if (!uniform || array.length % 4 !== 0)
  9901. return;
  9902. this._gl.uniform4fv(uniform, array);
  9903. };
  9904. Engine.prototype.setArray = function (uniform, array) {
  9905. if (!uniform)
  9906. return;
  9907. this._gl.uniform1fv(uniform, array);
  9908. };
  9909. Engine.prototype.setArray2 = function (uniform, array) {
  9910. if (!uniform || array.length % 2 !== 0)
  9911. return;
  9912. this._gl.uniform2fv(uniform, array);
  9913. };
  9914. Engine.prototype.setArray3 = function (uniform, array) {
  9915. if (!uniform || array.length % 3 !== 0)
  9916. return;
  9917. this._gl.uniform3fv(uniform, array);
  9918. };
  9919. Engine.prototype.setArray4 = function (uniform, array) {
  9920. if (!uniform || array.length % 4 !== 0)
  9921. return;
  9922. this._gl.uniform4fv(uniform, array);
  9923. };
  9924. Engine.prototype.setMatrices = function (uniform, matrices) {
  9925. if (!uniform)
  9926. return;
  9927. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9928. };
  9929. Engine.prototype.setMatrix = function (uniform, matrix) {
  9930. if (!uniform)
  9931. return;
  9932. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9933. };
  9934. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9935. if (!uniform)
  9936. return;
  9937. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9938. };
  9939. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9940. if (!uniform)
  9941. return;
  9942. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9943. };
  9944. Engine.prototype.setFloat = function (uniform, value) {
  9945. if (!uniform)
  9946. return;
  9947. this._gl.uniform1f(uniform, value);
  9948. };
  9949. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9950. if (!uniform)
  9951. return;
  9952. this._gl.uniform2f(uniform, x, y);
  9953. };
  9954. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9955. if (!uniform)
  9956. return;
  9957. this._gl.uniform3f(uniform, x, y, z);
  9958. };
  9959. Engine.prototype.setBool = function (uniform, bool) {
  9960. if (!uniform)
  9961. return;
  9962. this._gl.uniform1i(uniform, bool);
  9963. };
  9964. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9965. if (!uniform)
  9966. return;
  9967. this._gl.uniform4f(uniform, x, y, z, w);
  9968. };
  9969. Engine.prototype.setColor3 = function (uniform, color3) {
  9970. if (!uniform)
  9971. return;
  9972. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9973. };
  9974. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9975. if (!uniform)
  9976. return;
  9977. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9978. };
  9979. // States
  9980. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9981. if (zOffset === void 0) { zOffset = 0; }
  9982. if (reverseSide === void 0) { reverseSide = false; }
  9983. // Culling
  9984. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9985. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9986. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9987. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9988. if (culling) {
  9989. this._depthCullingState.cullFace = cullFace;
  9990. this._depthCullingState.cull = true;
  9991. }
  9992. else {
  9993. this._depthCullingState.cull = false;
  9994. }
  9995. }
  9996. // Z offset
  9997. this.setZOffset(zOffset);
  9998. };
  9999. Engine.prototype.setZOffset = function (value) {
  10000. this._depthCullingState.zOffset = value;
  10001. };
  10002. Engine.prototype.getZOffset = function () {
  10003. return this._depthCullingState.zOffset;
  10004. };
  10005. Engine.prototype.setDepthBuffer = function (enable) {
  10006. this._depthCullingState.depthTest = enable;
  10007. };
  10008. Engine.prototype.getDepthWrite = function () {
  10009. return this._depthCullingState.depthMask;
  10010. };
  10011. Engine.prototype.setDepthWrite = function (enable) {
  10012. this._depthCullingState.depthMask = enable;
  10013. };
  10014. Engine.prototype.setColorWrite = function (enable) {
  10015. this._gl.colorMask(enable, enable, enable, enable);
  10016. this._colorWrite = enable;
  10017. };
  10018. Engine.prototype.getColorWrite = function () {
  10019. return this._colorWrite;
  10020. };
  10021. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10022. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10023. };
  10024. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10025. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10026. if (this._alphaMode === mode) {
  10027. return;
  10028. }
  10029. switch (mode) {
  10030. case Engine.ALPHA_DISABLE:
  10031. this._alphaState.alphaBlend = false;
  10032. break;
  10033. case Engine.ALPHA_PREMULTIPLIED:
  10034. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10035. this._alphaState.alphaBlend = true;
  10036. break;
  10037. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10038. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10039. this._alphaState.alphaBlend = true;
  10040. break;
  10041. case Engine.ALPHA_COMBINE:
  10042. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10043. this._alphaState.alphaBlend = true;
  10044. break;
  10045. case Engine.ALPHA_ONEONE:
  10046. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10047. this._alphaState.alphaBlend = true;
  10048. break;
  10049. case Engine.ALPHA_ADD:
  10050. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10051. this._alphaState.alphaBlend = true;
  10052. break;
  10053. case Engine.ALPHA_SUBTRACT:
  10054. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10055. this._alphaState.alphaBlend = true;
  10056. break;
  10057. case Engine.ALPHA_MULTIPLY:
  10058. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10059. this._alphaState.alphaBlend = true;
  10060. break;
  10061. case Engine.ALPHA_MAXIMIZED:
  10062. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10063. this._alphaState.alphaBlend = true;
  10064. break;
  10065. case Engine.ALPHA_INTERPOLATE:
  10066. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10067. this._alphaState.alphaBlend = true;
  10068. break;
  10069. case Engine.ALPHA_SCREENMODE:
  10070. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10071. this._alphaState.alphaBlend = true;
  10072. break;
  10073. }
  10074. if (!noDepthWriteChange) {
  10075. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10076. }
  10077. this._alphaMode = mode;
  10078. };
  10079. Engine.prototype.getAlphaMode = function () {
  10080. return this._alphaMode;
  10081. };
  10082. Engine.prototype.setAlphaTesting = function (enable) {
  10083. this._alphaTest = enable;
  10084. };
  10085. Engine.prototype.getAlphaTesting = function () {
  10086. return !!this._alphaTest;
  10087. };
  10088. // Textures
  10089. Engine.prototype.wipeCaches = function (bruteForce) {
  10090. if (this.preventCacheWipeBetweenFrames) {
  10091. return;
  10092. }
  10093. this.resetTextureCache();
  10094. this._currentEffect = null;
  10095. // 6/8/2017: deltakosh: Should not be required anymore.
  10096. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10097. if (bruteForce) {
  10098. this._currentProgram = null;
  10099. this._stencilState.reset();
  10100. this._depthCullingState.reset();
  10101. this.setDepthFunctionToLessOrEqual();
  10102. this._alphaState.reset();
  10103. }
  10104. this._cachedVertexBuffers = null;
  10105. this._cachedIndexBuffer = null;
  10106. this._cachedEffectForVertexBuffers = null;
  10107. this._unbindVertexArrayObject();
  10108. this.bindIndexBuffer(null);
  10109. this.bindArrayBuffer(null);
  10110. };
  10111. /**
  10112. * Set the compressed texture format to use, based on the formats you have, and the formats
  10113. * supported by the hardware / browser.
  10114. *
  10115. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10116. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10117. * to API arguments needed to compressed textures. This puts the burden on the container
  10118. * generator to house the arcane code for determining these for current & future formats.
  10119. *
  10120. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10121. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10122. *
  10123. * Note: The result of this call is not taken into account when a texture is base64.
  10124. *
  10125. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10126. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10127. *
  10128. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10129. * @returns The extension selected.
  10130. */
  10131. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10132. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10133. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10134. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10135. return this._textureFormatInUse = this._texturesSupported[i];
  10136. }
  10137. }
  10138. }
  10139. // actively set format to nothing, to allow this to be called more than once
  10140. // and possibly fail the 2nd time
  10141. this._textureFormatInUse = null;
  10142. return null;
  10143. };
  10144. Engine.prototype._createTexture = function () {
  10145. var texture = this._gl.createTexture();
  10146. if (!texture) {
  10147. throw new Error("Unable to create texture");
  10148. }
  10149. return texture;
  10150. };
  10151. /**
  10152. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10153. * @param {string} urlArg- This contains one of the following:
  10154. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10155. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10156. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10157. *
  10158. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10159. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10160. * @param {Scene} scene- Needed for loading to the correct scene.
  10161. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10162. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10163. * @param {callback} onError- Optional callback to be called upon failure.
  10164. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10165. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10166. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10167. *
  10168. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10169. */
  10170. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10171. var _this = this;
  10172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10173. if (onLoad === void 0) { onLoad = null; }
  10174. if (onError === void 0) { onError = null; }
  10175. if (buffer === void 0) { buffer = null; }
  10176. if (fallBack === void 0) { fallBack = null; }
  10177. if (format === void 0) { format = null; }
  10178. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10179. var fromData = url.substr(0, 5) === "data:";
  10180. var fromBlob = url.substr(0, 5) === "blob:";
  10181. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10182. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10183. // establish the file extension, if possible
  10184. var lastDot = url.lastIndexOf('.');
  10185. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10186. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10187. var isTGA = (extension === ".tga");
  10188. // determine if a ktx file should be substituted
  10189. var isKTX = false;
  10190. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10191. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10192. isKTX = true;
  10193. }
  10194. if (scene) {
  10195. scene._addPendingData(texture);
  10196. }
  10197. texture.url = url;
  10198. texture.generateMipMaps = !noMipmap;
  10199. texture.samplingMode = samplingMode;
  10200. texture.invertY = invertY;
  10201. if (!this._doNotHandleContextLost) {
  10202. // Keep a link to the buffer only if we plan to handle context lost
  10203. texture._buffer = buffer;
  10204. }
  10205. if (onLoad) {
  10206. texture.onLoadedObservable.add(onLoad);
  10207. }
  10208. if (!fallBack)
  10209. this._internalTexturesCache.push(texture);
  10210. var onerror = function () {
  10211. if (scene) {
  10212. scene._removePendingData(texture);
  10213. }
  10214. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10215. if (isKTX) {
  10216. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10217. }
  10218. else if ((isTGA || isDDS) && BABYLON.Tools.UseFallbackTexture) {
  10219. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10220. }
  10221. else if (onError) {
  10222. onError();
  10223. }
  10224. };
  10225. var callback = null;
  10226. // processing for non-image formats
  10227. if (isKTX || isTGA || isDDS) {
  10228. if (isKTX) {
  10229. callback = function (data) {
  10230. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10231. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10232. ktx.uploadLevels(_this._gl, !noMipmap);
  10233. return false;
  10234. }, samplingMode);
  10235. };
  10236. }
  10237. else if (isTGA) {
  10238. callback = function (arrayBuffer) {
  10239. var data = new Uint8Array(arrayBuffer);
  10240. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10241. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10242. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10243. return false;
  10244. }, samplingMode);
  10245. };
  10246. }
  10247. else if (isDDS) {
  10248. callback = function (data) {
  10249. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10250. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10251. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10252. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10253. return false;
  10254. }, samplingMode);
  10255. };
  10256. }
  10257. if (!buffer) {
  10258. BABYLON.Tools.LoadFile(url, function (data) {
  10259. if (callback) {
  10260. callback(data);
  10261. }
  10262. }, undefined, scene ? scene.database : undefined, true, onerror);
  10263. }
  10264. else {
  10265. if (callback) {
  10266. callback(buffer);
  10267. }
  10268. }
  10269. // image format processing
  10270. }
  10271. else {
  10272. var onload = function (img) {
  10273. if (fromBlob && !_this._doNotHandleContextLost) {
  10274. // We need to store the image if we need to rebuild the texture
  10275. // in case of a webgl context lost
  10276. texture._buffer = img;
  10277. }
  10278. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10279. var gl = _this._gl;
  10280. var isPot = (img.width === potWidth && img.height === potHeight);
  10281. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10282. if (isPot) {
  10283. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10284. return false;
  10285. }
  10286. // Using shaders to rescale because canvas.drawImage is lossy
  10287. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10288. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10289. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10290. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10291. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10292. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10293. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10294. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10295. _this._releaseTexture(source);
  10296. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10297. continuationCallback();
  10298. });
  10299. return true;
  10300. }, samplingMode);
  10301. };
  10302. if (!fromData || isBase64)
  10303. if (buffer instanceof HTMLImageElement) {
  10304. onload(buffer);
  10305. }
  10306. else {
  10307. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10308. }
  10309. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10310. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10311. else
  10312. onload(buffer);
  10313. }
  10314. return texture;
  10315. };
  10316. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10317. var _this = this;
  10318. var rtt = this.createRenderTargetTexture({
  10319. width: destination.width,
  10320. height: destination.height,
  10321. }, {
  10322. generateMipMaps: false,
  10323. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10324. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10325. generateDepthBuffer: false,
  10326. generateStencilBuffer: false
  10327. });
  10328. if (!this._rescalePostProcess) {
  10329. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10330. }
  10331. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10332. _this._rescalePostProcess.onApply = function (effect) {
  10333. effect._bindTexture("textureSampler", source);
  10334. };
  10335. var hostingScene = scene;
  10336. if (!hostingScene) {
  10337. hostingScene = _this.scenes[_this.scenes.length - 1];
  10338. }
  10339. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10340. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10341. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10342. _this.unBindFramebuffer(rtt);
  10343. _this._releaseTexture(rtt);
  10344. if (onComplete) {
  10345. onComplete();
  10346. }
  10347. });
  10348. };
  10349. Engine.prototype._getInternalFormat = function (format) {
  10350. var internalFormat = this._gl.RGBA;
  10351. switch (format) {
  10352. case Engine.TEXTUREFORMAT_ALPHA:
  10353. internalFormat = this._gl.ALPHA;
  10354. break;
  10355. case Engine.TEXTUREFORMAT_LUMINANCE:
  10356. internalFormat = this._gl.LUMINANCE;
  10357. break;
  10358. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10359. internalFormat = this._gl.LUMINANCE_ALPHA;
  10360. break;
  10361. case Engine.TEXTUREFORMAT_RGB:
  10362. internalFormat = this._gl.RGB;
  10363. break;
  10364. case Engine.TEXTUREFORMAT_RGBA:
  10365. internalFormat = this._gl.RGBA;
  10366. break;
  10367. }
  10368. return internalFormat;
  10369. };
  10370. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10371. if (compression === void 0) { compression = null; }
  10372. if (!texture) {
  10373. return;
  10374. }
  10375. var internalFormat = this._getInternalFormat(format);
  10376. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10377. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10378. if (!this._doNotHandleContextLost) {
  10379. texture._bufferView = data;
  10380. texture.format = format;
  10381. texture.invertY = invertY;
  10382. texture._compression = compression;
  10383. }
  10384. if (texture.width % 4 !== 0) {
  10385. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10386. }
  10387. if (compression && data) {
  10388. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10389. }
  10390. else {
  10391. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10392. }
  10393. if (texture.generateMipMaps) {
  10394. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10395. }
  10396. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10397. this.resetTextureCache();
  10398. texture.isReady = true;
  10399. };
  10400. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10401. if (compression === void 0) { compression = null; }
  10402. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10403. texture.baseWidth = width;
  10404. texture.baseHeight = height;
  10405. texture.width = width;
  10406. texture.height = height;
  10407. texture.format = format;
  10408. texture.generateMipMaps = generateMipMaps;
  10409. texture.samplingMode = samplingMode;
  10410. texture.invertY = invertY;
  10411. texture._compression = compression;
  10412. if (!this._doNotHandleContextLost) {
  10413. texture._bufferView = data;
  10414. }
  10415. this.updateRawTexture(texture, data, format, invertY, compression);
  10416. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10417. // Filters
  10418. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10419. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10420. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10421. if (generateMipMaps) {
  10422. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10423. }
  10424. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10425. this._internalTexturesCache.push(texture);
  10426. return texture;
  10427. };
  10428. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10429. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10430. texture.baseWidth = width;
  10431. texture.baseHeight = height;
  10432. if (generateMipMaps) {
  10433. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10434. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10435. }
  10436. this.resetTextureCache();
  10437. texture.width = width;
  10438. texture.height = height;
  10439. texture.isReady = false;
  10440. texture.generateMipMaps = generateMipMaps;
  10441. texture.samplingMode = samplingMode;
  10442. this.updateTextureSamplingMode(samplingMode, texture);
  10443. this._internalTexturesCache.push(texture);
  10444. return texture;
  10445. };
  10446. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10447. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10448. if (texture.isCube) {
  10449. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10450. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10451. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10452. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10453. }
  10454. else if (texture.is3D) {
  10455. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10456. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10457. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10458. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10459. }
  10460. else {
  10461. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10462. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10463. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10464. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10465. }
  10466. texture.samplingMode = samplingMode;
  10467. };
  10468. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10469. if (premulAlpha === void 0) { premulAlpha = false; }
  10470. if (!texture) {
  10471. return;
  10472. }
  10473. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10474. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10475. if (premulAlpha) {
  10476. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10477. }
  10478. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10479. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10480. if (texture.generateMipMaps) {
  10481. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10482. }
  10483. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10484. if (premulAlpha) {
  10485. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10486. }
  10487. this.resetTextureCache();
  10488. texture.isReady = true;
  10489. };
  10490. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10491. if (!texture || texture._isDisabled) {
  10492. return;
  10493. }
  10494. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10495. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10496. try {
  10497. // Testing video texture support
  10498. if (this._videoTextureSupported === undefined) {
  10499. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10500. if (this._gl.getError() !== 0) {
  10501. this._videoTextureSupported = false;
  10502. }
  10503. else {
  10504. this._videoTextureSupported = true;
  10505. }
  10506. }
  10507. // Copy video through the current working canvas if video texture is not supported
  10508. if (!this._videoTextureSupported) {
  10509. if (!texture._workingCanvas) {
  10510. texture._workingCanvas = document.createElement("canvas");
  10511. var context = texture._workingCanvas.getContext("2d");
  10512. if (!context) {
  10513. throw new Error("Unable to get 2d context");
  10514. }
  10515. texture._workingContext = context;
  10516. texture._workingCanvas.width = texture.width;
  10517. texture._workingCanvas.height = texture.height;
  10518. }
  10519. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10520. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10521. }
  10522. else {
  10523. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10524. }
  10525. if (texture.generateMipMaps) {
  10526. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10527. }
  10528. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10529. this.resetTextureCache();
  10530. texture.isReady = true;
  10531. }
  10532. catch (ex) {
  10533. // Something unexpected
  10534. // Let's disable the texture
  10535. texture._isDisabled = true;
  10536. }
  10537. };
  10538. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10539. var fullOptions = new RenderTargetCreationOptions();
  10540. if (options !== undefined && typeof options === "object") {
  10541. fullOptions.generateMipMaps = options.generateMipMaps;
  10542. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10543. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10544. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10545. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10546. }
  10547. else {
  10548. fullOptions.generateMipMaps = options;
  10549. fullOptions.generateDepthBuffer = true;
  10550. fullOptions.generateStencilBuffer = false;
  10551. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10552. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10553. }
  10554. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10555. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10556. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10557. }
  10558. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10559. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10560. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10561. }
  10562. var gl = this._gl;
  10563. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10564. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10565. var width = size.width || size;
  10566. var height = size.height || size;
  10567. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10568. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10569. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10570. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10571. }
  10572. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10573. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10574. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10575. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10576. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10577. // Create the framebuffer
  10578. var framebuffer = gl.createFramebuffer();
  10579. this.bindUnboundFramebuffer(framebuffer);
  10580. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10581. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10582. if (fullOptions.generateMipMaps) {
  10583. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10584. }
  10585. // Unbind
  10586. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10587. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10588. this.bindUnboundFramebuffer(null);
  10589. texture._framebuffer = framebuffer;
  10590. texture.baseWidth = width;
  10591. texture.baseHeight = height;
  10592. texture.width = width;
  10593. texture.height = height;
  10594. texture.isReady = true;
  10595. texture.samples = 1;
  10596. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10597. texture.samplingMode = fullOptions.samplingMode;
  10598. texture.type = fullOptions.type;
  10599. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10600. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10601. this.resetTextureCache();
  10602. this._internalTexturesCache.push(texture);
  10603. return texture;
  10604. };
  10605. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10606. var generateMipMaps = false;
  10607. var generateDepthBuffer = true;
  10608. var generateStencilBuffer = false;
  10609. var generateDepthTexture = false;
  10610. var textureCount = 1;
  10611. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10612. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10613. var types = [], samplingModes = [];
  10614. if (options !== undefined) {
  10615. generateMipMaps = options.generateMipMaps;
  10616. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10617. generateStencilBuffer = options.generateStencilBuffer;
  10618. generateDepthTexture = options.generateDepthTexture;
  10619. textureCount = options.textureCount || 1;
  10620. if (options.types) {
  10621. types = options.types;
  10622. }
  10623. if (options.samplingModes) {
  10624. samplingModes = options.samplingModes;
  10625. }
  10626. }
  10627. var gl = this._gl;
  10628. // Create the framebuffer
  10629. var framebuffer = gl.createFramebuffer();
  10630. this.bindUnboundFramebuffer(framebuffer);
  10631. var width = size.width || size;
  10632. var height = size.height || size;
  10633. var textures = [];
  10634. var attachments = [];
  10635. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10636. for (var i = 0; i < textureCount; i++) {
  10637. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10638. var type = types[i] || defaultType;
  10639. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10640. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10641. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10642. }
  10643. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10644. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10645. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10646. }
  10647. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10648. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10649. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10650. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10651. }
  10652. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10653. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10654. textures.push(texture);
  10655. attachments.push(attachment);
  10656. gl.activeTexture(gl["TEXTURE" + i]);
  10657. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10658. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10659. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10660. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10661. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10662. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10663. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10664. if (generateMipMaps) {
  10665. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10666. }
  10667. // Unbind
  10668. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10669. texture._framebuffer = framebuffer;
  10670. texture._depthStencilBuffer = depthStencilBuffer;
  10671. texture.baseWidth = width;
  10672. texture.baseHeight = height;
  10673. texture.width = width;
  10674. texture.height = height;
  10675. texture.isReady = true;
  10676. texture.samples = 1;
  10677. texture.generateMipMaps = generateMipMaps;
  10678. texture.samplingMode = samplingMode;
  10679. texture.type = type;
  10680. texture._generateDepthBuffer = generateDepthBuffer;
  10681. texture._generateStencilBuffer = generateStencilBuffer;
  10682. this._internalTexturesCache.push(texture);
  10683. }
  10684. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10685. // Depth texture
  10686. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10687. gl.activeTexture(gl.TEXTURE0);
  10688. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10689. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10690. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10691. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10693. 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);
  10694. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10695. depthTexture._framebuffer = framebuffer;
  10696. depthTexture.baseWidth = width;
  10697. depthTexture.baseHeight = height;
  10698. depthTexture.width = width;
  10699. depthTexture.height = height;
  10700. depthTexture.isReady = true;
  10701. depthTexture.samples = 1;
  10702. depthTexture.generateMipMaps = generateMipMaps;
  10703. depthTexture.samplingMode = gl.NEAREST;
  10704. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10705. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10706. textures.push(depthTexture);
  10707. this._internalTexturesCache.push(depthTexture);
  10708. }
  10709. gl.drawBuffers(attachments);
  10710. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10711. this.bindUnboundFramebuffer(null);
  10712. this.resetTextureCache();
  10713. return textures;
  10714. };
  10715. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10716. if (samples === void 0) { samples = 1; }
  10717. var depthStencilBuffer = null;
  10718. var gl = this._gl;
  10719. // Create the depth/stencil buffer
  10720. if (generateStencilBuffer) {
  10721. depthStencilBuffer = gl.createRenderbuffer();
  10722. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10723. if (samples > 1) {
  10724. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10725. }
  10726. else {
  10727. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10728. }
  10729. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10730. }
  10731. else if (generateDepthBuffer) {
  10732. depthStencilBuffer = gl.createRenderbuffer();
  10733. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10734. if (samples > 1) {
  10735. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10736. }
  10737. else {
  10738. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10739. }
  10740. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10741. }
  10742. return depthStencilBuffer;
  10743. };
  10744. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10745. if (this.webGLVersion < 2 || !texture) {
  10746. return 1;
  10747. }
  10748. if (texture.samples === samples) {
  10749. return samples;
  10750. }
  10751. var gl = this._gl;
  10752. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10753. // Dispose previous render buffers
  10754. if (texture._depthStencilBuffer) {
  10755. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10756. }
  10757. if (texture._MSAAFramebuffer) {
  10758. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10759. }
  10760. if (texture._MSAARenderBuffer) {
  10761. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10762. }
  10763. if (samples > 1) {
  10764. var framebuffer = gl.createFramebuffer();
  10765. if (!framebuffer) {
  10766. throw new Error("Unable to create multi sampled framebuffer");
  10767. }
  10768. texture._MSAAFramebuffer = framebuffer;
  10769. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10770. var colorRenderbuffer = gl.createRenderbuffer();
  10771. if (!colorRenderbuffer) {
  10772. throw new Error("Unable to create multi sampled framebuffer");
  10773. }
  10774. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10775. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10776. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10777. texture._MSAARenderBuffer = colorRenderbuffer;
  10778. }
  10779. else {
  10780. this.bindUnboundFramebuffer(texture._framebuffer);
  10781. }
  10782. texture.samples = samples;
  10783. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10784. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10785. this.bindUnboundFramebuffer(null);
  10786. return samples;
  10787. };
  10788. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10789. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10790. };
  10791. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10792. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10793. };
  10794. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10795. var gl = this._gl;
  10796. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10797. var generateMipMaps = true;
  10798. var generateDepthBuffer = true;
  10799. var generateStencilBuffer = false;
  10800. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10801. if (options !== undefined) {
  10802. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10803. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10804. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10805. if (options.samplingMode !== undefined) {
  10806. samplingMode = options.samplingMode;
  10807. }
  10808. }
  10809. texture.isCube = true;
  10810. texture.generateMipMaps = generateMipMaps;
  10811. texture.samples = 1;
  10812. texture.samplingMode = samplingMode;
  10813. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10814. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10815. for (var face = 0; face < 6; face++) {
  10816. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10817. }
  10818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10822. // Create the framebuffer
  10823. var framebuffer = gl.createFramebuffer();
  10824. this.bindUnboundFramebuffer(framebuffer);
  10825. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10826. // Mipmaps
  10827. if (texture.generateMipMaps) {
  10828. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10829. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10830. }
  10831. // Unbind
  10832. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10833. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10834. this.bindUnboundFramebuffer(null);
  10835. texture._framebuffer = framebuffer;
  10836. texture.width = size;
  10837. texture.height = size;
  10838. texture.isReady = true;
  10839. this.resetTextureCache();
  10840. this._internalTexturesCache.push(texture);
  10841. return texture;
  10842. };
  10843. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10844. var _this = this;
  10845. if (onLoad === void 0) { onLoad = null; }
  10846. if (onError === void 0) { onError = null; }
  10847. if (forcedExtension === void 0) { forcedExtension = null; }
  10848. var callback = function (loadData) {
  10849. if (!loadData) {
  10850. if (onLoad) {
  10851. onLoad(null);
  10852. }
  10853. return;
  10854. }
  10855. var texture = loadData.texture;
  10856. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10857. texture._lodGenerationScale = scale;
  10858. texture._lodGenerationOffset = offset;
  10859. if (_this._caps.textureLOD) {
  10860. // Do not add extra process if texture lod is supported.
  10861. if (onLoad) {
  10862. onLoad(texture);
  10863. }
  10864. return;
  10865. }
  10866. var mipSlices = 3;
  10867. var gl = _this._gl;
  10868. var width = loadData.width;
  10869. if (!width) {
  10870. return;
  10871. }
  10872. var textures = [];
  10873. for (var i = 0; i < mipSlices; i++) {
  10874. //compute LOD from even spacing in smoothness (matching shader calculation)
  10875. var smoothness = i / (mipSlices - 1);
  10876. var roughness = 1 - smoothness;
  10877. var minLODIndex = offset; // roughness = 0
  10878. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10879. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10880. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10881. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10882. glTextureFromLod.isCube = true;
  10883. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10887. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10888. if (loadData.isDDS) {
  10889. var info = loadData.info;
  10890. var data = loadData.data;
  10891. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10892. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10893. }
  10894. else {
  10895. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10896. }
  10897. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10898. // Wrap in a base texture for easy binding.
  10899. var lodTexture = new BABYLON.BaseTexture(scene);
  10900. lodTexture.isCube = true;
  10901. lodTexture._texture = glTextureFromLod;
  10902. glTextureFromLod.isReady = true;
  10903. textures.push(lodTexture);
  10904. }
  10905. texture._lodTextureHigh = textures[2];
  10906. texture._lodTextureMid = textures[1];
  10907. texture._lodTextureLow = textures[0];
  10908. if (onLoad) {
  10909. onLoad(texture);
  10910. }
  10911. };
  10912. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10913. };
  10914. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10915. var _this = this;
  10916. if (onLoad === void 0) { onLoad = null; }
  10917. if (onError === void 0) { onError = null; }
  10918. if (forcedExtension === void 0) { forcedExtension = null; }
  10919. var gl = this._gl;
  10920. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10921. texture.isCube = true;
  10922. texture.url = rootUrl;
  10923. texture.generateMipMaps = !noMipmap;
  10924. if (!this._doNotHandleContextLost) {
  10925. texture._extension = forcedExtension;
  10926. texture._files = files;
  10927. }
  10928. var isKTX = false;
  10929. var isDDS = false;
  10930. var lastDot = rootUrl.lastIndexOf('.');
  10931. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  10932. if (this._textureFormatInUse) {
  10933. extension = this._textureFormatInUse;
  10934. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  10935. isKTX = true;
  10936. }
  10937. else {
  10938. isDDS = (extension === ".dds");
  10939. }
  10940. var onerror = function (request, exception) {
  10941. if (onError) {
  10942. onError(request.status + " " + request.statusText, exception);
  10943. }
  10944. };
  10945. if (isKTX) {
  10946. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10947. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10948. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10949. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10950. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10951. ktx.uploadLevels(_this._gl, !noMipmap);
  10952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10953. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10954. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10956. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10957. _this.resetTextureCache();
  10958. texture.width = ktx.pixelWidth;
  10959. texture.height = ktx.pixelHeight;
  10960. texture.isReady = true;
  10961. }, undefined, undefined, true, onerror);
  10962. }
  10963. else if (isDDS) {
  10964. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10965. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10966. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10967. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10968. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10969. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10970. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10971. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10972. }
  10973. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10974. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10975. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10976. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10977. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10978. _this.resetTextureCache();
  10979. texture.width = info.width;
  10980. texture.height = info.height;
  10981. texture.isReady = true;
  10982. texture.type = info.textureType;
  10983. if (onLoad) {
  10984. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10985. }
  10986. }, undefined, undefined, true, onerror);
  10987. }
  10988. else {
  10989. if (!files) {
  10990. throw new Error("Cannot load cubemap because files were not defined");
  10991. }
  10992. cascadeLoad(rootUrl, scene, function (imgs) {
  10993. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10994. var height = width;
  10995. _this._prepareWorkingCanvas();
  10996. if (!_this._workingCanvas || !_this._workingContext) {
  10997. return;
  10998. }
  10999. _this._workingCanvas.width = width;
  11000. _this._workingCanvas.height = height;
  11001. var faces = [
  11002. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11003. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11004. ];
  11005. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11006. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11007. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11008. for (var index = 0; index < faces.length; index++) {
  11009. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11010. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11011. }
  11012. if (!noMipmap) {
  11013. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11014. }
  11015. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11016. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  11017. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11018. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11019. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11020. _this.resetTextureCache();
  11021. texture.width = width;
  11022. texture.height = height;
  11023. texture.isReady = true;
  11024. if (format) {
  11025. texture.format = format;
  11026. }
  11027. texture.onLoadedObservable.notifyObservers(texture);
  11028. texture.onLoadedObservable.clear();
  11029. if (onLoad) {
  11030. onLoad();
  11031. }
  11032. }, files, onError);
  11033. }
  11034. this._internalTexturesCache.push(texture);
  11035. return texture;
  11036. };
  11037. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11038. if (compression === void 0) { compression = null; }
  11039. if (level === void 0) { level = 0; }
  11040. texture._bufferViewArray = data;
  11041. texture.format = format;
  11042. texture.type = type;
  11043. texture.invertY = invertY;
  11044. texture._compression = compression;
  11045. var gl = this._gl;
  11046. var textureType = this._getWebGLTextureType(type);
  11047. var internalFormat = this._getInternalFormat(format);
  11048. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11049. var needConversion = false;
  11050. if (internalFormat === gl.RGB) {
  11051. internalFormat = gl.RGBA;
  11052. needConversion = true;
  11053. }
  11054. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11055. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11056. if (texture.width % 4 !== 0) {
  11057. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11058. }
  11059. // Data are known to be in +X +Y +Z -X -Y -Z
  11060. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11061. var faceData = data[faceIndex];
  11062. if (compression) {
  11063. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11064. }
  11065. else {
  11066. if (needConversion) {
  11067. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11068. }
  11069. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11070. }
  11071. }
  11072. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11073. if (isPot && texture.generateMipMaps && level === 0) {
  11074. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11075. }
  11076. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11077. this.resetTextureCache();
  11078. texture.isReady = true;
  11079. };
  11080. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11081. if (compression === void 0) { compression = null; }
  11082. var gl = this._gl;
  11083. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11084. texture.isCube = true;
  11085. texture.generateMipMaps = generateMipMaps;
  11086. texture.format = format;
  11087. texture.type = type;
  11088. if (!this._doNotHandleContextLost) {
  11089. texture._bufferViewArray = data;
  11090. }
  11091. var textureType = this._getWebGLTextureType(type);
  11092. var internalFormat = this._getInternalFormat(format);
  11093. var needConversion = false;
  11094. if (internalFormat === gl.RGB) {
  11095. internalFormat = gl.RGBA;
  11096. needConversion = true;
  11097. }
  11098. var width = size;
  11099. var height = width;
  11100. texture.width = width;
  11101. texture.height = height;
  11102. // Double check on POT to generate Mips.
  11103. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11104. if (!isPot) {
  11105. generateMipMaps = false;
  11106. }
  11107. // Upload data if needed. The texture won't be ready until then.
  11108. if (data) {
  11109. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11110. }
  11111. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11112. // Filters
  11113. if (data && generateMipMaps) {
  11114. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11115. }
  11116. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11117. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11118. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11119. }
  11120. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11122. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11123. }
  11124. else {
  11125. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11126. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11127. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11128. }
  11129. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11130. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11131. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11132. return texture;
  11133. };
  11134. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11135. var _this = this;
  11136. if (onLoad === void 0) { onLoad = null; }
  11137. if (onError === void 0) { onError = null; }
  11138. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11139. if (invertY === void 0) { invertY = false; }
  11140. var gl = this._gl;
  11141. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11142. scene._addPendingData(texture);
  11143. texture.url = url;
  11144. this._internalTexturesCache.push(texture);
  11145. var onerror = function (request, exception) {
  11146. scene._removePendingData(texture);
  11147. if (onError) {
  11148. onError(request.status + " " + request.statusText, exception);
  11149. }
  11150. };
  11151. var internalCallback = function (data) {
  11152. var width = texture.width;
  11153. var faceDataArrays = callback(data);
  11154. if (!faceDataArrays) {
  11155. return;
  11156. }
  11157. if (mipmmapGenerator) {
  11158. var textureType = _this._getWebGLTextureType(type);
  11159. var internalFormat = _this._getInternalFormat(format);
  11160. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11161. var needConversion = false;
  11162. if (internalFormat === gl.RGB) {
  11163. internalFormat = gl.RGBA;
  11164. needConversion = true;
  11165. }
  11166. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11167. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11168. var mipData = mipmmapGenerator(faceDataArrays);
  11169. for (var level = 0; level < mipData.length; level++) {
  11170. var mipSize = width >> level;
  11171. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11172. var mipFaceData = mipData[level][faceIndex];
  11173. if (needConversion) {
  11174. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11175. }
  11176. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11177. }
  11178. }
  11179. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11180. }
  11181. else {
  11182. texture.generateMipMaps = !noMipmap;
  11183. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11184. }
  11185. texture.isReady = true;
  11186. _this.resetTextureCache();
  11187. scene._removePendingData(texture);
  11188. if (onLoad) {
  11189. onLoad();
  11190. }
  11191. };
  11192. BABYLON.Tools.LoadFile(url, function (data) {
  11193. internalCallback(data);
  11194. }, undefined, scene.database, true, onerror);
  11195. return texture;
  11196. };
  11197. ;
  11198. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11199. if (compression === void 0) { compression = null; }
  11200. var internalFormat = this._getInternalFormat(format);
  11201. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11202. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11203. if (!this._doNotHandleContextLost) {
  11204. texture._bufferView = data;
  11205. texture.format = format;
  11206. texture.invertY = invertY;
  11207. texture._compression = compression;
  11208. }
  11209. if (texture.width % 4 !== 0) {
  11210. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11211. }
  11212. if (compression && data) {
  11213. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11214. }
  11215. else {
  11216. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11217. }
  11218. if (texture.generateMipMaps) {
  11219. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11220. }
  11221. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11222. this.resetTextureCache();
  11223. texture.isReady = true;
  11224. };
  11225. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11226. if (compression === void 0) { compression = null; }
  11227. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11228. texture.baseWidth = width;
  11229. texture.baseHeight = height;
  11230. texture.baseDepth = depth;
  11231. texture.width = width;
  11232. texture.height = height;
  11233. texture.depth = depth;
  11234. texture.format = format;
  11235. texture.generateMipMaps = generateMipMaps;
  11236. texture.samplingMode = samplingMode;
  11237. texture.is3D = true;
  11238. if (!this._doNotHandleContextLost) {
  11239. texture._bufferView = data;
  11240. }
  11241. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11242. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11243. // Filters
  11244. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11245. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11246. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11247. if (generateMipMaps) {
  11248. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11249. }
  11250. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11251. this._internalTexturesCache.push(texture);
  11252. return texture;
  11253. };
  11254. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11255. var gl = this._gl;
  11256. if (!gl) {
  11257. return;
  11258. }
  11259. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11260. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11261. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11262. if (!noMipmap && !isCompressed) {
  11263. gl.generateMipmap(gl.TEXTURE_2D);
  11264. }
  11265. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11266. this.resetTextureCache();
  11267. if (scene) {
  11268. scene._removePendingData(texture);
  11269. }
  11270. texture.onLoadedObservable.notifyObservers(texture);
  11271. texture.onLoadedObservable.clear();
  11272. };
  11273. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11274. var _this = this;
  11275. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11276. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11277. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11278. var gl = this._gl;
  11279. if (!gl) {
  11280. return;
  11281. }
  11282. if (!texture._webGLTexture) {
  11283. this.resetTextureCache();
  11284. if (scene) {
  11285. scene._removePendingData(texture);
  11286. }
  11287. return;
  11288. }
  11289. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11290. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11291. texture.baseWidth = width;
  11292. texture.baseHeight = height;
  11293. texture.width = potWidth;
  11294. texture.height = potHeight;
  11295. texture.isReady = true;
  11296. if (processFunction(potWidth, potHeight, function () {
  11297. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11298. })) {
  11299. // Returning as texture needs extra async steps
  11300. return;
  11301. }
  11302. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11303. };
  11304. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11305. // Create new RGBA data container.
  11306. var rgbaData;
  11307. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11308. rgbaData = new Float32Array(width * height * 4);
  11309. }
  11310. else {
  11311. rgbaData = new Uint32Array(width * height * 4);
  11312. }
  11313. // Convert each pixel.
  11314. for (var x = 0; x < width; x++) {
  11315. for (var y = 0; y < height; y++) {
  11316. var index = (y * width + x) * 3;
  11317. var newIndex = (y * width + x) * 4;
  11318. // Map Old Value to new value.
  11319. rgbaData[newIndex + 0] = rgbData[index + 0];
  11320. rgbaData[newIndex + 1] = rgbData[index + 1];
  11321. rgbaData[newIndex + 2] = rgbData[index + 2];
  11322. // Add fully opaque alpha channel.
  11323. rgbaData[newIndex + 3] = 1;
  11324. }
  11325. }
  11326. return rgbaData;
  11327. };
  11328. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11329. var gl = this._gl;
  11330. if (texture._framebuffer) {
  11331. gl.deleteFramebuffer(texture._framebuffer);
  11332. texture._framebuffer = null;
  11333. }
  11334. if (texture._depthStencilBuffer) {
  11335. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11336. texture._depthStencilBuffer = null;
  11337. }
  11338. if (texture._MSAAFramebuffer) {
  11339. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11340. texture._MSAAFramebuffer = null;
  11341. }
  11342. if (texture._MSAARenderBuffer) {
  11343. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11344. texture._MSAARenderBuffer = null;
  11345. }
  11346. };
  11347. Engine.prototype._releaseTexture = function (texture) {
  11348. var gl = this._gl;
  11349. this._releaseFramebufferObjects(texture);
  11350. gl.deleteTexture(texture._webGLTexture);
  11351. // Unbind channels
  11352. this.unbindAllTextures();
  11353. var index = this._internalTexturesCache.indexOf(texture);
  11354. if (index !== -1) {
  11355. this._internalTexturesCache.splice(index, 1);
  11356. }
  11357. // Integrated fixed lod samplers.
  11358. if (texture._lodTextureHigh) {
  11359. texture._lodTextureHigh.dispose();
  11360. }
  11361. if (texture._lodTextureMid) {
  11362. texture._lodTextureMid.dispose();
  11363. }
  11364. if (texture._lodTextureLow) {
  11365. texture._lodTextureLow.dispose();
  11366. }
  11367. };
  11368. Engine.prototype.setProgram = function (program) {
  11369. if (this._currentProgram !== program) {
  11370. this._gl.useProgram(program);
  11371. this._currentProgram = program;
  11372. }
  11373. };
  11374. Engine.prototype.bindSamplers = function (effect) {
  11375. this.setProgram(effect.getProgram());
  11376. var samplers = effect.getSamplers();
  11377. for (var index = 0; index < samplers.length; index++) {
  11378. var uniform = effect.getUniform(samplers[index]);
  11379. this._gl.uniform1i(uniform, index);
  11380. }
  11381. this._currentEffect = null;
  11382. };
  11383. Engine.prototype.activateTextureChannel = function (textureChannel) {
  11384. if (this._activeTextureChannel !== textureChannel) {
  11385. this._gl.activeTexture(textureChannel);
  11386. this._activeTextureChannel = textureChannel;
  11387. }
  11388. };
  11389. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11390. if (this._activeTexturesCache[this._activeTextureChannel] !== texture) {
  11391. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11392. this._activeTexturesCache[this._activeTextureChannel] = texture;
  11393. }
  11394. };
  11395. Engine.prototype._bindTexture = function (channel, texture) {
  11396. if (channel < 0) {
  11397. return;
  11398. }
  11399. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11400. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11401. };
  11402. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11403. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11404. };
  11405. Engine.prototype.unbindAllTextures = function () {
  11406. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11407. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11408. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11409. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11410. if (this.webGLVersion > 1) {
  11411. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11412. }
  11413. }
  11414. };
  11415. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11416. if (channel < 0) {
  11417. return;
  11418. }
  11419. if (this._setTexture(channel, texture)) {
  11420. this._gl.uniform1i(uniform, channel);
  11421. }
  11422. };
  11423. Engine.prototype._setTexture = function (channel, texture) {
  11424. // Not ready?
  11425. if (!texture) {
  11426. if (this._activeTexturesCache[channel] != null) {
  11427. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11428. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11429. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11430. if (this.webGLVersion > 1) {
  11431. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11432. }
  11433. }
  11434. return false;
  11435. }
  11436. // Video
  11437. var alreadyActivated = false;
  11438. if (texture.video) {
  11439. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11440. alreadyActivated = true;
  11441. texture.update();
  11442. }
  11443. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11444. texture.delayLoad();
  11445. return false;
  11446. }
  11447. var internalTexture;
  11448. if (texture.isReady()) {
  11449. internalTexture = texture.getInternalTexture();
  11450. }
  11451. else if (texture.isCube) {
  11452. internalTexture = this.emptyCubeTexture;
  11453. }
  11454. else if (texture.is3D) {
  11455. internalTexture = this.emptyTexture3D;
  11456. }
  11457. else {
  11458. internalTexture = this.emptyTexture;
  11459. }
  11460. if (!alreadyActivated) {
  11461. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11462. }
  11463. if (this._activeTexturesCache[this._activeTextureChannel] === internalTexture) {
  11464. return false;
  11465. }
  11466. if (internalTexture && internalTexture.is3D) {
  11467. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11468. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11469. internalTexture._cachedWrapU = texture.wrapU;
  11470. switch (texture.wrapU) {
  11471. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11472. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11473. break;
  11474. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11475. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11476. break;
  11477. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11478. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11479. break;
  11480. }
  11481. }
  11482. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11483. internalTexture._cachedWrapV = texture.wrapV;
  11484. switch (texture.wrapV) {
  11485. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11486. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11487. break;
  11488. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11489. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11490. break;
  11491. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11492. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11493. break;
  11494. }
  11495. }
  11496. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11497. internalTexture._cachedWrapR = texture.wrapR;
  11498. switch (texture.wrapV) {
  11499. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11500. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11501. break;
  11502. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11503. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11504. break;
  11505. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11506. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11507. break;
  11508. }
  11509. }
  11510. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11511. }
  11512. else if (internalTexture && internalTexture.isCube) {
  11513. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11514. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11515. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11516. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11517. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11518. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11519. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11520. }
  11521. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11522. }
  11523. else {
  11524. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11525. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11526. internalTexture._cachedWrapU = texture.wrapU;
  11527. switch (texture.wrapU) {
  11528. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11529. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11530. break;
  11531. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11532. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11533. break;
  11534. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11535. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11536. break;
  11537. }
  11538. }
  11539. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11540. internalTexture._cachedWrapV = texture.wrapV;
  11541. switch (texture.wrapV) {
  11542. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11543. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11544. break;
  11545. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11546. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11547. break;
  11548. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11549. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11550. break;
  11551. }
  11552. }
  11553. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11554. }
  11555. return true;
  11556. };
  11557. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11558. if (channel < 0 || !uniform) {
  11559. return;
  11560. }
  11561. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11562. this._textureUnits = new Int32Array(textures.length);
  11563. }
  11564. for (var i = 0; i < textures.length; i++) {
  11565. this._textureUnits[i] = channel + i;
  11566. }
  11567. this._gl.uniform1iv(uniform, this._textureUnits);
  11568. for (var index = 0; index < textures.length; index++) {
  11569. this._setTexture(channel + index, textures[index]);
  11570. }
  11571. };
  11572. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11573. var internalTexture = texture.getInternalTexture();
  11574. if (!internalTexture) {
  11575. return;
  11576. }
  11577. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11578. var value = texture.anisotropicFilteringLevel;
  11579. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11580. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11581. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11582. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11583. }
  11584. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11585. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11586. internalTexture._cachedAnisotropicFilteringLevel = value;
  11587. }
  11588. };
  11589. Engine.prototype.readPixels = function (x, y, width, height) {
  11590. var data = new Uint8Array(height * width * 4);
  11591. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11592. return data;
  11593. };
  11594. /**
  11595. * Add an externaly attached data from its key.
  11596. * This method call will fail and return false, if such key already exists.
  11597. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11598. * @param key the unique key that identifies the data
  11599. * @param data the data object to associate to the key for this Engine instance
  11600. * @return true if no such key were already present and the data was added successfully, false otherwise
  11601. */
  11602. Engine.prototype.addExternalData = function (key, data) {
  11603. if (!this._externalData) {
  11604. this._externalData = new BABYLON.StringDictionary();
  11605. }
  11606. return this._externalData.add(key, data);
  11607. };
  11608. /**
  11609. * Get an externaly attached data from its key
  11610. * @param key the unique key that identifies the data
  11611. * @return the associated data, if present (can be null), or undefined if not present
  11612. */
  11613. Engine.prototype.getExternalData = function (key) {
  11614. if (!this._externalData) {
  11615. this._externalData = new BABYLON.StringDictionary();
  11616. }
  11617. return this._externalData.get(key);
  11618. };
  11619. /**
  11620. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11621. * @param key the unique key that identifies the data
  11622. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11623. * @return the associated data, can be null if the factory returned null.
  11624. */
  11625. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11626. if (!this._externalData) {
  11627. this._externalData = new BABYLON.StringDictionary();
  11628. }
  11629. return this._externalData.getOrAddWithFactory(key, factory);
  11630. };
  11631. /**
  11632. * Remove an externaly attached data from the Engine instance
  11633. * @param key the unique key that identifies the data
  11634. * @return true if the data was successfully removed, false if it doesn't exist
  11635. */
  11636. Engine.prototype.removeExternalData = function (key) {
  11637. if (!this._externalData) {
  11638. this._externalData = new BABYLON.StringDictionary();
  11639. }
  11640. return this._externalData.remove(key);
  11641. };
  11642. Engine.prototype.unbindAllAttributes = function () {
  11643. if (this._mustWipeVertexAttributes) {
  11644. this._mustWipeVertexAttributes = false;
  11645. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11646. this._gl.disableVertexAttribArray(i);
  11647. this._vertexAttribArraysEnabled[i] = false;
  11648. this._currentBufferPointers[i].active = false;
  11649. }
  11650. return;
  11651. }
  11652. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11653. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11654. continue;
  11655. }
  11656. this._gl.disableVertexAttribArray(i);
  11657. this._vertexAttribArraysEnabled[i] = false;
  11658. this._currentBufferPointers[i].active = false;
  11659. }
  11660. };
  11661. Engine.prototype.releaseEffects = function () {
  11662. for (var name in this._compiledEffects) {
  11663. this._deleteProgram(this._compiledEffects[name]._program);
  11664. }
  11665. this._compiledEffects = {};
  11666. };
  11667. // Dispose
  11668. Engine.prototype.dispose = function () {
  11669. this.hideLoadingUI();
  11670. this.stopRenderLoop();
  11671. // Release postProcesses
  11672. while (this.postProcesses.length) {
  11673. this.postProcesses[0].dispose();
  11674. }
  11675. // Empty texture
  11676. if (this._emptyTexture) {
  11677. this._releaseTexture(this._emptyTexture);
  11678. this._emptyTexture = null;
  11679. }
  11680. if (this._emptyCubeTexture) {
  11681. this._releaseTexture(this._emptyCubeTexture);
  11682. this._emptyCubeTexture = null;
  11683. }
  11684. // Rescale PP
  11685. if (this._rescalePostProcess) {
  11686. this._rescalePostProcess.dispose();
  11687. }
  11688. // Release scenes
  11689. while (this.scenes.length) {
  11690. this.scenes[0].dispose();
  11691. }
  11692. // Release audio engine
  11693. if (Engine.audioEngine) {
  11694. Engine.audioEngine.dispose();
  11695. }
  11696. // Release effects
  11697. this.releaseEffects();
  11698. // Unbind
  11699. this.unbindAllAttributes();
  11700. if (this._dummyFramebuffer) {
  11701. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11702. }
  11703. //WebVR
  11704. this.disableVR();
  11705. // Events
  11706. window.removeEventListener("blur", this._onBlur);
  11707. window.removeEventListener("focus", this._onFocus);
  11708. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11709. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11710. if (this._renderingCanvas) {
  11711. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11712. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11713. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11714. if (!this._doNotHandleContextLost) {
  11715. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11716. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11717. }
  11718. }
  11719. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11720. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11721. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11722. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11723. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11724. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11725. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11726. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11727. if (this._onVrDisplayConnect) {
  11728. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11729. if (this._onVrDisplayDisconnect) {
  11730. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11731. }
  11732. if (this._onVrDisplayPresentChange) {
  11733. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11734. }
  11735. this._onVrDisplayConnect = null;
  11736. this._onVrDisplayDisconnect = null;
  11737. }
  11738. // Remove from Instances
  11739. var index = Engine.Instances.indexOf(this);
  11740. if (index >= 0) {
  11741. Engine.Instances.splice(index, 1);
  11742. }
  11743. this._workingCanvas = null;
  11744. this._workingContext = null;
  11745. this._currentBufferPointers = [];
  11746. this._renderingCanvas = null;
  11747. this._currentProgram = null;
  11748. this.onResizeObservable.clear();
  11749. this.onCanvasBlurObservable.clear();
  11750. this.onCanvasFocusObservable.clear();
  11751. this.onCanvasPointerOutObservable.clear();
  11752. this.onBeginFrameObservable.clear();
  11753. this.onEndFrameObservable.clear();
  11754. BABYLON.Effect.ResetCache();
  11755. };
  11756. // Loading screen
  11757. Engine.prototype.displayLoadingUI = function () {
  11758. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11759. return;
  11760. }
  11761. var loadingScreen = this.loadingScreen;
  11762. if (loadingScreen) {
  11763. loadingScreen.displayLoadingUI();
  11764. }
  11765. };
  11766. Engine.prototype.hideLoadingUI = function () {
  11767. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11768. return;
  11769. }
  11770. var loadingScreen = this.loadingScreen;
  11771. if (loadingScreen) {
  11772. loadingScreen.hideLoadingUI();
  11773. }
  11774. };
  11775. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11776. get: function () {
  11777. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11778. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11779. return this._loadingScreen;
  11780. },
  11781. set: function (loadingScreen) {
  11782. this._loadingScreen = loadingScreen;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11788. set: function (text) {
  11789. this.loadingScreen.loadingUIText = text;
  11790. },
  11791. enumerable: true,
  11792. configurable: true
  11793. });
  11794. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11795. set: function (color) {
  11796. this.loadingScreen.loadingUIBackgroundColor = color;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Engine.prototype.attachContextLostEvent = function (callback) {
  11802. if (this._renderingCanvas) {
  11803. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11804. }
  11805. };
  11806. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11807. if (this._renderingCanvas) {
  11808. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11809. }
  11810. };
  11811. Engine.prototype.getVertexShaderSource = function (program) {
  11812. var shaders = this._gl.getAttachedShaders(program);
  11813. if (!shaders) {
  11814. return null;
  11815. }
  11816. return this._gl.getShaderSource(shaders[0]);
  11817. };
  11818. Engine.prototype.getFragmentShaderSource = function (program) {
  11819. var shaders = this._gl.getAttachedShaders(program);
  11820. if (!shaders) {
  11821. return null;
  11822. }
  11823. return this._gl.getShaderSource(shaders[1]);
  11824. };
  11825. Engine.prototype.getError = function () {
  11826. return this._gl.getError();
  11827. };
  11828. // FPS
  11829. Engine.prototype.getFps = function () {
  11830. return this._fps;
  11831. };
  11832. Engine.prototype.getDeltaTime = function () {
  11833. return this._deltaTime;
  11834. };
  11835. Engine.prototype._measureFps = function () {
  11836. this._performanceMonitor.sampleFrame();
  11837. this._fps = this._performanceMonitor.averageFPS;
  11838. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11839. };
  11840. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11841. if (faceIndex === void 0) { faceIndex = -1; }
  11842. var gl = this._gl;
  11843. if (!this._dummyFramebuffer) {
  11844. var dummy = gl.createFramebuffer();
  11845. if (!dummy) {
  11846. throw new Error("Unable to create dummy framebuffer");
  11847. }
  11848. this._dummyFramebuffer = dummy;
  11849. }
  11850. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11851. if (faceIndex > -1) {
  11852. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11853. }
  11854. else {
  11855. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11856. }
  11857. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11858. var buffer;
  11859. switch (readType) {
  11860. case gl.UNSIGNED_BYTE:
  11861. buffer = new Uint8Array(4 * width * height);
  11862. readType = gl.UNSIGNED_BYTE;
  11863. break;
  11864. default:
  11865. buffer = new Float32Array(4 * width * height);
  11866. readType = gl.FLOAT;
  11867. break;
  11868. }
  11869. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11870. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11871. return buffer;
  11872. };
  11873. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11874. if (this._webGLVersion > 1) {
  11875. return this._caps.colorBufferFloat;
  11876. }
  11877. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11878. };
  11879. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11880. if (this._webGLVersion > 1) {
  11881. return this._caps.colorBufferFloat;
  11882. }
  11883. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11884. };
  11885. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11886. Engine.prototype._canRenderToFramebuffer = function (type) {
  11887. var gl = this._gl;
  11888. //clear existing errors
  11889. while (gl.getError() !== gl.NO_ERROR) { }
  11890. var successful = true;
  11891. var texture = gl.createTexture();
  11892. gl.bindTexture(gl.TEXTURE_2D, texture);
  11893. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11896. var fb = gl.createFramebuffer();
  11897. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11898. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11899. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11900. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11901. successful = successful && (gl.getError() === gl.NO_ERROR);
  11902. //try render by clearing frame buffer's color buffer
  11903. if (successful) {
  11904. gl.clear(gl.COLOR_BUFFER_BIT);
  11905. successful = successful && (gl.getError() === gl.NO_ERROR);
  11906. }
  11907. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11908. if (successful) {
  11909. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11910. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11911. var readFormat = gl.RGBA;
  11912. var readType = gl.UNSIGNED_BYTE;
  11913. var buffer = new Uint8Array(4);
  11914. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11915. successful = successful && (gl.getError() === gl.NO_ERROR);
  11916. }
  11917. //clean up
  11918. gl.deleteTexture(texture);
  11919. gl.deleteFramebuffer(fb);
  11920. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11921. //clear accumulated errors
  11922. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11923. return successful;
  11924. };
  11925. Engine.prototype._getWebGLTextureType = function (type) {
  11926. if (type === Engine.TEXTURETYPE_FLOAT) {
  11927. return this._gl.FLOAT;
  11928. }
  11929. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11930. // Add Half Float Constant.
  11931. return this._gl.HALF_FLOAT_OES;
  11932. }
  11933. return this._gl.UNSIGNED_BYTE;
  11934. };
  11935. ;
  11936. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11937. if (this._webGLVersion === 1) {
  11938. return this._gl.RGBA;
  11939. }
  11940. if (type === Engine.TEXTURETYPE_FLOAT) {
  11941. return this._gl.RGBA32F;
  11942. }
  11943. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11944. return this._gl.RGBA16F;
  11945. }
  11946. return this._gl.RGBA;
  11947. };
  11948. ;
  11949. Engine.prototype.createQuery = function () {
  11950. return this._gl.createQuery();
  11951. };
  11952. Engine.prototype.deleteQuery = function (query) {
  11953. this._gl.deleteQuery(query);
  11954. return this;
  11955. };
  11956. Engine.prototype.isQueryResultAvailable = function (query) {
  11957. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11958. };
  11959. Engine.prototype.getQueryResult = function (query) {
  11960. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11961. };
  11962. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  11963. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11964. this._gl.beginQuery(glAlgorithm, query);
  11965. return this;
  11966. };
  11967. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  11968. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11969. this._gl.endQuery(glAlgorithm);
  11970. return this;
  11971. };
  11972. /* Time queries */
  11973. Engine.prototype._createTimeQuery = function () {
  11974. var timerQuery = this._caps.timerQuery;
  11975. if (timerQuery.createQueryEXT) {
  11976. return timerQuery.createQueryEXT();
  11977. }
  11978. return this.createQuery();
  11979. };
  11980. Engine.prototype._deleteTimeQuery = function (query) {
  11981. var timerQuery = this._caps.timerQuery;
  11982. if (timerQuery.deleteQueryEXT) {
  11983. timerQuery.deleteQueryEXT(query);
  11984. return;
  11985. }
  11986. this.deleteQuery(query);
  11987. };
  11988. Engine.prototype._getTimeQueryResult = function (query) {
  11989. var timerQuery = this._caps.timerQuery;
  11990. if (timerQuery.getQueryObjectEXT) {
  11991. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  11992. }
  11993. return this.getQueryResult(query);
  11994. };
  11995. Engine.prototype._getTimeQueryAvailability = function (query) {
  11996. var timerQuery = this._caps.timerQuery;
  11997. if (timerQuery.getQueryObjectEXT) {
  11998. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  11999. }
  12000. return this.isQueryResultAvailable(query);
  12001. };
  12002. Engine.prototype.startTimeQuery = function () {
  12003. var timerQuery = this._caps.timerQuery;
  12004. if (!timerQuery) {
  12005. return null;
  12006. }
  12007. var token = new BABYLON._TimeToken();
  12008. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12009. if (this._caps.canUseTimestampForTimerQuery) {
  12010. token._startTimeQuery = this._createTimeQuery();
  12011. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12012. }
  12013. else {
  12014. if (this._currentNonTimestampToken) {
  12015. return this._currentNonTimestampToken;
  12016. }
  12017. token._timeElapsedQuery = this._createTimeQuery();
  12018. if (timerQuery.beginQueryEXT) {
  12019. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12020. }
  12021. else {
  12022. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12023. }
  12024. this._currentNonTimestampToken = token;
  12025. }
  12026. return token;
  12027. };
  12028. Engine.prototype.endTimeQuery = function (token) {
  12029. var timerQuery = this._caps.timerQuery;
  12030. if (!timerQuery || !token) {
  12031. return -1;
  12032. }
  12033. if (this._caps.canUseTimestampForTimerQuery) {
  12034. if (!token._startTimeQuery) {
  12035. return -1;
  12036. }
  12037. if (!token._endTimeQuery) {
  12038. token._endTimeQuery = this._createTimeQuery();
  12039. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12040. }
  12041. }
  12042. else if (!token._timeElapsedQueryEnded) {
  12043. if (!token._timeElapsedQuery) {
  12044. return -1;
  12045. }
  12046. if (timerQuery.endQueryEXT) {
  12047. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12048. }
  12049. else {
  12050. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12051. }
  12052. token._timeElapsedQueryEnded = true;
  12053. }
  12054. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12055. var available = false;
  12056. if (token._endTimeQuery) {
  12057. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12058. }
  12059. else if (token._timeElapsedQuery) {
  12060. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12061. }
  12062. if (available && !disjoint) {
  12063. var result = 0;
  12064. if (this._caps.canUseTimestampForTimerQuery) {
  12065. if (!token._startTimeQuery || !token._endTimeQuery) {
  12066. return -1;
  12067. }
  12068. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12069. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12070. result = timeEnd - timeStart;
  12071. this._deleteTimeQuery(token._startTimeQuery);
  12072. this._deleteTimeQuery(token._endTimeQuery);
  12073. token._startTimeQuery = null;
  12074. token._endTimeQuery = null;
  12075. }
  12076. else {
  12077. if (!token._timeElapsedQuery) {
  12078. return -1;
  12079. }
  12080. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12081. this._deleteTimeQuery(token._timeElapsedQuery);
  12082. token._timeElapsedQuery = null;
  12083. token._timeElapsedQueryEnded = false;
  12084. this._currentNonTimestampToken = null;
  12085. }
  12086. return result;
  12087. }
  12088. return -1;
  12089. };
  12090. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12091. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12092. };
  12093. // Transform feedback
  12094. Engine.prototype.createTransformFeedback = function () {
  12095. return this._gl.createTransformFeedback();
  12096. };
  12097. Engine.prototype.deleteTransformFeedback = function (value) {
  12098. this._gl.deleteTransformFeedback(value);
  12099. };
  12100. Engine.prototype.bindTransformFeedback = function (value) {
  12101. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12102. };
  12103. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12104. if (usePoints === void 0) { usePoints = true; }
  12105. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12106. };
  12107. Engine.prototype.endTransformFeedback = function () {
  12108. this._gl.endTransformFeedback();
  12109. };
  12110. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12111. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12112. };
  12113. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12114. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12115. };
  12116. // Statics
  12117. Engine.isSupported = function () {
  12118. try {
  12119. var tempcanvas = document.createElement("canvas");
  12120. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12121. return gl != null && !!window.WebGLRenderingContext;
  12122. }
  12123. catch (e) {
  12124. return false;
  12125. }
  12126. };
  12127. Engine.Instances = new Array();
  12128. // Const statics
  12129. Engine._ALPHA_DISABLE = 0;
  12130. Engine._ALPHA_ADD = 1;
  12131. Engine._ALPHA_COMBINE = 2;
  12132. Engine._ALPHA_SUBTRACT = 3;
  12133. Engine._ALPHA_MULTIPLY = 4;
  12134. Engine._ALPHA_MAXIMIZED = 5;
  12135. Engine._ALPHA_ONEONE = 6;
  12136. Engine._ALPHA_PREMULTIPLIED = 7;
  12137. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12138. Engine._ALPHA_INTERPOLATE = 9;
  12139. Engine._ALPHA_SCREENMODE = 10;
  12140. Engine._DELAYLOADSTATE_NONE = 0;
  12141. Engine._DELAYLOADSTATE_LOADED = 1;
  12142. Engine._DELAYLOADSTATE_LOADING = 2;
  12143. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12144. Engine._TEXTUREFORMAT_ALPHA = 0;
  12145. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12146. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12147. Engine._TEXTUREFORMAT_RGB = 4;
  12148. Engine._TEXTUREFORMAT_RGBA = 5;
  12149. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12150. Engine._TEXTURETYPE_FLOAT = 1;
  12151. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12152. // Depht or Stencil test Constants.
  12153. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12154. 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.
  12155. 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.
  12156. 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.
  12157. 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.
  12158. 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.
  12159. 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.
  12160. 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.
  12161. // Stencil Actions Constants.
  12162. Engine._KEEP = 0x1E00;
  12163. Engine._REPLACE = 0x1E01;
  12164. Engine._INCR = 0x1E02;
  12165. Engine._DECR = 0x1E03;
  12166. Engine._INVERT = 0x150A;
  12167. Engine._INCR_WRAP = 0x8507;
  12168. Engine._DECR_WRAP = 0x8508;
  12169. // Texture rescaling mode
  12170. Engine._SCALEMODE_FLOOR = 1;
  12171. Engine._SCALEMODE_NEAREST = 2;
  12172. Engine._SCALEMODE_CEILING = 3;
  12173. // Updatable statics so stick with vars here
  12174. Engine.CollisionsEpsilon = 0.001;
  12175. Engine.CodeRepository = "src/";
  12176. Engine.ShadersRepository = "src/Shaders/";
  12177. return Engine;
  12178. }());
  12179. BABYLON.Engine = Engine;
  12180. })(BABYLON || (BABYLON = {}));
  12181. //# sourceMappingURL=babylon.engine.js.map
  12182. var BABYLON;
  12183. (function (BABYLON) {
  12184. /**
  12185. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12186. */
  12187. var Node = /** @class */ (function () {
  12188. /**
  12189. * @constructor
  12190. * @param {string} name - the name and id to be given to this node
  12191. * @param {BABYLON.Scene} the scene this node will be added to
  12192. */
  12193. function Node(name, scene) {
  12194. if (scene === void 0) { scene = null; }
  12195. this.state = "";
  12196. this.metadata = null;
  12197. this.doNotSerialize = false;
  12198. this.animations = new Array();
  12199. this._ranges = {};
  12200. this._isEnabled = true;
  12201. this._isReady = true;
  12202. this._currentRenderId = -1;
  12203. this._parentRenderId = -1;
  12204. /**
  12205. * An event triggered when the mesh is disposed.
  12206. * @type {BABYLON.Observable}
  12207. */
  12208. this.onDisposeObservable = new BABYLON.Observable();
  12209. // Behaviors
  12210. this._behaviors = new Array();
  12211. this.name = name;
  12212. this.id = name;
  12213. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12214. this.uniqueId = this._scene.getUniqueId();
  12215. this._initCache();
  12216. }
  12217. Object.defineProperty(Node.prototype, "parent", {
  12218. get: function () {
  12219. return this._parentNode;
  12220. },
  12221. set: function (parent) {
  12222. if (this._parentNode === parent) {
  12223. return;
  12224. }
  12225. if (this._parentNode) {
  12226. var index = this._parentNode._children.indexOf(this);
  12227. if (index !== -1) {
  12228. this._parentNode._children.splice(index, 1);
  12229. }
  12230. }
  12231. this._parentNode = parent;
  12232. if (this._parentNode) {
  12233. if (!this._parentNode._children) {
  12234. this._parentNode._children = new Array();
  12235. }
  12236. this._parentNode._children.push(this);
  12237. }
  12238. },
  12239. enumerable: true,
  12240. configurable: true
  12241. });
  12242. Node.prototype.getClassName = function () {
  12243. return "Node";
  12244. };
  12245. Object.defineProperty(Node.prototype, "onDispose", {
  12246. set: function (callback) {
  12247. if (this._onDisposeObserver) {
  12248. this.onDisposeObservable.remove(this._onDisposeObserver);
  12249. }
  12250. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12251. },
  12252. enumerable: true,
  12253. configurable: true
  12254. });
  12255. Node.prototype.getScene = function () {
  12256. return this._scene;
  12257. };
  12258. Node.prototype.getEngine = function () {
  12259. return this._scene.getEngine();
  12260. };
  12261. Node.prototype.addBehavior = function (behavior) {
  12262. var _this = this;
  12263. var index = this._behaviors.indexOf(behavior);
  12264. if (index !== -1) {
  12265. return this;
  12266. }
  12267. behavior.init();
  12268. if (this._scene.isLoading) {
  12269. // We defer the attach when the scene will be loaded
  12270. var observer = this._scene.onDataLoadedObservable.add(function () {
  12271. behavior.attach(_this);
  12272. _this._scene.onDataLoadedObservable.remove(observer);
  12273. });
  12274. }
  12275. else {
  12276. behavior.attach(this);
  12277. }
  12278. this._behaviors.push(behavior);
  12279. return this;
  12280. };
  12281. Node.prototype.removeBehavior = function (behavior) {
  12282. var index = this._behaviors.indexOf(behavior);
  12283. if (index === -1) {
  12284. return this;
  12285. }
  12286. this._behaviors[index].detach();
  12287. this._behaviors.splice(index, 1);
  12288. return this;
  12289. };
  12290. Object.defineProperty(Node.prototype, "behaviors", {
  12291. get: function () {
  12292. return this._behaviors;
  12293. },
  12294. enumerable: true,
  12295. configurable: true
  12296. });
  12297. Node.prototype.getBehaviorByName = function (name) {
  12298. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12299. var behavior = _a[_i];
  12300. if (behavior.name === name) {
  12301. return behavior;
  12302. }
  12303. }
  12304. return null;
  12305. };
  12306. // override it in derived class
  12307. Node.prototype.getWorldMatrix = function () {
  12308. return BABYLON.Matrix.Identity();
  12309. };
  12310. // override it in derived class if you add new variables to the cache
  12311. // and call the parent class method
  12312. Node.prototype._initCache = function () {
  12313. this._cache = {};
  12314. this._cache.parent = undefined;
  12315. };
  12316. Node.prototype.updateCache = function (force) {
  12317. if (!force && this.isSynchronized())
  12318. return;
  12319. this._cache.parent = this.parent;
  12320. this._updateCache();
  12321. };
  12322. // override it in derived class if you add new variables to the cache
  12323. // and call the parent class method if !ignoreParentClass
  12324. Node.prototype._updateCache = function (ignoreParentClass) {
  12325. };
  12326. // override it in derived class if you add new variables to the cache
  12327. Node.prototype._isSynchronized = function () {
  12328. return true;
  12329. };
  12330. Node.prototype._markSyncedWithParent = function () {
  12331. if (this.parent) {
  12332. this._parentRenderId = this.parent._currentRenderId;
  12333. }
  12334. };
  12335. Node.prototype.isSynchronizedWithParent = function () {
  12336. if (!this.parent) {
  12337. return true;
  12338. }
  12339. if (this._parentRenderId !== this.parent._currentRenderId) {
  12340. return false;
  12341. }
  12342. return this.parent.isSynchronized();
  12343. };
  12344. Node.prototype.isSynchronized = function (updateCache) {
  12345. var check = this.hasNewParent();
  12346. check = check || !this.isSynchronizedWithParent();
  12347. check = check || !this._isSynchronized();
  12348. if (updateCache)
  12349. this.updateCache(true);
  12350. return !check;
  12351. };
  12352. Node.prototype.hasNewParent = function (update) {
  12353. if (this._cache.parent === this.parent)
  12354. return false;
  12355. if (update)
  12356. this._cache.parent = this.parent;
  12357. return true;
  12358. };
  12359. /**
  12360. * Is this node ready to be used/rendered
  12361. * @return {boolean} is it ready
  12362. */
  12363. Node.prototype.isReady = function () {
  12364. return this._isReady;
  12365. };
  12366. /**
  12367. * Is this node enabled.
  12368. * If the node has a parent and is enabled, the parent will be inspected as well.
  12369. * @return {boolean} whether this node (and its parent) is enabled.
  12370. * @see setEnabled
  12371. */
  12372. Node.prototype.isEnabled = function () {
  12373. if (!this._isEnabled) {
  12374. return false;
  12375. }
  12376. if (this.parent) {
  12377. return this.parent.isEnabled();
  12378. }
  12379. return true;
  12380. };
  12381. /**
  12382. * Set the enabled state of this node.
  12383. * @param {boolean} value - the new enabled state
  12384. * @see isEnabled
  12385. */
  12386. Node.prototype.setEnabled = function (value) {
  12387. this._isEnabled = value;
  12388. };
  12389. /**
  12390. * Is this node a descendant of the given node.
  12391. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12392. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12393. * @see parent
  12394. */
  12395. Node.prototype.isDescendantOf = function (ancestor) {
  12396. if (this.parent) {
  12397. if (this.parent === ancestor) {
  12398. return true;
  12399. }
  12400. return this.parent.isDescendantOf(ancestor);
  12401. }
  12402. return false;
  12403. };
  12404. /**
  12405. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12406. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12407. * @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.
  12408. * @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.
  12409. */
  12410. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12411. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12412. if (!this._children) {
  12413. return;
  12414. }
  12415. for (var index = 0; index < this._children.length; index++) {
  12416. var item = this._children[index];
  12417. if (!predicate || predicate(item)) {
  12418. results.push(item);
  12419. }
  12420. if (!directDescendantsOnly) {
  12421. item._getDescendants(results, false, predicate);
  12422. }
  12423. }
  12424. };
  12425. /**
  12426. * Will return all nodes that have this node as ascendant.
  12427. * @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.
  12428. * @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.
  12429. * @return {BABYLON.Node[]} all children nodes of all types.
  12430. */
  12431. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12432. var results = new Array();
  12433. this._getDescendants(results, directDescendantsOnly, predicate);
  12434. return results;
  12435. };
  12436. /**
  12437. * Get all child-meshes of this node.
  12438. */
  12439. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12440. var results = [];
  12441. this._getDescendants(results, directDecendantsOnly, function (node) {
  12442. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12443. });
  12444. return results;
  12445. };
  12446. /**
  12447. * Get all direct children of this node.
  12448. */
  12449. Node.prototype.getChildren = function (predicate) {
  12450. return this.getDescendants(true, predicate);
  12451. };
  12452. Node.prototype._setReady = function (state) {
  12453. if (state === this._isReady) {
  12454. return;
  12455. }
  12456. if (!state) {
  12457. this._isReady = false;
  12458. return;
  12459. }
  12460. this._isReady = true;
  12461. if (this.onReady) {
  12462. this.onReady(this);
  12463. }
  12464. };
  12465. Node.prototype.getAnimationByName = function (name) {
  12466. for (var i = 0; i < this.animations.length; i++) {
  12467. var animation = this.animations[i];
  12468. if (animation.name === name) {
  12469. return animation;
  12470. }
  12471. }
  12472. return null;
  12473. };
  12474. Node.prototype.createAnimationRange = function (name, from, to) {
  12475. // check name not already in use
  12476. if (!this._ranges[name]) {
  12477. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12478. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12479. if (this.animations[i]) {
  12480. this.animations[i].createRange(name, from, to);
  12481. }
  12482. }
  12483. }
  12484. };
  12485. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12486. if (deleteFrames === void 0) { deleteFrames = true; }
  12487. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12488. if (this.animations[i]) {
  12489. this.animations[i].deleteRange(name, deleteFrames);
  12490. }
  12491. }
  12492. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12493. };
  12494. Node.prototype.getAnimationRange = function (name) {
  12495. return this._ranges[name];
  12496. };
  12497. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12498. var range = this.getAnimationRange(name);
  12499. if (!range) {
  12500. return;
  12501. }
  12502. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12503. };
  12504. Node.prototype.serializeAnimationRanges = function () {
  12505. var serializationRanges = [];
  12506. for (var name in this._ranges) {
  12507. var localRange = this._ranges[name];
  12508. if (!localRange) {
  12509. continue;
  12510. }
  12511. var range = {};
  12512. range.name = name;
  12513. range.from = localRange.from;
  12514. range.to = localRange.to;
  12515. serializationRanges.push(range);
  12516. }
  12517. return serializationRanges;
  12518. };
  12519. Node.prototype.dispose = function () {
  12520. this.parent = null;
  12521. // Callback
  12522. this.onDisposeObservable.notifyObservers(this);
  12523. this.onDisposeObservable.clear();
  12524. // Behaviors
  12525. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12526. var behavior = _a[_i];
  12527. behavior.detach();
  12528. }
  12529. this._behaviors = [];
  12530. };
  12531. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12532. if (parsedNode.ranges) {
  12533. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12534. var data = parsedNode.ranges[index];
  12535. node.createAnimationRange(data.name, data.from, data.to);
  12536. }
  12537. }
  12538. };
  12539. __decorate([
  12540. BABYLON.serialize()
  12541. ], Node.prototype, "name", void 0);
  12542. __decorate([
  12543. BABYLON.serialize()
  12544. ], Node.prototype, "id", void 0);
  12545. __decorate([
  12546. BABYLON.serialize()
  12547. ], Node.prototype, "uniqueId", void 0);
  12548. __decorate([
  12549. BABYLON.serialize()
  12550. ], Node.prototype, "state", void 0);
  12551. __decorate([
  12552. BABYLON.serialize()
  12553. ], Node.prototype, "metadata", void 0);
  12554. return Node;
  12555. }());
  12556. BABYLON.Node = Node;
  12557. })(BABYLON || (BABYLON = {}));
  12558. //# sourceMappingURL=babylon.node.js.map
  12559. var BABYLON;
  12560. (function (BABYLON) {
  12561. var BoundingSphere = /** @class */ (function () {
  12562. function BoundingSphere(minimum, maximum) {
  12563. this.minimum = minimum;
  12564. this.maximum = maximum;
  12565. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12566. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12567. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12568. this.radius = distance * 0.5;
  12569. this.centerWorld = BABYLON.Vector3.Zero();
  12570. this._update(BABYLON.Matrix.Identity());
  12571. }
  12572. // Methods
  12573. BoundingSphere.prototype._update = function (world) {
  12574. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12575. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12576. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12577. };
  12578. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12579. for (var i = 0; i < 6; i++) {
  12580. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12581. return false;
  12582. }
  12583. return true;
  12584. };
  12585. BoundingSphere.prototype.intersectsPoint = function (point) {
  12586. var x = this.centerWorld.x - point.x;
  12587. var y = this.centerWorld.y - point.y;
  12588. var z = this.centerWorld.z - point.z;
  12589. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12590. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12591. return false;
  12592. return true;
  12593. };
  12594. // Statics
  12595. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12596. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12597. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12598. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12599. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12600. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12601. return false;
  12602. return true;
  12603. };
  12604. return BoundingSphere;
  12605. }());
  12606. BABYLON.BoundingSphere = BoundingSphere;
  12607. })(BABYLON || (BABYLON = {}));
  12608. //# sourceMappingURL=babylon.boundingSphere.js.map
  12609. var BABYLON;
  12610. (function (BABYLON) {
  12611. var BoundingBox = /** @class */ (function () {
  12612. function BoundingBox(minimum, maximum) {
  12613. this.minimum = minimum;
  12614. this.maximum = maximum;
  12615. this.vectors = new Array();
  12616. this.vectorsWorld = new Array();
  12617. // Bounding vectors
  12618. this.vectors.push(this.minimum.clone());
  12619. this.vectors.push(this.maximum.clone());
  12620. this.vectors.push(this.minimum.clone());
  12621. this.vectors[2].x = this.maximum.x;
  12622. this.vectors.push(this.minimum.clone());
  12623. this.vectors[3].y = this.maximum.y;
  12624. this.vectors.push(this.minimum.clone());
  12625. this.vectors[4].z = this.maximum.z;
  12626. this.vectors.push(this.maximum.clone());
  12627. this.vectors[5].z = this.minimum.z;
  12628. this.vectors.push(this.maximum.clone());
  12629. this.vectors[6].x = this.minimum.x;
  12630. this.vectors.push(this.maximum.clone());
  12631. this.vectors[7].y = this.minimum.y;
  12632. // OBB
  12633. this.center = this.maximum.add(this.minimum).scale(0.5);
  12634. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12635. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12636. // World
  12637. for (var index = 0; index < this.vectors.length; index++) {
  12638. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12639. }
  12640. this.minimumWorld = BABYLON.Vector3.Zero();
  12641. this.maximumWorld = BABYLON.Vector3.Zero();
  12642. this.centerWorld = BABYLON.Vector3.Zero();
  12643. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12644. this._update(BABYLON.Matrix.Identity());
  12645. }
  12646. // Methods
  12647. BoundingBox.prototype.getWorldMatrix = function () {
  12648. return this._worldMatrix;
  12649. };
  12650. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12651. this._worldMatrix.copyFrom(matrix);
  12652. return this;
  12653. };
  12654. BoundingBox.prototype._update = function (world) {
  12655. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12656. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12657. for (var index = 0; index < this.vectors.length; index++) {
  12658. var v = this.vectorsWorld[index];
  12659. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12660. if (v.x < this.minimumWorld.x)
  12661. this.minimumWorld.x = v.x;
  12662. if (v.y < this.minimumWorld.y)
  12663. this.minimumWorld.y = v.y;
  12664. if (v.z < this.minimumWorld.z)
  12665. this.minimumWorld.z = v.z;
  12666. if (v.x > this.maximumWorld.x)
  12667. this.maximumWorld.x = v.x;
  12668. if (v.y > this.maximumWorld.y)
  12669. this.maximumWorld.y = v.y;
  12670. if (v.z > this.maximumWorld.z)
  12671. this.maximumWorld.z = v.z;
  12672. }
  12673. // Extend
  12674. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12675. this.extendSizeWorld.scaleInPlace(0.5);
  12676. // OBB
  12677. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12678. this.centerWorld.scaleInPlace(0.5);
  12679. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12680. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12681. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12682. this._worldMatrix = world;
  12683. };
  12684. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12685. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12686. };
  12687. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12688. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12689. };
  12690. BoundingBox.prototype.intersectsPoint = function (point) {
  12691. var delta = -BABYLON.Epsilon;
  12692. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12693. return false;
  12694. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12695. return false;
  12696. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12697. return false;
  12698. return true;
  12699. };
  12700. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12701. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12702. };
  12703. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12704. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12705. return false;
  12706. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12707. return false;
  12708. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12709. return false;
  12710. return true;
  12711. };
  12712. // Statics
  12713. BoundingBox.Intersects = function (box0, box1) {
  12714. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12715. return false;
  12716. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12717. return false;
  12718. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12719. return false;
  12720. return true;
  12721. };
  12722. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12723. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12724. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12725. return (num <= (sphereRadius * sphereRadius));
  12726. };
  12727. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12728. for (var p = 0; p < 6; p++) {
  12729. for (var i = 0; i < 8; i++) {
  12730. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12731. return false;
  12732. }
  12733. }
  12734. }
  12735. return true;
  12736. };
  12737. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12738. for (var p = 0; p < 6; p++) {
  12739. var inCount = 8;
  12740. for (var i = 0; i < 8; i++) {
  12741. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12742. --inCount;
  12743. }
  12744. else {
  12745. break;
  12746. }
  12747. }
  12748. if (inCount === 0)
  12749. return false;
  12750. }
  12751. return true;
  12752. };
  12753. return BoundingBox;
  12754. }());
  12755. BABYLON.BoundingBox = BoundingBox;
  12756. })(BABYLON || (BABYLON = {}));
  12757. //# sourceMappingURL=babylon.boundingBox.js.map
  12758. var BABYLON;
  12759. (function (BABYLON) {
  12760. var computeBoxExtents = function (axis, box) {
  12761. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12762. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12763. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12764. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12765. var r = r0 + r1 + r2;
  12766. return {
  12767. min: p - r,
  12768. max: p + r
  12769. };
  12770. };
  12771. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12772. var axisOverlap = function (axis, box0, box1) {
  12773. var result0 = computeBoxExtents(axis, box0);
  12774. var result1 = computeBoxExtents(axis, box1);
  12775. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12776. };
  12777. var BoundingInfo = /** @class */ (function () {
  12778. function BoundingInfo(minimum, maximum) {
  12779. this.minimum = minimum;
  12780. this.maximum = maximum;
  12781. this._isLocked = false;
  12782. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12783. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12784. }
  12785. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12786. get: function () {
  12787. return this._isLocked;
  12788. },
  12789. set: function (value) {
  12790. this._isLocked = value;
  12791. },
  12792. enumerable: true,
  12793. configurable: true
  12794. });
  12795. // Methods
  12796. BoundingInfo.prototype.update = function (world) {
  12797. if (this._isLocked) {
  12798. return;
  12799. }
  12800. this.boundingBox._update(world);
  12801. this.boundingSphere._update(world);
  12802. };
  12803. /**
  12804. * Recreate the bounding info to be centered around a specific point given a specific extend.
  12805. * @param center New center of the bounding info
  12806. * @param extend New extend of the bounding info
  12807. */
  12808. BoundingInfo.prototype.centerOn = function (center, extend) {
  12809. this.minimum = center.subtract(extend);
  12810. this.maximum = center.add(extend);
  12811. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  12812. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  12813. return this;
  12814. };
  12815. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12816. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12817. return false;
  12818. return this.boundingBox.isInFrustum(frustumPlanes);
  12819. };
  12820. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12821. /**
  12822. * Gets the world distance between the min and max points of the bounding box
  12823. */
  12824. get: function () {
  12825. var boundingBox = this.boundingBox;
  12826. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12827. return size.length();
  12828. },
  12829. enumerable: true,
  12830. configurable: true
  12831. });
  12832. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12833. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12834. };
  12835. BoundingInfo.prototype._checkCollision = function (collider) {
  12836. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12837. };
  12838. BoundingInfo.prototype.intersectsPoint = function (point) {
  12839. if (!this.boundingSphere.centerWorld) {
  12840. return false;
  12841. }
  12842. if (!this.boundingSphere.intersectsPoint(point)) {
  12843. return false;
  12844. }
  12845. if (!this.boundingBox.intersectsPoint(point)) {
  12846. return false;
  12847. }
  12848. return true;
  12849. };
  12850. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12851. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12852. return false;
  12853. }
  12854. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12855. return false;
  12856. }
  12857. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12858. return false;
  12859. }
  12860. if (!precise) {
  12861. return true;
  12862. }
  12863. var box0 = this.boundingBox;
  12864. var box1 = boundingInfo.boundingBox;
  12865. if (!axisOverlap(box0.directions[0], box0, box1))
  12866. return false;
  12867. if (!axisOverlap(box0.directions[1], box0, box1))
  12868. return false;
  12869. if (!axisOverlap(box0.directions[2], box0, box1))
  12870. return false;
  12871. if (!axisOverlap(box1.directions[0], box0, box1))
  12872. return false;
  12873. if (!axisOverlap(box1.directions[1], box0, box1))
  12874. return false;
  12875. if (!axisOverlap(box1.directions[2], box0, box1))
  12876. return false;
  12877. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12878. return false;
  12879. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12880. return false;
  12881. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12882. return false;
  12883. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12884. return false;
  12885. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12886. return false;
  12887. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12888. return false;
  12889. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12890. return false;
  12891. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12892. return false;
  12893. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12894. return false;
  12895. return true;
  12896. };
  12897. return BoundingInfo;
  12898. }());
  12899. BABYLON.BoundingInfo = BoundingInfo;
  12900. })(BABYLON || (BABYLON = {}));
  12901. //# sourceMappingURL=babylon.boundingInfo.js.map
  12902. var BABYLON;
  12903. (function (BABYLON) {
  12904. var AbstractMesh = /** @class */ (function (_super) {
  12905. __extends(AbstractMesh, _super);
  12906. // Constructor
  12907. function AbstractMesh(name, scene) {
  12908. if (scene === void 0) { scene = null; }
  12909. var _this = _super.call(this, name, scene) || this;
  12910. _this._facetNb = 0; // facet number
  12911. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12912. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12913. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12914. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12915. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12916. _this._subDiv = {
  12917. max: 1,
  12918. X: 1,
  12919. Y: 1,
  12920. Z: 1
  12921. };
  12922. // Normal matrix
  12923. _this._nonUniformScaling = false;
  12924. // Events
  12925. /**
  12926. * An event triggered when this mesh collides with another one
  12927. * @type {BABYLON.Observable}
  12928. */
  12929. _this.onCollideObservable = new BABYLON.Observable();
  12930. /**
  12931. * An event triggered when the collision's position changes
  12932. * @type {BABYLON.Observable}
  12933. */
  12934. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12935. /**
  12936. * An event triggered after the world matrix is updated
  12937. * @type {BABYLON.Observable}
  12938. */
  12939. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12940. /**
  12941. * An event triggered when material is changed
  12942. * @type {BABYLON.Observable}
  12943. */
  12944. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12945. // Properties
  12946. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12947. _this.position = BABYLON.Vector3.Zero();
  12948. /**
  12949. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12950. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12951. * or
  12952. * 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.
  12953. * for more info check WebGl documentations
  12954. */
  12955. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12956. /**
  12957. * 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:
  12958. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12959. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12960. * 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.
  12961. */
  12962. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12963. /**
  12964. * 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.
  12965. * The default value is -1 which means don't break the query and wait till the result.
  12966. */
  12967. _this.occlusionRetryCount = -1;
  12968. _this._occlusionInternalRetryCounter = 0;
  12969. _this._isOccluded = false;
  12970. _this._isOcclusionQueryInProgress = false;
  12971. _this._rotation = BABYLON.Vector3.Zero();
  12972. _this._scaling = BABYLON.Vector3.One();
  12973. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12974. _this.visibility = 1.0;
  12975. _this.alphaIndex = Number.MAX_VALUE;
  12976. _this.infiniteDistance = false;
  12977. _this.isVisible = true;
  12978. _this.isPickable = true;
  12979. _this.showBoundingBox = false;
  12980. _this.showSubMeshesBoundingBox = false;
  12981. _this.isBlocker = false;
  12982. _this.enablePointerMoveEvents = false;
  12983. _this.renderingGroupId = 0;
  12984. _this._receiveShadows = false;
  12985. _this.renderOutline = false;
  12986. _this.outlineColor = BABYLON.Color3.Red();
  12987. _this.outlineWidth = 0.02;
  12988. _this.renderOverlay = false;
  12989. _this.overlayColor = BABYLON.Color3.Red();
  12990. _this.overlayAlpha = 0.5;
  12991. _this._hasVertexAlpha = false;
  12992. _this._useVertexColors = true;
  12993. _this._computeBonesUsingShaders = true;
  12994. _this._numBoneInfluencers = 4;
  12995. _this._applyFog = true;
  12996. _this.scalingDeterminant = 1;
  12997. _this.useOctreeForRenderingSelection = true;
  12998. _this.useOctreeForPicking = true;
  12999. _this.useOctreeForCollisions = true;
  13000. _this._layerMask = 0x0FFFFFFF;
  13001. /**
  13002. * True if the mesh must be rendered in any case.
  13003. */
  13004. _this.alwaysSelectAsActiveMesh = false;
  13005. // Collisions
  13006. _this._checkCollisions = false;
  13007. _this._collisionMask = -1;
  13008. _this._collisionGroup = -1;
  13009. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13010. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  13011. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  13012. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  13013. // Edges
  13014. _this.edgesWidth = 1;
  13015. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  13016. // Cache
  13017. _this._localWorld = BABYLON.Matrix.Zero();
  13018. _this._worldMatrix = BABYLON.Matrix.Zero();
  13019. _this._absolutePosition = BABYLON.Vector3.Zero();
  13020. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  13021. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  13022. _this._isDirty = false;
  13023. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13024. _this._postMultiplyPivotMatrix = false;
  13025. _this._isDisposed = false;
  13026. _this._renderId = 0;
  13027. _this._intersectionsInProgress = new Array();
  13028. _this._isWorldMatrixFrozen = false;
  13029. _this._unIndexed = false;
  13030. _this._lightSources = new Array();
  13031. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13032. if (collidedMesh === void 0) { collidedMesh = null; }
  13033. //TODO move this to the collision coordinator!
  13034. if (_this.getScene().workerCollisions)
  13035. newPosition.multiplyInPlace(_this._collider.radius);
  13036. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  13037. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  13038. _this.position.addInPlace(_this._diffPositionForCollisions);
  13039. }
  13040. if (collidedMesh) {
  13041. _this.onCollideObservable.notifyObservers(collidedMesh);
  13042. }
  13043. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  13044. };
  13045. _this.getScene().addMesh(_this);
  13046. _this._resyncLightSources();
  13047. return _this;
  13048. }
  13049. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  13050. get: function () {
  13051. return AbstractMesh._BILLBOARDMODE_NONE;
  13052. },
  13053. enumerable: true,
  13054. configurable: true
  13055. });
  13056. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  13057. get: function () {
  13058. return AbstractMesh._BILLBOARDMODE_X;
  13059. },
  13060. enumerable: true,
  13061. configurable: true
  13062. });
  13063. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  13064. get: function () {
  13065. return AbstractMesh._BILLBOARDMODE_Y;
  13066. },
  13067. enumerable: true,
  13068. configurable: true
  13069. });
  13070. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  13071. get: function () {
  13072. return AbstractMesh._BILLBOARDMODE_Z;
  13073. },
  13074. enumerable: true,
  13075. configurable: true
  13076. });
  13077. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  13078. get: function () {
  13079. return AbstractMesh._BILLBOARDMODE_ALL;
  13080. },
  13081. enumerable: true,
  13082. configurable: true
  13083. });
  13084. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  13085. /**
  13086. * Read-only : the number of facets in the mesh
  13087. */
  13088. get: function () {
  13089. return this._facetNb;
  13090. },
  13091. enumerable: true,
  13092. configurable: true
  13093. });
  13094. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  13095. /**
  13096. * The number (integer) of subdivisions per axis in the partioning space
  13097. */
  13098. get: function () {
  13099. return this._partitioningSubdivisions;
  13100. },
  13101. set: function (nb) {
  13102. this._partitioningSubdivisions = nb;
  13103. },
  13104. enumerable: true,
  13105. configurable: true
  13106. });
  13107. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  13108. /**
  13109. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  13110. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  13111. */
  13112. get: function () {
  13113. return this._partitioningBBoxRatio;
  13114. },
  13115. set: function (ratio) {
  13116. this._partitioningBBoxRatio = ratio;
  13117. },
  13118. enumerable: true,
  13119. configurable: true
  13120. });
  13121. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  13122. /**
  13123. * Read-only boolean : is the feature facetData enabled ?
  13124. */
  13125. get: function () {
  13126. return this._facetDataEnabled;
  13127. },
  13128. enumerable: true,
  13129. configurable: true
  13130. });
  13131. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  13132. get: function () {
  13133. return this._nonUniformScaling;
  13134. },
  13135. set: function (value) {
  13136. if (this._nonUniformScaling === value) {
  13137. return;
  13138. }
  13139. this._nonUniformScaling = true;
  13140. this._markSubMeshesAsMiscDirty();
  13141. },
  13142. enumerable: true,
  13143. configurable: true
  13144. });
  13145. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  13146. set: function (callback) {
  13147. if (this._onCollideObserver) {
  13148. this.onCollideObservable.remove(this._onCollideObserver);
  13149. }
  13150. this._onCollideObserver = this.onCollideObservable.add(callback);
  13151. },
  13152. enumerable: true,
  13153. configurable: true
  13154. });
  13155. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  13156. set: function (callback) {
  13157. if (this._onCollisionPositionChangeObserver) {
  13158. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  13159. }
  13160. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  13161. },
  13162. enumerable: true,
  13163. configurable: true
  13164. });
  13165. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  13166. /**
  13167. * 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.
  13168. */
  13169. get: function () {
  13170. return this._isOccluded;
  13171. },
  13172. set: function (value) {
  13173. this._isOccluded = value;
  13174. },
  13175. enumerable: true,
  13176. configurable: true
  13177. });
  13178. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  13179. /**
  13180. * Flag to check the progress status of the query
  13181. */
  13182. get: function () {
  13183. return this._isOcclusionQueryInProgress;
  13184. },
  13185. enumerable: true,
  13186. configurable: true
  13187. });
  13188. Object.defineProperty(AbstractMesh.prototype, "material", {
  13189. get: function () {
  13190. return this._material;
  13191. },
  13192. set: function (value) {
  13193. if (this._material === value) {
  13194. return;
  13195. }
  13196. this._material = value;
  13197. if (this.onMaterialChangedObservable.hasObservers) {
  13198. this.onMaterialChangedObservable.notifyObservers(this);
  13199. }
  13200. if (!this.subMeshes) {
  13201. return;
  13202. }
  13203. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13204. var subMesh = _a[_i];
  13205. subMesh.setEffect(null);
  13206. }
  13207. },
  13208. enumerable: true,
  13209. configurable: true
  13210. });
  13211. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  13212. get: function () {
  13213. return this._receiveShadows;
  13214. },
  13215. set: function (value) {
  13216. if (this._receiveShadows === value) {
  13217. return;
  13218. }
  13219. this._receiveShadows = value;
  13220. this._markSubMeshesAsLightDirty();
  13221. },
  13222. enumerable: true,
  13223. configurable: true
  13224. });
  13225. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  13226. get: function () {
  13227. return this._hasVertexAlpha;
  13228. },
  13229. set: function (value) {
  13230. if (this._hasVertexAlpha === value) {
  13231. return;
  13232. }
  13233. this._hasVertexAlpha = value;
  13234. this._markSubMeshesAsAttributesDirty();
  13235. },
  13236. enumerable: true,
  13237. configurable: true
  13238. });
  13239. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  13240. get: function () {
  13241. return this._useVertexColors;
  13242. },
  13243. set: function (value) {
  13244. if (this._useVertexColors === value) {
  13245. return;
  13246. }
  13247. this._useVertexColors = value;
  13248. this._markSubMeshesAsAttributesDirty();
  13249. },
  13250. enumerable: true,
  13251. configurable: true
  13252. });
  13253. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  13254. get: function () {
  13255. return this._computeBonesUsingShaders;
  13256. },
  13257. set: function (value) {
  13258. if (this._computeBonesUsingShaders === value) {
  13259. return;
  13260. }
  13261. this._computeBonesUsingShaders = value;
  13262. this._markSubMeshesAsAttributesDirty();
  13263. },
  13264. enumerable: true,
  13265. configurable: true
  13266. });
  13267. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  13268. get: function () {
  13269. return this._numBoneInfluencers;
  13270. },
  13271. set: function (value) {
  13272. if (this._numBoneInfluencers === value) {
  13273. return;
  13274. }
  13275. this._numBoneInfluencers = value;
  13276. this._markSubMeshesAsAttributesDirty();
  13277. },
  13278. enumerable: true,
  13279. configurable: true
  13280. });
  13281. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  13282. get: function () {
  13283. return this._applyFog;
  13284. },
  13285. set: function (value) {
  13286. if (this._applyFog === value) {
  13287. return;
  13288. }
  13289. this._applyFog = value;
  13290. this._markSubMeshesAsMiscDirty();
  13291. },
  13292. enumerable: true,
  13293. configurable: true
  13294. });
  13295. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  13296. get: function () {
  13297. return this._layerMask;
  13298. },
  13299. set: function (value) {
  13300. if (value === this._layerMask) {
  13301. return;
  13302. }
  13303. this._layerMask = value;
  13304. this._resyncLightSources();
  13305. },
  13306. enumerable: true,
  13307. configurable: true
  13308. });
  13309. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  13310. get: function () {
  13311. return this._collisionMask;
  13312. },
  13313. set: function (mask) {
  13314. this._collisionMask = !isNaN(mask) ? mask : -1;
  13315. },
  13316. enumerable: true,
  13317. configurable: true
  13318. });
  13319. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  13320. get: function () {
  13321. return this._collisionGroup;
  13322. },
  13323. set: function (mask) {
  13324. this._collisionGroup = !isNaN(mask) ? mask : -1;
  13325. },
  13326. enumerable: true,
  13327. configurable: true
  13328. });
  13329. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  13330. get: function () {
  13331. return null;
  13332. },
  13333. enumerable: true,
  13334. configurable: true
  13335. });
  13336. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  13337. get: function () {
  13338. return this._skeleton;
  13339. },
  13340. set: function (value) {
  13341. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  13342. this._skeleton._unregisterMeshWithPoseMatrix(this);
  13343. }
  13344. if (value && value.needInitialSkinMatrix) {
  13345. value._registerMeshWithPoseMatrix(this);
  13346. }
  13347. this._skeleton = value;
  13348. if (!this._skeleton) {
  13349. this._bonesTransformMatrices = null;
  13350. }
  13351. this._markSubMeshesAsAttributesDirty();
  13352. },
  13353. enumerable: true,
  13354. configurable: true
  13355. });
  13356. /**
  13357. * Boolean : true if the mesh has been disposed.
  13358. */
  13359. AbstractMesh.prototype.isDisposed = function () {
  13360. return this._isDisposed;
  13361. };
  13362. /**
  13363. * Returns the string "AbstractMesh"
  13364. */
  13365. AbstractMesh.prototype.getClassName = function () {
  13366. return "AbstractMesh";
  13367. };
  13368. /**
  13369. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13370. */
  13371. AbstractMesh.prototype.toString = function (fullDetails) {
  13372. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  13373. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  13374. if (this._skeleton) {
  13375. ret += ", skeleton: " + this._skeleton.name;
  13376. }
  13377. if (fullDetails) {
  13378. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  13379. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  13380. }
  13381. return ret;
  13382. };
  13383. AbstractMesh.prototype._rebuild = function () {
  13384. if (this._occlusionQuery) {
  13385. this._occlusionQuery = null;
  13386. }
  13387. if (this._edgesRenderer) {
  13388. this._edgesRenderer._rebuild();
  13389. }
  13390. if (!this.subMeshes) {
  13391. return;
  13392. }
  13393. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13394. var subMesh = _a[_i];
  13395. subMesh._rebuild();
  13396. }
  13397. };
  13398. AbstractMesh.prototype._resyncLightSources = function () {
  13399. this._lightSources.length = 0;
  13400. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  13401. var light = _a[_i];
  13402. if (!light.isEnabled()) {
  13403. continue;
  13404. }
  13405. if (light.canAffectMesh(this)) {
  13406. this._lightSources.push(light);
  13407. }
  13408. }
  13409. this._markSubMeshesAsLightDirty();
  13410. };
  13411. AbstractMesh.prototype._resyncLighSource = function (light) {
  13412. var isIn = light.isEnabled() && light.canAffectMesh(this);
  13413. var index = this._lightSources.indexOf(light);
  13414. if (index === -1) {
  13415. if (!isIn) {
  13416. return;
  13417. }
  13418. this._lightSources.push(light);
  13419. }
  13420. else {
  13421. if (isIn) {
  13422. return;
  13423. }
  13424. this._lightSources.splice(index, 1);
  13425. }
  13426. this._markSubMeshesAsLightDirty();
  13427. };
  13428. AbstractMesh.prototype._removeLightSource = function (light) {
  13429. var index = this._lightSources.indexOf(light);
  13430. if (index === -1) {
  13431. return;
  13432. }
  13433. this._lightSources.splice(index, 1);
  13434. };
  13435. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  13436. if (!this.subMeshes) {
  13437. return;
  13438. }
  13439. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13440. var subMesh = _a[_i];
  13441. if (subMesh._materialDefines) {
  13442. func(subMesh._materialDefines);
  13443. }
  13444. }
  13445. };
  13446. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13447. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13448. };
  13449. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13450. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13451. };
  13452. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13453. if (!this.subMeshes) {
  13454. return;
  13455. }
  13456. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13457. var subMesh = _a[_i];
  13458. var material = subMesh.getMaterial();
  13459. if (material) {
  13460. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13461. }
  13462. }
  13463. };
  13464. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13465. /**
  13466. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13467. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13468. * Default : (0.0, 0.0, 0.0)
  13469. */
  13470. get: function () {
  13471. return this._rotation;
  13472. },
  13473. set: function (newRotation) {
  13474. this._rotation = newRotation;
  13475. },
  13476. enumerable: true,
  13477. configurable: true
  13478. });
  13479. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13480. /**
  13481. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13482. * Default : (1.0, 1.0, 1.0)
  13483. */
  13484. get: function () {
  13485. return this._scaling;
  13486. },
  13487. set: function (newScaling) {
  13488. this._scaling = newScaling;
  13489. if (this.physicsImpostor) {
  13490. this.physicsImpostor.forceUpdate();
  13491. }
  13492. },
  13493. enumerable: true,
  13494. configurable: true
  13495. });
  13496. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13497. /**
  13498. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13499. * It's null by default.
  13500. * 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)
  13501. */
  13502. get: function () {
  13503. return this._rotationQuaternion;
  13504. },
  13505. set: function (quaternion) {
  13506. this._rotationQuaternion = quaternion;
  13507. //reset the rotation vector.
  13508. if (quaternion && this.rotation.length()) {
  13509. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13510. }
  13511. },
  13512. enumerable: true,
  13513. configurable: true
  13514. });
  13515. // Methods
  13516. /**
  13517. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13518. * Returns the AbstractMesh.
  13519. */
  13520. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13521. this._poseMatrix.copyFrom(matrix);
  13522. return this;
  13523. };
  13524. /**
  13525. * Returns the mesh Pose matrix.
  13526. * Returned object : Matrix
  13527. */
  13528. AbstractMesh.prototype.getPoseMatrix = function () {
  13529. return this._poseMatrix;
  13530. };
  13531. /**
  13532. * Disables the mesh edger rendering mode.
  13533. * Returns the AbstractMesh.
  13534. */
  13535. AbstractMesh.prototype.disableEdgesRendering = function () {
  13536. if (this._edgesRenderer) {
  13537. this._edgesRenderer.dispose();
  13538. this._edgesRenderer = null;
  13539. }
  13540. return this;
  13541. };
  13542. /**
  13543. * Enables the edge rendering mode on the mesh.
  13544. * This mode makes the mesh edges visible.
  13545. * Returns the AbstractMesh.
  13546. */
  13547. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13548. if (epsilon === void 0) { epsilon = 0.95; }
  13549. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13550. this.disableEdgesRendering();
  13551. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13552. return this;
  13553. };
  13554. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13555. /**
  13556. * Returns true if the mesh is blocked. Used by the class Mesh.
  13557. * Returns the boolean `false` by default.
  13558. */
  13559. get: function () {
  13560. return false;
  13561. },
  13562. enumerable: true,
  13563. configurable: true
  13564. });
  13565. /**
  13566. * Returns the mesh itself by default, used by the class Mesh.
  13567. * Returned type : AbstractMesh
  13568. */
  13569. AbstractMesh.prototype.getLOD = function (camera) {
  13570. return this;
  13571. };
  13572. /**
  13573. * Returns 0 by default, used by the class Mesh.
  13574. * Returns an integer.
  13575. */
  13576. AbstractMesh.prototype.getTotalVertices = function () {
  13577. return 0;
  13578. };
  13579. /**
  13580. * Returns null by default, used by the class Mesh.
  13581. * Returned type : integer array
  13582. */
  13583. AbstractMesh.prototype.getIndices = function () {
  13584. return null;
  13585. };
  13586. /**
  13587. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13588. * Returned type : float array or Float32Array
  13589. */
  13590. AbstractMesh.prototype.getVerticesData = function (kind) {
  13591. return null;
  13592. };
  13593. /**
  13594. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13595. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13596. * The `data` are either a numeric array either a Float32Array.
  13597. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13598. * 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).
  13599. * Note that a new underlying VertexBuffer object is created each call.
  13600. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13601. *
  13602. * Possible `kind` values :
  13603. * - BABYLON.VertexBuffer.PositionKind
  13604. * - BABYLON.VertexBuffer.UVKind
  13605. * - BABYLON.VertexBuffer.UV2Kind
  13606. * - BABYLON.VertexBuffer.UV3Kind
  13607. * - BABYLON.VertexBuffer.UV4Kind
  13608. * - BABYLON.VertexBuffer.UV5Kind
  13609. * - BABYLON.VertexBuffer.UV6Kind
  13610. * - BABYLON.VertexBuffer.ColorKind
  13611. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13612. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13613. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13614. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13615. *
  13616. * Returns the Mesh.
  13617. */
  13618. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13619. return this;
  13620. };
  13621. /**
  13622. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13623. * If the mesh has no geometry, it is simply returned as it is.
  13624. * The `data` are either a numeric array either a Float32Array.
  13625. * No new underlying VertexBuffer object is created.
  13626. * 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.
  13627. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13628. *
  13629. * Possible `kind` values :
  13630. * - BABYLON.VertexBuffer.PositionKind
  13631. * - BABYLON.VertexBuffer.UVKind
  13632. * - BABYLON.VertexBuffer.UV2Kind
  13633. * - BABYLON.VertexBuffer.UV3Kind
  13634. * - BABYLON.VertexBuffer.UV4Kind
  13635. * - BABYLON.VertexBuffer.UV5Kind
  13636. * - BABYLON.VertexBuffer.UV6Kind
  13637. * - BABYLON.VertexBuffer.ColorKind
  13638. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13639. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13640. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13641. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13642. *
  13643. * Returns the Mesh.
  13644. */
  13645. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13646. return this;
  13647. };
  13648. /**
  13649. * Sets the mesh indices.
  13650. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13651. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13652. * This method creates a new index buffer each call.
  13653. * Returns the Mesh.
  13654. */
  13655. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13656. return this;
  13657. };
  13658. /** Returns false by default, used by the class Mesh.
  13659. * Returns a boolean
  13660. */
  13661. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13662. return false;
  13663. };
  13664. /**
  13665. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13666. * Returns a BoundingInfo
  13667. */
  13668. AbstractMesh.prototype.getBoundingInfo = function () {
  13669. if (this._masterMesh) {
  13670. return this._masterMesh.getBoundingInfo();
  13671. }
  13672. if (!this._boundingInfo) {
  13673. this._updateBoundingInfo();
  13674. }
  13675. return this._boundingInfo;
  13676. };
  13677. /**
  13678. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  13679. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  13680. */
  13681. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  13682. if (includeDescendants === void 0) { includeDescendants = true; }
  13683. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  13684. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  13685. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  13686. if (maxDimension === 0) {
  13687. return this;
  13688. }
  13689. var scale = 1 / maxDimension;
  13690. this.scaling.scaleInPlace(scale);
  13691. return this;
  13692. };
  13693. /**
  13694. * Sets a mesh new object BoundingInfo.
  13695. * Returns the AbstractMesh.
  13696. */
  13697. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13698. this._boundingInfo = boundingInfo;
  13699. return this;
  13700. };
  13701. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13702. get: function () {
  13703. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13704. },
  13705. enumerable: true,
  13706. configurable: true
  13707. });
  13708. AbstractMesh.prototype._preActivate = function () {
  13709. };
  13710. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13711. };
  13712. AbstractMesh.prototype._activate = function (renderId) {
  13713. this._renderId = renderId;
  13714. };
  13715. /**
  13716. * Returns the latest update of the World matrix
  13717. * Returns a Matrix.
  13718. */
  13719. AbstractMesh.prototype.getWorldMatrix = function () {
  13720. if (this._masterMesh) {
  13721. return this._masterMesh.getWorldMatrix();
  13722. }
  13723. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13724. this.computeWorldMatrix();
  13725. }
  13726. return this._worldMatrix;
  13727. };
  13728. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13729. /**
  13730. * Returns directly the latest state of the mesh World matrix.
  13731. * A Matrix is returned.
  13732. */
  13733. get: function () {
  13734. return this._worldMatrix;
  13735. },
  13736. enumerable: true,
  13737. configurable: true
  13738. });
  13739. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13740. /**
  13741. * Returns the current mesh absolute position.
  13742. * Retuns a Vector3.
  13743. */
  13744. get: function () {
  13745. return this._absolutePosition;
  13746. },
  13747. enumerable: true,
  13748. configurable: true
  13749. });
  13750. /**
  13751. * Prevents the World matrix to be computed any longer.
  13752. * Returns the AbstractMesh.
  13753. */
  13754. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13755. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13756. this.computeWorldMatrix(true);
  13757. this._isWorldMatrixFrozen = true;
  13758. return this;
  13759. };
  13760. /**
  13761. * Allows back the World matrix computation.
  13762. * Returns the AbstractMesh.
  13763. */
  13764. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13765. this._isWorldMatrixFrozen = false;
  13766. this.computeWorldMatrix(true);
  13767. return this;
  13768. };
  13769. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13770. /**
  13771. * True if the World matrix has been frozen.
  13772. * Returns a boolean.
  13773. */
  13774. get: function () {
  13775. return this._isWorldMatrixFrozen;
  13776. },
  13777. enumerable: true,
  13778. configurable: true
  13779. });
  13780. /**
  13781. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13782. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13783. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13784. * The passed axis is also normalized.
  13785. * Returns the AbstractMesh.
  13786. */
  13787. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13788. axis.normalize();
  13789. if (!this.rotationQuaternion) {
  13790. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13791. this.rotation = BABYLON.Vector3.Zero();
  13792. }
  13793. var rotationQuaternion;
  13794. if (!space || space === BABYLON.Space.LOCAL) {
  13795. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13796. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13797. }
  13798. else {
  13799. if (this.parent) {
  13800. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13801. invertParentWorldMatrix.invert();
  13802. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13803. }
  13804. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13805. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13806. }
  13807. return this;
  13808. };
  13809. /**
  13810. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13811. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13812. * The passed axis is also normalized.
  13813. * Returns the AbstractMesh.
  13814. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13815. */
  13816. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13817. axis.normalize();
  13818. if (!this.rotationQuaternion) {
  13819. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13820. this.rotation.copyFromFloats(0, 0, 0);
  13821. }
  13822. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13823. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13824. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13825. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13826. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13827. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13828. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13829. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13830. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13831. return this;
  13832. };
  13833. /**
  13834. * Translates the mesh along the axis vector for the passed distance in the given space.
  13835. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13836. * Returns the AbstractMesh.
  13837. */
  13838. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13839. var displacementVector = axis.scale(distance);
  13840. if (!space || space === BABYLON.Space.LOCAL) {
  13841. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13842. this.setPositionWithLocalVector(tempV3);
  13843. }
  13844. else {
  13845. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13846. }
  13847. return this;
  13848. };
  13849. /**
  13850. * Adds a rotation step to the mesh current rotation.
  13851. * x, y, z are Euler angles expressed in radians.
  13852. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13853. * This means this rotation is made in the mesh local space only.
  13854. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13855. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13856. * ```javascript
  13857. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13858. * ```
  13859. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13860. * 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.
  13861. * Returns the AbstractMesh.
  13862. */
  13863. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13864. var rotationQuaternion;
  13865. if (this.rotationQuaternion) {
  13866. rotationQuaternion = this.rotationQuaternion;
  13867. }
  13868. else {
  13869. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13870. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13871. }
  13872. var accumulation = BABYLON.Tmp.Quaternion[0];
  13873. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13874. rotationQuaternion.multiplyInPlace(accumulation);
  13875. if (!this.rotationQuaternion) {
  13876. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13877. }
  13878. return this;
  13879. };
  13880. /**
  13881. * Retuns the mesh absolute position in the World.
  13882. * Returns a Vector3.
  13883. */
  13884. AbstractMesh.prototype.getAbsolutePosition = function () {
  13885. this.computeWorldMatrix();
  13886. return this._absolutePosition;
  13887. };
  13888. /**
  13889. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13890. * Returns the AbstractMesh.
  13891. */
  13892. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13893. if (!absolutePosition) {
  13894. return this;
  13895. }
  13896. var absolutePositionX;
  13897. var absolutePositionY;
  13898. var absolutePositionZ;
  13899. if (absolutePosition.x === undefined) {
  13900. if (arguments.length < 3) {
  13901. return this;
  13902. }
  13903. absolutePositionX = arguments[0];
  13904. absolutePositionY = arguments[1];
  13905. absolutePositionZ = arguments[2];
  13906. }
  13907. else {
  13908. absolutePositionX = absolutePosition.x;
  13909. absolutePositionY = absolutePosition.y;
  13910. absolutePositionZ = absolutePosition.z;
  13911. }
  13912. if (this.parent) {
  13913. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13914. invertParentWorldMatrix.invert();
  13915. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13916. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13917. }
  13918. else {
  13919. this.position.x = absolutePositionX;
  13920. this.position.y = absolutePositionY;
  13921. this.position.z = absolutePositionZ;
  13922. }
  13923. return this;
  13924. };
  13925. // ================================== Point of View Movement =================================
  13926. /**
  13927. * Perform relative position change from the point of view of behind the front of the mesh.
  13928. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13929. * Supports definition of mesh facing forward or backward.
  13930. * @param {number} amountRight
  13931. * @param {number} amountUp
  13932. * @param {number} amountForward
  13933. *
  13934. * Returns the AbstractMesh.
  13935. */
  13936. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13937. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13938. return this;
  13939. };
  13940. /**
  13941. * Calculate relative position change from the point of view of behind the front of the mesh.
  13942. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13943. * Supports definition of mesh facing forward or backward.
  13944. * @param {number} amountRight
  13945. * @param {number} amountUp
  13946. * @param {number} amountForward
  13947. *
  13948. * Returns a new Vector3.
  13949. */
  13950. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13951. var rotMatrix = new BABYLON.Matrix();
  13952. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13953. rotQuaternion.toRotationMatrix(rotMatrix);
  13954. var translationDelta = BABYLON.Vector3.Zero();
  13955. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13956. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13957. return translationDelta;
  13958. };
  13959. // ================================== Point of View Rotation =================================
  13960. /**
  13961. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13962. * Supports definition of mesh facing forward or backward.
  13963. * @param {number} flipBack
  13964. * @param {number} twirlClockwise
  13965. * @param {number} tiltRight
  13966. *
  13967. * Returns the AbstractMesh.
  13968. */
  13969. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13970. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13971. return this;
  13972. };
  13973. /**
  13974. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13975. * Supports definition of mesh facing forward or backward.
  13976. * @param {number} flipBack
  13977. * @param {number} twirlClockwise
  13978. * @param {number} tiltRight
  13979. *
  13980. * Returns a new Vector3.
  13981. */
  13982. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13983. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13984. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13985. };
  13986. /**
  13987. * Sets a new pivot matrix to the mesh.
  13988. * Returns the AbstractMesh.
  13989. */
  13990. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13991. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13992. this._pivotMatrix = matrix.clone();
  13993. this._cache.pivotMatrixUpdated = true;
  13994. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13995. if (this._postMultiplyPivotMatrix) {
  13996. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13997. }
  13998. return this;
  13999. };
  14000. /**
  14001. * Returns the mesh pivot matrix.
  14002. * Default : Identity.
  14003. * A Matrix is returned.
  14004. */
  14005. AbstractMesh.prototype.getPivotMatrix = function () {
  14006. return this._pivotMatrix;
  14007. };
  14008. AbstractMesh.prototype._isSynchronized = function () {
  14009. if (this._isDirty) {
  14010. return false;
  14011. }
  14012. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  14013. return false;
  14014. if (this._cache.pivotMatrixUpdated) {
  14015. return false;
  14016. }
  14017. if (this.infiniteDistance) {
  14018. return false;
  14019. }
  14020. if (!this._cache.position.equals(this.position))
  14021. return false;
  14022. if (this.rotationQuaternion) {
  14023. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14024. return false;
  14025. }
  14026. if (!this._cache.rotation.equals(this.rotation))
  14027. return false;
  14028. if (!this._cache.scaling.equals(this.scaling))
  14029. return false;
  14030. return true;
  14031. };
  14032. AbstractMesh.prototype._initCache = function () {
  14033. _super.prototype._initCache.call(this);
  14034. this._cache.localMatrixUpdated = false;
  14035. this._cache.position = BABYLON.Vector3.Zero();
  14036. this._cache.scaling = BABYLON.Vector3.Zero();
  14037. this._cache.rotation = BABYLON.Vector3.Zero();
  14038. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14039. this._cache.billboardMode = -1;
  14040. };
  14041. AbstractMesh.prototype.markAsDirty = function (property) {
  14042. if (property === "rotation") {
  14043. this.rotationQuaternion = null;
  14044. }
  14045. this._currentRenderId = Number.MAX_VALUE;
  14046. this._isDirty = true;
  14047. return this;
  14048. };
  14049. /**
  14050. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14051. * @param includeDescendants Include bounding info from descendants as well (true by default).
  14052. */
  14053. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  14054. if (includeDescendants === void 0) { includeDescendants = true; }
  14055. this.computeWorldMatrix(true);
  14056. var min;
  14057. var max;
  14058. var boundingInfo = this.getBoundingInfo();
  14059. if (!this.subMeshes || !boundingInfo) {
  14060. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14061. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14062. }
  14063. else {
  14064. min = boundingInfo.boundingBox.minimumWorld;
  14065. max = boundingInfo.boundingBox.maximumWorld;
  14066. }
  14067. if (includeDescendants) {
  14068. var descendants = this.getDescendants(false);
  14069. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14070. var descendant = descendants_1[_i];
  14071. var childMesh = descendant;
  14072. childMesh.computeWorldMatrix(true);
  14073. var childBoundingInfo = childMesh.getBoundingInfo();
  14074. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  14075. continue;
  14076. }
  14077. var boundingBox = childBoundingInfo.boundingBox;
  14078. var minBox = boundingBox.minimumWorld;
  14079. var maxBox = boundingBox.maximumWorld;
  14080. BABYLON.Tools.CheckExtends(minBox, min, max);
  14081. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14082. }
  14083. }
  14084. return {
  14085. min: min,
  14086. max: max
  14087. };
  14088. };
  14089. /**
  14090. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14091. * Returns the AbstractMesh.
  14092. */
  14093. AbstractMesh.prototype._updateBoundingInfo = function () {
  14094. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14095. this._boundingInfo.update(this.worldMatrixFromCache);
  14096. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14097. return this;
  14098. };
  14099. /**
  14100. * Update a mesh's children BoundingInfo objects only.
  14101. * Returns the AbstractMesh.
  14102. */
  14103. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14104. if (!this.subMeshes) {
  14105. return this;
  14106. }
  14107. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14108. var subMesh = this.subMeshes[subIndex];
  14109. if (!subMesh.IsGlobal) {
  14110. subMesh.updateBoundingInfo(matrix);
  14111. }
  14112. }
  14113. return this;
  14114. };
  14115. /**
  14116. * Computes the mesh World matrix and returns it.
  14117. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14118. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14119. * If the parameter `force`is set to `true`, the actual computation is done.
  14120. * Returns the mesh World Matrix.
  14121. */
  14122. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  14123. if (this._isWorldMatrixFrozen) {
  14124. return this._worldMatrix;
  14125. }
  14126. if (!force && this.isSynchronized(true)) {
  14127. return this._worldMatrix;
  14128. }
  14129. this._cache.position.copyFrom(this.position);
  14130. this._cache.scaling.copyFrom(this.scaling);
  14131. this._cache.pivotMatrixUpdated = false;
  14132. this._cache.billboardMode = this.billboardMode;
  14133. this._currentRenderId = this.getScene().getRenderId();
  14134. this._isDirty = false;
  14135. // Scaling
  14136. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14137. // Rotation
  14138. //rotate, if quaternion is set and rotation was used
  14139. if (this.rotationQuaternion) {
  14140. var len = this.rotation.length();
  14141. if (len) {
  14142. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14143. this.rotation.copyFromFloats(0, 0, 0);
  14144. }
  14145. }
  14146. if (this.rotationQuaternion) {
  14147. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14148. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14149. }
  14150. else {
  14151. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14152. this._cache.rotation.copyFrom(this.rotation);
  14153. }
  14154. // Translation
  14155. var camera = this.getScene().activeCamera;
  14156. if (this.infiniteDistance && !this.parent && camera) {
  14157. var cameraWorldMatrix = camera.getWorldMatrix();
  14158. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14159. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14160. }
  14161. else {
  14162. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14163. }
  14164. // Composing transformations
  14165. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14166. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14167. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14168. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14169. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  14170. // Need to decompose each rotation here
  14171. var currentPosition = BABYLON.Tmp.Vector3[3];
  14172. if (this.parent && this.parent.getWorldMatrix) {
  14173. if (this._meshToBoneReferal) {
  14174. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14175. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14176. }
  14177. else {
  14178. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14179. }
  14180. }
  14181. else {
  14182. currentPosition.copyFrom(this.position);
  14183. }
  14184. currentPosition.subtractInPlace(camera.globalPosition);
  14185. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14186. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  14187. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14188. }
  14189. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  14190. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14191. }
  14192. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  14193. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14194. }
  14195. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14196. }
  14197. else {
  14198. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14199. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14200. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14201. }
  14202. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14203. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14204. }
  14205. // Local world
  14206. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14207. // Parent
  14208. if (this.parent && this.parent.getWorldMatrix) {
  14209. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  14210. if (this._meshToBoneReferal) {
  14211. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14212. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14213. }
  14214. else {
  14215. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14216. }
  14217. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14218. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14219. this._worldMatrix.copyFrom(this._localWorld);
  14220. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14221. }
  14222. else {
  14223. if (this._meshToBoneReferal) {
  14224. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14225. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14226. }
  14227. else {
  14228. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14229. }
  14230. }
  14231. this._markSyncedWithParent();
  14232. }
  14233. else {
  14234. this._worldMatrix.copyFrom(this._localWorld);
  14235. }
  14236. // Post multiply inverse of pivotMatrix
  14237. if (this._postMultiplyPivotMatrix) {
  14238. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14239. }
  14240. // Normal matrix
  14241. if (this.scaling.isNonUniform) {
  14242. this.nonUniformScaling = true;
  14243. }
  14244. else if (this.parent && this.parent._nonUniformScaling) {
  14245. this.nonUniformScaling = this.parent._nonUniformScaling;
  14246. }
  14247. else {
  14248. this.nonUniformScaling = false;
  14249. }
  14250. // Bounding info
  14251. this._updateBoundingInfo();
  14252. // Absolute position
  14253. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14254. // Callbacks
  14255. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14256. if (!this._poseMatrix) {
  14257. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14258. }
  14259. return this._worldMatrix;
  14260. };
  14261. /**
  14262. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14263. * @param func: callback function to add
  14264. *
  14265. * Returns the AbstractMesh.
  14266. */
  14267. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14268. this.onAfterWorldMatrixUpdateObservable.add(func);
  14269. return this;
  14270. };
  14271. /**
  14272. * Removes a registered callback function.
  14273. * Returns the AbstractMesh.
  14274. */
  14275. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14276. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14277. return this;
  14278. };
  14279. /**
  14280. * Sets the mesh position in its local space.
  14281. * Returns the AbstractMesh.
  14282. */
  14283. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  14284. this.computeWorldMatrix();
  14285. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14286. return this;
  14287. };
  14288. /**
  14289. * Returns the mesh position in the local space from the current World matrix values.
  14290. * Returns a new Vector3.
  14291. */
  14292. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  14293. this.computeWorldMatrix();
  14294. var invLocalWorldMatrix = this._localWorld.clone();
  14295. invLocalWorldMatrix.invert();
  14296. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14297. };
  14298. /**
  14299. * Translates the mesh along the passed Vector3 in its local space.
  14300. * Returns the AbstractMesh.
  14301. */
  14302. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  14303. this.computeWorldMatrix(true);
  14304. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14305. return this;
  14306. };
  14307. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14308. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  14309. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  14310. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  14311. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  14312. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  14313. /// <returns>Mesh oriented towards targetMesh</returns>
  14314. if (yawCor === void 0) { yawCor = 0; }
  14315. if (pitchCor === void 0) { pitchCor = 0; }
  14316. if (rollCor === void 0) { rollCor = 0; }
  14317. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14318. var dv = AbstractMesh._lookAtVectorCache;
  14319. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14320. targetPoint.subtractToRef(pos, dv);
  14321. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14322. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14323. var pitch = Math.atan2(dv.y, len);
  14324. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  14325. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14326. return this;
  14327. };
  14328. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  14329. this._meshToBoneReferal = affectedMesh;
  14330. this.parent = bone;
  14331. if (bone.getWorldMatrix().determinant() < 0) {
  14332. this.scalingDeterminant *= -1;
  14333. }
  14334. return this;
  14335. };
  14336. AbstractMesh.prototype.detachFromBone = function () {
  14337. if (!this.parent) {
  14338. return this;
  14339. }
  14340. if (this.parent.getWorldMatrix().determinant() < 0) {
  14341. this.scalingDeterminant *= -1;
  14342. }
  14343. this._meshToBoneReferal = null;
  14344. this.parent = null;
  14345. return this;
  14346. };
  14347. /**
  14348. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14349. * A mesh is in the frustum if its bounding box intersects the frustum.
  14350. * Boolean returned.
  14351. */
  14352. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14353. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14354. };
  14355. /**
  14356. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14357. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14358. * Boolean returned.
  14359. */
  14360. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14361. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14362. ;
  14363. };
  14364. /**
  14365. * True if the mesh intersects another mesh or a SolidParticle object.
  14366. * 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)
  14367. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14368. * Returns a boolean.
  14369. */
  14370. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14371. if (precise === void 0) { precise = false; }
  14372. if (!this._boundingInfo || !mesh._boundingInfo) {
  14373. return false;
  14374. }
  14375. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14376. return true;
  14377. }
  14378. if (includeDescendants) {
  14379. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14380. var child = _a[_i];
  14381. if (child.intersectsMesh(mesh, precise, true)) {
  14382. return true;
  14383. }
  14384. }
  14385. }
  14386. return false;
  14387. };
  14388. /**
  14389. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14390. * Returns a boolean.
  14391. */
  14392. AbstractMesh.prototype.intersectsPoint = function (point) {
  14393. if (!this._boundingInfo) {
  14394. return false;
  14395. }
  14396. return this._boundingInfo.intersectsPoint(point);
  14397. };
  14398. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14399. return this.physicsImpostor;
  14400. };
  14401. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14402. if (camera === void 0) { camera = null; }
  14403. if (!camera) {
  14404. camera = this.getScene().activeCamera;
  14405. }
  14406. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14407. };
  14408. /**
  14409. * Returns the distance from the mesh to the active camera.
  14410. * Returns a float.
  14411. */
  14412. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14413. if (camera === void 0) { camera = null; }
  14414. if (!camera) {
  14415. camera = this.getScene().activeCamera;
  14416. }
  14417. return this.absolutePosition.subtract(camera.position).length();
  14418. };
  14419. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14420. if (!this.physicsImpostor) {
  14421. return this;
  14422. }
  14423. this.physicsImpostor.applyImpulse(force, contactPoint);
  14424. return this;
  14425. };
  14426. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14427. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14428. return this;
  14429. }
  14430. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14431. mainPivot: pivot1,
  14432. connectedPivot: pivot2,
  14433. nativeParams: options
  14434. });
  14435. return this;
  14436. };
  14437. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14438. // Collisions
  14439. /**
  14440. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14441. * Default `false`.
  14442. */
  14443. get: function () {
  14444. return this._checkCollisions;
  14445. },
  14446. set: function (collisionEnabled) {
  14447. this._checkCollisions = collisionEnabled;
  14448. if (this.getScene().workerCollisions) {
  14449. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14450. }
  14451. },
  14452. enumerable: true,
  14453. configurable: true
  14454. });
  14455. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14456. var globalPosition = this.getAbsolutePosition();
  14457. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14458. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14459. if (!this._collider) {
  14460. this._collider = new BABYLON.Collider();
  14461. }
  14462. this._collider.radius = this.ellipsoid;
  14463. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14464. return this;
  14465. };
  14466. // Submeshes octree
  14467. /**
  14468. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14469. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14470. * Returns an Octree of submeshes.
  14471. */
  14472. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14473. if (maxCapacity === void 0) { maxCapacity = 64; }
  14474. if (maxDepth === void 0) { maxDepth = 2; }
  14475. if (!this._submeshesOctree) {
  14476. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14477. }
  14478. this.computeWorldMatrix(true);
  14479. var boundingInfo = this.getBoundingInfo();
  14480. // Update octree
  14481. if (boundingInfo) {
  14482. var bbox = boundingInfo.boundingBox;
  14483. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14484. }
  14485. return this._submeshesOctree;
  14486. };
  14487. // Collisions
  14488. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14489. this._generatePointsArray();
  14490. if (!this._positions) {
  14491. return this;
  14492. }
  14493. // Transformation
  14494. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14495. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14496. subMesh._lastColliderWorldVertices = [];
  14497. subMesh._trianglePlanes = [];
  14498. var start = subMesh.verticesStart;
  14499. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14500. for (var i = start; i < end; i++) {
  14501. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14502. }
  14503. }
  14504. // Collide
  14505. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14506. if (collider.collisionFound) {
  14507. collider.collidedMesh = this;
  14508. }
  14509. return this;
  14510. };
  14511. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14512. var subMeshes;
  14513. var len;
  14514. // Octrees
  14515. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14516. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14517. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14518. len = intersections.length;
  14519. subMeshes = intersections.data;
  14520. }
  14521. else {
  14522. subMeshes = this.subMeshes;
  14523. len = subMeshes.length;
  14524. }
  14525. for (var index = 0; index < len; index++) {
  14526. var subMesh = subMeshes[index];
  14527. // Bounding test
  14528. if (len > 1 && !subMesh._checkCollision(collider))
  14529. continue;
  14530. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14531. }
  14532. return this;
  14533. };
  14534. AbstractMesh.prototype._checkCollision = function (collider) {
  14535. // Bounding box test
  14536. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14537. return this;
  14538. // Transformation matrix
  14539. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14540. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14541. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14542. return this;
  14543. };
  14544. // Picking
  14545. AbstractMesh.prototype._generatePointsArray = function () {
  14546. return false;
  14547. };
  14548. /**
  14549. * Checks if the passed Ray intersects with the mesh.
  14550. * Returns an object PickingInfo.
  14551. */
  14552. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14553. var pickingInfo = new BABYLON.PickingInfo();
  14554. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14555. return pickingInfo;
  14556. }
  14557. if (!this._generatePointsArray()) {
  14558. return pickingInfo;
  14559. }
  14560. var intersectInfo = null;
  14561. // Octrees
  14562. var subMeshes;
  14563. var len;
  14564. if (this._submeshesOctree && this.useOctreeForPicking) {
  14565. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14566. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14567. len = intersections.length;
  14568. subMeshes = intersections.data;
  14569. }
  14570. else {
  14571. subMeshes = this.subMeshes;
  14572. len = subMeshes.length;
  14573. }
  14574. for (var index = 0; index < len; index++) {
  14575. var subMesh = subMeshes[index];
  14576. // Bounding test
  14577. if (len > 1 && !subMesh.canIntersects(ray))
  14578. continue;
  14579. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14580. if (currentIntersectInfo) {
  14581. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14582. intersectInfo = currentIntersectInfo;
  14583. intersectInfo.subMeshId = index;
  14584. if (fastCheck) {
  14585. break;
  14586. }
  14587. }
  14588. }
  14589. }
  14590. if (intersectInfo) {
  14591. // Get picked point
  14592. var world = this.getWorldMatrix();
  14593. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14594. var direction = ray.direction.clone();
  14595. direction = direction.scale(intersectInfo.distance);
  14596. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14597. var pickedPoint = worldOrigin.add(worldDirection);
  14598. // Return result
  14599. pickingInfo.hit = true;
  14600. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14601. pickingInfo.pickedPoint = pickedPoint;
  14602. pickingInfo.pickedMesh = this;
  14603. pickingInfo.bu = intersectInfo.bu || 0;
  14604. pickingInfo.bv = intersectInfo.bv || 0;
  14605. pickingInfo.faceId = intersectInfo.faceId;
  14606. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14607. return pickingInfo;
  14608. }
  14609. return pickingInfo;
  14610. };
  14611. /**
  14612. * Clones the mesh, used by the class Mesh.
  14613. * Just returns `null` for an AbstractMesh.
  14614. */
  14615. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14616. return null;
  14617. };
  14618. /**
  14619. * Disposes all the mesh submeshes.
  14620. * Returns the AbstractMesh.
  14621. */
  14622. AbstractMesh.prototype.releaseSubMeshes = function () {
  14623. if (this.subMeshes) {
  14624. while (this.subMeshes.length) {
  14625. this.subMeshes[0].dispose();
  14626. }
  14627. }
  14628. else {
  14629. this.subMeshes = new Array();
  14630. }
  14631. return this;
  14632. };
  14633. /**
  14634. * Disposes the AbstractMesh.
  14635. * Some internal references are kept for further use.
  14636. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14637. * Returns nothing.
  14638. */
  14639. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14640. var _this = this;
  14641. var index;
  14642. // Action manager
  14643. if (this.actionManager) {
  14644. this.actionManager.dispose();
  14645. this.actionManager = null;
  14646. }
  14647. // Skeleton
  14648. this.skeleton = null;
  14649. // Animations
  14650. this.getScene().stopAnimation(this);
  14651. // Physics
  14652. if (this.physicsImpostor) {
  14653. this.physicsImpostor.dispose();
  14654. }
  14655. // Intersections in progress
  14656. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14657. var other = this._intersectionsInProgress[index];
  14658. var pos = other._intersectionsInProgress.indexOf(this);
  14659. other._intersectionsInProgress.splice(pos, 1);
  14660. }
  14661. this._intersectionsInProgress = [];
  14662. // Lights
  14663. var lights = this.getScene().lights;
  14664. lights.forEach(function (light) {
  14665. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14666. if (meshIndex !== -1) {
  14667. light.includedOnlyMeshes.splice(meshIndex, 1);
  14668. }
  14669. meshIndex = light.excludedMeshes.indexOf(_this);
  14670. if (meshIndex !== -1) {
  14671. light.excludedMeshes.splice(meshIndex, 1);
  14672. }
  14673. // Shadow generators
  14674. var generator = light.getShadowGenerator();
  14675. if (generator) {
  14676. var shadowMap = generator.getShadowMap();
  14677. if (shadowMap && shadowMap.renderList) {
  14678. meshIndex = shadowMap.renderList.indexOf(_this);
  14679. if (meshIndex !== -1) {
  14680. shadowMap.renderList.splice(meshIndex, 1);
  14681. }
  14682. }
  14683. }
  14684. });
  14685. // Edges
  14686. if (this._edgesRenderer) {
  14687. this._edgesRenderer.dispose();
  14688. this._edgesRenderer = null;
  14689. }
  14690. // SubMeshes
  14691. if (this.getClassName() !== "InstancedMesh") {
  14692. this.releaseSubMeshes();
  14693. }
  14694. // Octree
  14695. var sceneOctree = this.getScene().selectionOctree;
  14696. if (sceneOctree) {
  14697. var index = sceneOctree.dynamicContent.indexOf(this);
  14698. if (index !== -1) {
  14699. sceneOctree.dynamicContent.splice(index, 1);
  14700. }
  14701. }
  14702. // Query
  14703. var engine = this.getScene().getEngine();
  14704. if (this._occlusionQuery) {
  14705. this._isOcclusionQueryInProgress = false;
  14706. engine.deleteQuery(this._occlusionQuery);
  14707. this._occlusionQuery = null;
  14708. }
  14709. // Engine
  14710. engine.wipeCaches();
  14711. // Remove from scene
  14712. this.getScene().removeMesh(this);
  14713. if (!doNotRecurse) {
  14714. // Particles
  14715. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14716. if (this.getScene().particleSystems[index].emitter === this) {
  14717. this.getScene().particleSystems[index].dispose();
  14718. index--;
  14719. }
  14720. }
  14721. // Children
  14722. var objects = this.getDescendants(true);
  14723. for (index = 0; index < objects.length; index++) {
  14724. objects[index].dispose();
  14725. }
  14726. }
  14727. else {
  14728. var childMeshes = this.getChildMeshes(true);
  14729. for (index = 0; index < childMeshes.length; index++) {
  14730. var child = childMeshes[index];
  14731. child.parent = null;
  14732. child.computeWorldMatrix(true);
  14733. }
  14734. }
  14735. // facet data
  14736. if (this._facetDataEnabled) {
  14737. this.disableFacetData();
  14738. }
  14739. this.onAfterWorldMatrixUpdateObservable.clear();
  14740. this.onCollideObservable.clear();
  14741. this.onCollisionPositionChangeObservable.clear();
  14742. this._isDisposed = true;
  14743. _super.prototype.dispose.call(this);
  14744. };
  14745. /**
  14746. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14747. * This Vector3 is expressed in the World space.
  14748. */
  14749. AbstractMesh.prototype.getDirection = function (localAxis) {
  14750. var result = BABYLON.Vector3.Zero();
  14751. this.getDirectionToRef(localAxis, result);
  14752. return result;
  14753. };
  14754. /**
  14755. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14756. * localAxis is expressed in the mesh local space.
  14757. * result is computed in the Wordl space from the mesh World matrix.
  14758. * Returns the AbstractMesh.
  14759. */
  14760. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14761. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14762. return this;
  14763. };
  14764. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14765. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14766. if (this.getScene().getRenderId() == 0) {
  14767. this.computeWorldMatrix(true);
  14768. }
  14769. var wm = this.getWorldMatrix();
  14770. if (space == BABYLON.Space.WORLD) {
  14771. var tmat = BABYLON.Tmp.Matrix[0];
  14772. wm.invertToRef(tmat);
  14773. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14774. }
  14775. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14776. this._pivotMatrix.m[12] = -point.x;
  14777. this._pivotMatrix.m[13] = -point.y;
  14778. this._pivotMatrix.m[14] = -point.z;
  14779. this._cache.pivotMatrixUpdated = true;
  14780. return this;
  14781. };
  14782. /**
  14783. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14784. */
  14785. AbstractMesh.prototype.getPivotPoint = function () {
  14786. var point = BABYLON.Vector3.Zero();
  14787. this.getPivotPointToRef(point);
  14788. return point;
  14789. };
  14790. /**
  14791. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14792. * Returns the AbstractMesh.
  14793. */
  14794. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14795. result.x = -this._pivotMatrix.m[12];
  14796. result.y = -this._pivotMatrix.m[13];
  14797. result.z = -this._pivotMatrix.m[14];
  14798. return this;
  14799. };
  14800. /**
  14801. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14802. */
  14803. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14804. var point = BABYLON.Vector3.Zero();
  14805. this.getAbsolutePivotPointToRef(point);
  14806. return point;
  14807. };
  14808. /**
  14809. * Defines the passed mesh as the parent of the current mesh.
  14810. * Returns the AbstractMesh.
  14811. */
  14812. AbstractMesh.prototype.setParent = function (mesh) {
  14813. var parent = mesh;
  14814. if (mesh == null) {
  14815. var rotation = BABYLON.Tmp.Quaternion[0];
  14816. var position = BABYLON.Tmp.Vector3[0];
  14817. var scale = BABYLON.Tmp.Vector3[1];
  14818. this.getWorldMatrix().decompose(scale, rotation, position);
  14819. if (this.rotationQuaternion) {
  14820. this.rotationQuaternion.copyFrom(rotation);
  14821. }
  14822. else {
  14823. rotation.toEulerAnglesToRef(this.rotation);
  14824. }
  14825. this.position.x = position.x;
  14826. this.position.y = position.y;
  14827. this.position.z = position.z;
  14828. }
  14829. else {
  14830. var position = BABYLON.Tmp.Vector3[0];
  14831. var m1 = BABYLON.Tmp.Matrix[0];
  14832. parent.getWorldMatrix().invertToRef(m1);
  14833. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  14834. this.position.copyFrom(position);
  14835. }
  14836. this.parent = parent;
  14837. return this;
  14838. };
  14839. /**
  14840. * Adds the passed mesh as a child to the current mesh.
  14841. * Returns the AbstractMesh.
  14842. */
  14843. AbstractMesh.prototype.addChild = function (mesh) {
  14844. mesh.setParent(this);
  14845. return this;
  14846. };
  14847. /**
  14848. * Removes the passed mesh from the current mesh children list.
  14849. * Returns the AbstractMesh.
  14850. */
  14851. AbstractMesh.prototype.removeChild = function (mesh) {
  14852. mesh.setParent(null);
  14853. return this;
  14854. };
  14855. /**
  14856. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14857. * Returns the AbstractMesh.
  14858. */
  14859. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14860. result.x = this._pivotMatrix.m[12];
  14861. result.y = this._pivotMatrix.m[13];
  14862. result.z = this._pivotMatrix.m[14];
  14863. this.getPivotPointToRef(result);
  14864. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14865. return this;
  14866. };
  14867. // Facet data
  14868. /**
  14869. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14870. * Returns the AbstractMesh.
  14871. */
  14872. AbstractMesh.prototype._initFacetData = function () {
  14873. if (!this._facetNormals) {
  14874. this._facetNormals = new Array();
  14875. }
  14876. if (!this._facetPositions) {
  14877. this._facetPositions = new Array();
  14878. }
  14879. if (!this._facetPartitioning) {
  14880. this._facetPartitioning = new Array();
  14881. }
  14882. this._facetNb = this.getIndices().length / 3;
  14883. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14884. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14885. for (var f = 0; f < this._facetNb; f++) {
  14886. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14887. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14888. }
  14889. this._facetDataEnabled = true;
  14890. return this;
  14891. };
  14892. /**
  14893. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14894. * This method can be called within the render loop.
  14895. * 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.
  14896. * Returns the AbstractMesh.
  14897. */
  14898. AbstractMesh.prototype.updateFacetData = function () {
  14899. if (!this._facetDataEnabled) {
  14900. this._initFacetData();
  14901. }
  14902. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14903. var indices = this.getIndices();
  14904. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14905. var bInfo = this.getBoundingInfo();
  14906. if (!bInfo) {
  14907. return this;
  14908. }
  14909. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14910. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14911. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14912. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14913. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14914. this._subDiv.max = this._partitioningSubdivisions;
  14915. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14916. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14917. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14918. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14919. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14920. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14921. // set the parameters for ComputeNormals()
  14922. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14923. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14924. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14925. this._facetParameters.bInfo = bInfo;
  14926. this._facetParameters.bbSize = this._bbSize;
  14927. this._facetParameters.subDiv = this._subDiv;
  14928. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14929. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14930. return this;
  14931. };
  14932. /**
  14933. * Returns the facetLocalNormals array.
  14934. * The normals are expressed in the mesh local space.
  14935. */
  14936. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14937. if (!this._facetNormals) {
  14938. this.updateFacetData();
  14939. }
  14940. return this._facetNormals;
  14941. };
  14942. /**
  14943. * Returns the facetLocalPositions array.
  14944. * The facet positions are expressed in the mesh local space.
  14945. */
  14946. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14947. if (!this._facetPositions) {
  14948. this.updateFacetData();
  14949. }
  14950. return this._facetPositions;
  14951. };
  14952. /**
  14953. * Returns the facetLocalPartioning array.
  14954. */
  14955. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14956. if (!this._facetPartitioning) {
  14957. this.updateFacetData();
  14958. }
  14959. return this._facetPartitioning;
  14960. };
  14961. /**
  14962. * Returns the i-th facet position in the world system.
  14963. * This method allocates a new Vector3 per call.
  14964. */
  14965. AbstractMesh.prototype.getFacetPosition = function (i) {
  14966. var pos = BABYLON.Vector3.Zero();
  14967. this.getFacetPositionToRef(i, pos);
  14968. return pos;
  14969. };
  14970. /**
  14971. * Sets the reference Vector3 with the i-th facet position in the world system.
  14972. * Returns the AbstractMesh.
  14973. */
  14974. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14975. var localPos = (this.getFacetLocalPositions())[i];
  14976. var world = this.getWorldMatrix();
  14977. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14978. return this;
  14979. };
  14980. /**
  14981. * Returns the i-th facet normal in the world system.
  14982. * This method allocates a new Vector3 per call.
  14983. */
  14984. AbstractMesh.prototype.getFacetNormal = function (i) {
  14985. var norm = BABYLON.Vector3.Zero();
  14986. this.getFacetNormalToRef(i, norm);
  14987. return norm;
  14988. };
  14989. /**
  14990. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14991. * Returns the AbstractMesh.
  14992. */
  14993. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14994. var localNorm = (this.getFacetLocalNormals())[i];
  14995. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14996. return this;
  14997. };
  14998. /**
  14999. * 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).
  15000. */
  15001. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15002. var bInfo = this.getBoundingInfo();
  15003. if (!bInfo) {
  15004. return null;
  15005. }
  15006. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15007. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15008. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15009. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15010. return null;
  15011. }
  15012. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15013. };
  15014. /**
  15015. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15016. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15017. * 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.
  15018. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15019. * 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.
  15020. */
  15021. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15022. if (checkFace === void 0) { checkFace = false; }
  15023. if (facing === void 0) { facing = true; }
  15024. var world = this.getWorldMatrix();
  15025. var invMat = BABYLON.Tmp.Matrix[5];
  15026. world.invertToRef(invMat);
  15027. var invVect = BABYLON.Tmp.Vector3[8];
  15028. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15029. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15030. if (projected) {
  15031. // tranform the local computed projected vector to world coordinates
  15032. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15033. }
  15034. return closest;
  15035. };
  15036. /**
  15037. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15038. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15039. * 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.
  15040. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15041. * 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.
  15042. */
  15043. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15044. if (checkFace === void 0) { checkFace = false; }
  15045. if (facing === void 0) { facing = true; }
  15046. var closest = null;
  15047. var tmpx = 0.0;
  15048. var tmpy = 0.0;
  15049. var tmpz = 0.0;
  15050. var d = 0.0; // tmp dot facet normal * facet position
  15051. var t0 = 0.0;
  15052. var projx = 0.0;
  15053. var projy = 0.0;
  15054. var projz = 0.0;
  15055. // Get all the facets in the same partitioning block than (x, y, z)
  15056. var facetPositions = this.getFacetLocalPositions();
  15057. var facetNormals = this.getFacetLocalNormals();
  15058. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15059. if (!facetsInBlock) {
  15060. return null;
  15061. }
  15062. // Get the closest facet to (x, y, z)
  15063. var shortest = Number.MAX_VALUE; // init distance vars
  15064. var tmpDistance = shortest;
  15065. var fib; // current facet in the block
  15066. var norm; // current facet normal
  15067. var p0; // current facet barycenter position
  15068. // loop on all the facets in the current partitioning block
  15069. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15070. fib = facetsInBlock[idx];
  15071. norm = facetNormals[fib];
  15072. p0 = facetPositions[fib];
  15073. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15074. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15075. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15076. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15077. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15078. projx = x + norm.x * t0;
  15079. projy = y + norm.y * t0;
  15080. projz = z + norm.z * t0;
  15081. tmpx = projx - x;
  15082. tmpy = projy - y;
  15083. tmpz = projz - z;
  15084. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15085. if (tmpDistance < shortest) {
  15086. shortest = tmpDistance;
  15087. closest = fib;
  15088. if (projected) {
  15089. projected.x = projx;
  15090. projected.y = projy;
  15091. projected.z = projz;
  15092. }
  15093. }
  15094. }
  15095. }
  15096. return closest;
  15097. };
  15098. /**
  15099. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15100. */
  15101. AbstractMesh.prototype.getFacetDataParameters = function () {
  15102. return this._facetParameters;
  15103. };
  15104. /**
  15105. * Disables the feature FacetData and frees the related memory.
  15106. * Returns the AbstractMesh.
  15107. */
  15108. AbstractMesh.prototype.disableFacetData = function () {
  15109. if (this._facetDataEnabled) {
  15110. this._facetDataEnabled = false;
  15111. this._facetPositions = new Array();
  15112. ;
  15113. this._facetNormals = new Array();
  15114. ;
  15115. this._facetPartitioning = new Array();
  15116. ;
  15117. this._facetParameters = null;
  15118. }
  15119. return this;
  15120. };
  15121. /**
  15122. * Creates new normals data for the mesh.
  15123. * @param updatable.
  15124. */
  15125. AbstractMesh.prototype.createNormals = function (updatable) {
  15126. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15127. var indices = this.getIndices();
  15128. var normals;
  15129. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15130. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15131. }
  15132. else {
  15133. normals = [];
  15134. }
  15135. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15136. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15137. };
  15138. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15139. var engine = this.getEngine();
  15140. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15141. this._isOccluded = false;
  15142. return;
  15143. }
  15144. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15145. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15146. if (isOcclusionQueryAvailable) {
  15147. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15148. this._isOcclusionQueryInProgress = false;
  15149. this._occlusionInternalRetryCounter = 0;
  15150. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15151. }
  15152. else {
  15153. this._occlusionInternalRetryCounter++;
  15154. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15155. this._isOcclusionQueryInProgress = false;
  15156. this._occlusionInternalRetryCounter = 0;
  15157. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15158. // if strict continue the last state of the object.
  15159. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15160. }
  15161. else {
  15162. return;
  15163. }
  15164. }
  15165. }
  15166. var scene = this.getScene();
  15167. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15168. if (!this._occlusionQuery) {
  15169. this._occlusionQuery = engine.createQuery();
  15170. }
  15171. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15172. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15173. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15174. this._isOcclusionQueryInProgress = true;
  15175. };
  15176. // Statics
  15177. AbstractMesh._BILLBOARDMODE_NONE = 0;
  15178. AbstractMesh._BILLBOARDMODE_X = 1;
  15179. AbstractMesh._BILLBOARDMODE_Y = 2;
  15180. AbstractMesh._BILLBOARDMODE_Z = 4;
  15181. AbstractMesh._BILLBOARDMODE_ALL = 7;
  15182. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15183. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15184. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15185. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15186. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15187. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  15188. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15189. return AbstractMesh;
  15190. }(BABYLON.Node));
  15191. BABYLON.AbstractMesh = AbstractMesh;
  15192. })(BABYLON || (BABYLON = {}));
  15193. //# sourceMappingURL=babylon.abstractMesh.js.map
  15194. var BABYLON;
  15195. (function (BABYLON) {
  15196. var Light = /** @class */ (function (_super) {
  15197. __extends(Light, _super);
  15198. /**
  15199. * Creates a Light object in the scene.
  15200. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15201. */
  15202. function Light(name, scene) {
  15203. var _this = _super.call(this, name, scene) || this;
  15204. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15205. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15206. _this.intensity = 1.0;
  15207. _this.range = Number.MAX_VALUE;
  15208. /**
  15209. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15210. * of light.
  15211. */
  15212. _this._photometricScale = 1.0;
  15213. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15214. _this._radius = 0.00001;
  15215. _this.renderPriority = 0;
  15216. /**
  15217. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15218. * the current shadow generator.
  15219. */
  15220. _this.shadowEnabled = true;
  15221. _this._excludeWithLayerMask = 0;
  15222. _this._includeOnlyWithLayerMask = 0;
  15223. _this._lightmapMode = 0;
  15224. _this._excludedMeshesIds = new Array();
  15225. _this._includedOnlyMeshesIds = new Array();
  15226. _this.getScene().addLight(_this);
  15227. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15228. _this._buildUniformLayout();
  15229. _this.includedOnlyMeshes = new Array();
  15230. _this.excludedMeshes = new Array();
  15231. _this._resyncMeshes();
  15232. return _this;
  15233. }
  15234. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15235. /**
  15236. * If every light affecting the material is in this lightmapMode,
  15237. * material.lightmapTexture adds or multiplies
  15238. * (depends on material.useLightmapAsShadowmap)
  15239. * after every other light calculations.
  15240. */
  15241. get: function () {
  15242. return Light._LIGHTMAP_DEFAULT;
  15243. },
  15244. enumerable: true,
  15245. configurable: true
  15246. });
  15247. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15248. /**
  15249. * material.lightmapTexture as only diffuse lighting from this light
  15250. * adds pnly specular lighting from this light
  15251. * adds dynamic shadows
  15252. */
  15253. get: function () {
  15254. return Light._LIGHTMAP_SPECULAR;
  15255. },
  15256. enumerable: true,
  15257. configurable: true
  15258. });
  15259. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15260. /**
  15261. * material.lightmapTexture as only lighting
  15262. * no light calculation from this light
  15263. * only adds dynamic shadows from this light
  15264. */
  15265. get: function () {
  15266. return Light._LIGHTMAP_SHADOWSONLY;
  15267. },
  15268. enumerable: true,
  15269. configurable: true
  15270. });
  15271. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15272. /**
  15273. * Each light type uses the default quantity according to its type:
  15274. * point/spot lights use luminous intensity
  15275. * directional lights use illuminance
  15276. */
  15277. get: function () {
  15278. return Light._INTENSITYMODE_AUTOMATIC;
  15279. },
  15280. enumerable: true,
  15281. configurable: true
  15282. });
  15283. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15284. /**
  15285. * lumen (lm)
  15286. */
  15287. get: function () {
  15288. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15289. },
  15290. enumerable: true,
  15291. configurable: true
  15292. });
  15293. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15294. /**
  15295. * candela (lm/sr)
  15296. */
  15297. get: function () {
  15298. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15299. },
  15300. enumerable: true,
  15301. configurable: true
  15302. });
  15303. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15304. /**
  15305. * lux (lm/m^2)
  15306. */
  15307. get: function () {
  15308. return Light._INTENSITYMODE_ILLUMINANCE;
  15309. },
  15310. enumerable: true,
  15311. configurable: true
  15312. });
  15313. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15314. /**
  15315. * nit (cd/m^2)
  15316. */
  15317. get: function () {
  15318. return Light._INTENSITYMODE_LUMINANCE;
  15319. },
  15320. enumerable: true,
  15321. configurable: true
  15322. });
  15323. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15324. /**
  15325. * Light type const id of the point light.
  15326. */
  15327. get: function () {
  15328. return Light._LIGHTTYPEID_POINTLIGHT;
  15329. },
  15330. enumerable: true,
  15331. configurable: true
  15332. });
  15333. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15334. /**
  15335. * Light type const id of the directional light.
  15336. */
  15337. get: function () {
  15338. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15339. },
  15340. enumerable: true,
  15341. configurable: true
  15342. });
  15343. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15344. /**
  15345. * Light type const id of the spot light.
  15346. */
  15347. get: function () {
  15348. return Light._LIGHTTYPEID_SPOTLIGHT;
  15349. },
  15350. enumerable: true,
  15351. configurable: true
  15352. });
  15353. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15354. /**
  15355. * Light type const id of the hemispheric light.
  15356. */
  15357. get: function () {
  15358. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15359. },
  15360. enumerable: true,
  15361. configurable: true
  15362. });
  15363. Object.defineProperty(Light.prototype, "intensityMode", {
  15364. /**
  15365. * Gets the photometric scale used to interpret the intensity.
  15366. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15367. */
  15368. get: function () {
  15369. return this._intensityMode;
  15370. },
  15371. /**
  15372. * Sets the photometric scale used to interpret the intensity.
  15373. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15374. */
  15375. set: function (value) {
  15376. this._intensityMode = value;
  15377. this._computePhotometricScale();
  15378. },
  15379. enumerable: true,
  15380. configurable: true
  15381. });
  15382. ;
  15383. ;
  15384. Object.defineProperty(Light.prototype, "radius", {
  15385. /**
  15386. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15387. */
  15388. get: function () {
  15389. return this._radius;
  15390. },
  15391. /**
  15392. * sets the light radius used by PBR Materials to simulate soft area lights.
  15393. */
  15394. set: function (value) {
  15395. this._radius = value;
  15396. this._computePhotometricScale();
  15397. },
  15398. enumerable: true,
  15399. configurable: true
  15400. });
  15401. ;
  15402. ;
  15403. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15404. get: function () {
  15405. return this._includedOnlyMeshes;
  15406. },
  15407. set: function (value) {
  15408. this._includedOnlyMeshes = value;
  15409. this._hookArrayForIncludedOnly(value);
  15410. },
  15411. enumerable: true,
  15412. configurable: true
  15413. });
  15414. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15415. get: function () {
  15416. return this._excludedMeshes;
  15417. },
  15418. set: function (value) {
  15419. this._excludedMeshes = value;
  15420. this._hookArrayForExcluded(value);
  15421. },
  15422. enumerable: true,
  15423. configurable: true
  15424. });
  15425. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15426. get: function () {
  15427. return this._excludeWithLayerMask;
  15428. },
  15429. set: function (value) {
  15430. this._excludeWithLayerMask = value;
  15431. this._resyncMeshes();
  15432. },
  15433. enumerable: true,
  15434. configurable: true
  15435. });
  15436. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15437. get: function () {
  15438. return this._includeOnlyWithLayerMask;
  15439. },
  15440. set: function (value) {
  15441. this._includeOnlyWithLayerMask = value;
  15442. this._resyncMeshes();
  15443. },
  15444. enumerable: true,
  15445. configurable: true
  15446. });
  15447. Object.defineProperty(Light.prototype, "lightmapMode", {
  15448. get: function () {
  15449. return this._lightmapMode;
  15450. },
  15451. set: function (value) {
  15452. if (this._lightmapMode === value) {
  15453. return;
  15454. }
  15455. this._lightmapMode = value;
  15456. this._markMeshesAsLightDirty();
  15457. },
  15458. enumerable: true,
  15459. configurable: true
  15460. });
  15461. Light.prototype._buildUniformLayout = function () {
  15462. // Overridden
  15463. };
  15464. /**
  15465. * Returns the string "Light".
  15466. */
  15467. Light.prototype.getClassName = function () {
  15468. return "Light";
  15469. };
  15470. /**
  15471. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15472. */
  15473. Light.prototype.toString = function (fullDetails) {
  15474. var ret = "Name: " + this.name;
  15475. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15476. if (this.animations) {
  15477. for (var i = 0; i < this.animations.length; i++) {
  15478. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15479. }
  15480. }
  15481. if (fullDetails) {
  15482. }
  15483. return ret;
  15484. };
  15485. /**
  15486. * Set the enabled state of this node.
  15487. * @param {boolean} value - the new enabled state
  15488. * @see isEnabled
  15489. */
  15490. Light.prototype.setEnabled = function (value) {
  15491. _super.prototype.setEnabled.call(this, value);
  15492. this._resyncMeshes();
  15493. };
  15494. /**
  15495. * Returns the Light associated shadow generator.
  15496. */
  15497. Light.prototype.getShadowGenerator = function () {
  15498. return this._shadowGenerator;
  15499. };
  15500. /**
  15501. * Returns a Vector3, the absolute light position in the World.
  15502. */
  15503. Light.prototype.getAbsolutePosition = function () {
  15504. return BABYLON.Vector3.Zero();
  15505. };
  15506. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15507. };
  15508. Light.prototype._getWorldMatrix = function () {
  15509. return BABYLON.Matrix.Identity();
  15510. };
  15511. /**
  15512. * Boolean : True if the light will affect the passed mesh.
  15513. */
  15514. Light.prototype.canAffectMesh = function (mesh) {
  15515. if (!mesh) {
  15516. return true;
  15517. }
  15518. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15519. return false;
  15520. }
  15521. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15522. return false;
  15523. }
  15524. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15525. return false;
  15526. }
  15527. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15528. return false;
  15529. }
  15530. return true;
  15531. };
  15532. /**
  15533. * Returns the light World matrix.
  15534. */
  15535. Light.prototype.getWorldMatrix = function () {
  15536. this._currentRenderId = this.getScene().getRenderId();
  15537. var worldMatrix = this._getWorldMatrix();
  15538. if (this.parent && this.parent.getWorldMatrix) {
  15539. if (!this._parentedWorldMatrix) {
  15540. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15541. }
  15542. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15543. this._markSyncedWithParent();
  15544. return this._parentedWorldMatrix;
  15545. }
  15546. return worldMatrix;
  15547. };
  15548. /**
  15549. * Sort function to order lights for rendering.
  15550. * @param a First Light object to compare to second.
  15551. * @param b Second Light object to compare first.
  15552. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15553. */
  15554. Light.compareLightsPriority = function (a, b) {
  15555. //shadow-casting lights have priority over non-shadow-casting lights
  15556. //the renderPrioirty is a secondary sort criterion
  15557. if (a.shadowEnabled !== b.shadowEnabled) {
  15558. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15559. }
  15560. return b.renderPriority - a.renderPriority;
  15561. };
  15562. /**
  15563. * Disposes the light.
  15564. */
  15565. Light.prototype.dispose = function () {
  15566. if (this._shadowGenerator) {
  15567. this._shadowGenerator.dispose();
  15568. this._shadowGenerator = null;
  15569. }
  15570. // Animations
  15571. this.getScene().stopAnimation(this);
  15572. // Remove from meshes
  15573. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15574. var mesh = _a[_i];
  15575. mesh._removeLightSource(this);
  15576. }
  15577. this._uniformBuffer.dispose();
  15578. // Remove from scene
  15579. this.getScene().removeLight(this);
  15580. _super.prototype.dispose.call(this);
  15581. };
  15582. /**
  15583. * Returns the light type ID (integer).
  15584. */
  15585. Light.prototype.getTypeID = function () {
  15586. return 0;
  15587. };
  15588. /**
  15589. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15590. */
  15591. Light.prototype.getScaledIntensity = function () {
  15592. return this._photometricScale * this.intensity;
  15593. };
  15594. /**
  15595. * Returns a new Light object, named "name", from the current one.
  15596. */
  15597. Light.prototype.clone = function (name) {
  15598. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15599. if (!constructor) {
  15600. return null;
  15601. }
  15602. return BABYLON.SerializationHelper.Clone(constructor, this);
  15603. };
  15604. /**
  15605. * Serializes the current light into a Serialization object.
  15606. * Returns the serialized object.
  15607. */
  15608. Light.prototype.serialize = function () {
  15609. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15610. // Type
  15611. serializationObject.type = this.getTypeID();
  15612. // Parent
  15613. if (this.parent) {
  15614. serializationObject.parentId = this.parent.id;
  15615. }
  15616. // Inclusion / exclusions
  15617. if (this.excludedMeshes.length > 0) {
  15618. serializationObject.excludedMeshesIds = [];
  15619. this.excludedMeshes.forEach(function (mesh) {
  15620. serializationObject.excludedMeshesIds.push(mesh.id);
  15621. });
  15622. }
  15623. if (this.includedOnlyMeshes.length > 0) {
  15624. serializationObject.includedOnlyMeshesIds = [];
  15625. this.includedOnlyMeshes.forEach(function (mesh) {
  15626. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15627. });
  15628. }
  15629. // Animations
  15630. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15631. serializationObject.ranges = this.serializeAnimationRanges();
  15632. return serializationObject;
  15633. };
  15634. /**
  15635. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15636. * This new light is named "name" and added to the passed scene.
  15637. */
  15638. Light.GetConstructorFromName = function (type, name, scene) {
  15639. switch (type) {
  15640. case 0:
  15641. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15642. case 1:
  15643. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15644. case 2:
  15645. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15646. case 3:
  15647. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15648. }
  15649. return null;
  15650. };
  15651. /**
  15652. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15653. */
  15654. Light.Parse = function (parsedLight, scene) {
  15655. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15656. if (!constructor) {
  15657. return null;
  15658. }
  15659. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15660. // Inclusion / exclusions
  15661. if (parsedLight.excludedMeshesIds) {
  15662. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15663. }
  15664. if (parsedLight.includedOnlyMeshesIds) {
  15665. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15666. }
  15667. // Parent
  15668. if (parsedLight.parentId) {
  15669. light._waitingParentId = parsedLight.parentId;
  15670. }
  15671. // Animations
  15672. if (parsedLight.animations) {
  15673. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15674. var parsedAnimation = parsedLight.animations[animationIndex];
  15675. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15676. }
  15677. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15678. }
  15679. if (parsedLight.autoAnimate) {
  15680. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15681. }
  15682. return light;
  15683. };
  15684. Light.prototype._hookArrayForExcluded = function (array) {
  15685. var _this = this;
  15686. var oldPush = array.push;
  15687. array.push = function () {
  15688. var items = [];
  15689. for (var _i = 0; _i < arguments.length; _i++) {
  15690. items[_i] = arguments[_i];
  15691. }
  15692. var result = oldPush.apply(array, items);
  15693. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15694. var item = items_1[_a];
  15695. item._resyncLighSource(_this);
  15696. }
  15697. return result;
  15698. };
  15699. var oldSplice = array.splice;
  15700. array.splice = function (index, deleteCount) {
  15701. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15702. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15703. var item = deleted_1[_i];
  15704. item._resyncLighSource(_this);
  15705. }
  15706. return deleted;
  15707. };
  15708. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15709. var item = array_1[_i];
  15710. item._resyncLighSource(this);
  15711. }
  15712. };
  15713. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15714. var _this = this;
  15715. var oldPush = array.push;
  15716. array.push = function () {
  15717. var items = [];
  15718. for (var _i = 0; _i < arguments.length; _i++) {
  15719. items[_i] = arguments[_i];
  15720. }
  15721. var result = oldPush.apply(array, items);
  15722. _this._resyncMeshes();
  15723. return result;
  15724. };
  15725. var oldSplice = array.splice;
  15726. array.splice = function (index, deleteCount) {
  15727. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15728. _this._resyncMeshes();
  15729. return deleted;
  15730. };
  15731. this._resyncMeshes();
  15732. };
  15733. Light.prototype._resyncMeshes = function () {
  15734. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15735. var mesh = _a[_i];
  15736. mesh._resyncLighSource(this);
  15737. }
  15738. };
  15739. Light.prototype._markMeshesAsLightDirty = function () {
  15740. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15741. var mesh = _a[_i];
  15742. if (mesh._lightSources.indexOf(this) !== -1) {
  15743. mesh._markSubMeshesAsLightDirty();
  15744. }
  15745. }
  15746. };
  15747. /**
  15748. * Recomputes the cached photometric scale if needed.
  15749. */
  15750. Light.prototype._computePhotometricScale = function () {
  15751. this._photometricScale = this._getPhotometricScale();
  15752. this.getScene().resetCachedMaterial();
  15753. };
  15754. /**
  15755. * Returns the Photometric Scale according to the light type and intensity mode.
  15756. */
  15757. Light.prototype._getPhotometricScale = function () {
  15758. var photometricScale = 0.0;
  15759. var lightTypeID = this.getTypeID();
  15760. //get photometric mode
  15761. var photometricMode = this.intensityMode;
  15762. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15763. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15764. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15765. }
  15766. else {
  15767. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15768. }
  15769. }
  15770. //compute photometric scale
  15771. switch (lightTypeID) {
  15772. case Light.LIGHTTYPEID_POINTLIGHT:
  15773. case Light.LIGHTTYPEID_SPOTLIGHT:
  15774. switch (photometricMode) {
  15775. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15776. photometricScale = 1.0 / (4.0 * Math.PI);
  15777. break;
  15778. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15779. photometricScale = 1.0;
  15780. break;
  15781. case Light.INTENSITYMODE_LUMINANCE:
  15782. photometricScale = this.radius * this.radius;
  15783. break;
  15784. }
  15785. break;
  15786. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15787. switch (photometricMode) {
  15788. case Light.INTENSITYMODE_ILLUMINANCE:
  15789. photometricScale = 1.0;
  15790. break;
  15791. case Light.INTENSITYMODE_LUMINANCE:
  15792. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15793. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15794. var apexAngleRadians = this.radius;
  15795. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15796. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15797. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15798. photometricScale = solidAngle;
  15799. break;
  15800. }
  15801. break;
  15802. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15803. // No fall off in hemisperic light.
  15804. photometricScale = 1.0;
  15805. break;
  15806. }
  15807. return photometricScale;
  15808. };
  15809. Light.prototype._reorderLightsInScene = function () {
  15810. var scene = this.getScene();
  15811. if (this._renderPriority != 0) {
  15812. scene.requireLightSorting = true;
  15813. }
  15814. this.getScene().sortLightsByPriority();
  15815. };
  15816. //lightmapMode Consts
  15817. Light._LIGHTMAP_DEFAULT = 0;
  15818. Light._LIGHTMAP_SPECULAR = 1;
  15819. Light._LIGHTMAP_SHADOWSONLY = 2;
  15820. // Intensity Mode Consts
  15821. Light._INTENSITYMODE_AUTOMATIC = 0;
  15822. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15823. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15824. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15825. Light._INTENSITYMODE_LUMINANCE = 4;
  15826. // Light types ids const.
  15827. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15828. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15829. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15830. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15831. __decorate([
  15832. BABYLON.serializeAsColor3()
  15833. ], Light.prototype, "diffuse", void 0);
  15834. __decorate([
  15835. BABYLON.serializeAsColor3()
  15836. ], Light.prototype, "specular", void 0);
  15837. __decorate([
  15838. BABYLON.serialize()
  15839. ], Light.prototype, "intensity", void 0);
  15840. __decorate([
  15841. BABYLON.serialize()
  15842. ], Light.prototype, "range", void 0);
  15843. __decorate([
  15844. BABYLON.serialize()
  15845. ], Light.prototype, "intensityMode", null);
  15846. __decorate([
  15847. BABYLON.serialize()
  15848. ], Light.prototype, "radius", null);
  15849. __decorate([
  15850. BABYLON.serialize()
  15851. ], Light.prototype, "_renderPriority", void 0);
  15852. __decorate([
  15853. BABYLON.expandToProperty("_reorderLightsInScene")
  15854. ], Light.prototype, "renderPriority", void 0);
  15855. __decorate([
  15856. BABYLON.serialize()
  15857. ], Light.prototype, "shadowEnabled", void 0);
  15858. __decorate([
  15859. BABYLON.serialize("excludeWithLayerMask")
  15860. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15861. __decorate([
  15862. BABYLON.serialize("includeOnlyWithLayerMask")
  15863. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15864. __decorate([
  15865. BABYLON.serialize("lightmapMode")
  15866. ], Light.prototype, "_lightmapMode", void 0);
  15867. return Light;
  15868. }(BABYLON.Node));
  15869. BABYLON.Light = Light;
  15870. })(BABYLON || (BABYLON = {}));
  15871. //# sourceMappingURL=babylon.light.js.map
  15872. var BABYLON;
  15873. (function (BABYLON) {
  15874. var Camera = /** @class */ (function (_super) {
  15875. __extends(Camera, _super);
  15876. function Camera(name, position, scene) {
  15877. var _this = _super.call(this, name, scene) || this;
  15878. _this.upVector = BABYLON.Vector3.Up();
  15879. _this.orthoLeft = null;
  15880. _this.orthoRight = null;
  15881. _this.orthoBottom = null;
  15882. _this.orthoTop = null;
  15883. _this.fov = 0.8;
  15884. _this.minZ = 1;
  15885. _this.maxZ = 10000.0;
  15886. _this.inertia = 0.9;
  15887. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15888. _this.isIntermediate = false;
  15889. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15890. _this.layerMask = 0x0FFFFFFF;
  15891. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15892. // Camera rig members
  15893. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15894. _this._rigCameras = new Array();
  15895. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15896. _this._skipRendering = false;
  15897. _this.customRenderTargets = new Array();
  15898. // Observables
  15899. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15900. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15901. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15902. _this.onRestoreStateObservable = new BABYLON.Observable();
  15903. // Cache
  15904. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15905. _this._projectionMatrix = new BABYLON.Matrix();
  15906. _this._doNotComputeProjectionMatrix = false;
  15907. _this._postProcesses = new Array();
  15908. _this._transformMatrix = BABYLON.Matrix.Zero();
  15909. _this._activeMeshes = new BABYLON.SmartArray(256);
  15910. _this._globalPosition = BABYLON.Vector3.Zero();
  15911. _this._refreshFrustumPlanes = true;
  15912. _this.getScene().addCamera(_this);
  15913. if (!_this.getScene().activeCamera) {
  15914. _this.getScene().activeCamera = _this;
  15915. }
  15916. _this.position = position;
  15917. return _this;
  15918. }
  15919. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15920. get: function () {
  15921. return Camera._PERSPECTIVE_CAMERA;
  15922. },
  15923. enumerable: true,
  15924. configurable: true
  15925. });
  15926. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15927. get: function () {
  15928. return Camera._ORTHOGRAPHIC_CAMERA;
  15929. },
  15930. enumerable: true,
  15931. configurable: true
  15932. });
  15933. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15934. get: function () {
  15935. return Camera._FOVMODE_VERTICAL_FIXED;
  15936. },
  15937. enumerable: true,
  15938. configurable: true
  15939. });
  15940. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15941. get: function () {
  15942. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15943. },
  15944. enumerable: true,
  15945. configurable: true
  15946. });
  15947. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15948. get: function () {
  15949. return Camera._RIG_MODE_NONE;
  15950. },
  15951. enumerable: true,
  15952. configurable: true
  15953. });
  15954. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15955. get: function () {
  15956. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15957. },
  15958. enumerable: true,
  15959. configurable: true
  15960. });
  15961. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15962. get: function () {
  15963. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15964. },
  15965. enumerable: true,
  15966. configurable: true
  15967. });
  15968. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15969. get: function () {
  15970. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15971. },
  15972. enumerable: true,
  15973. configurable: true
  15974. });
  15975. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15976. get: function () {
  15977. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15978. },
  15979. enumerable: true,
  15980. configurable: true
  15981. });
  15982. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15983. get: function () {
  15984. return Camera._RIG_MODE_VR;
  15985. },
  15986. enumerable: true,
  15987. configurable: true
  15988. });
  15989. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15990. get: function () {
  15991. return Camera._RIG_MODE_WEBVR;
  15992. },
  15993. enumerable: true,
  15994. configurable: true
  15995. });
  15996. /**
  15997. * Store current camera state (fov, position, etc..)
  15998. */
  15999. Camera.prototype.storeState = function () {
  16000. this._stateStored = true;
  16001. this._storedFov = this.fov;
  16002. return this;
  16003. };
  16004. /**
  16005. * Restores the camera state values if it has been stored. You must call storeState() first
  16006. */
  16007. Camera.prototype._restoreStateValues = function () {
  16008. if (!this._stateStored) {
  16009. return false;
  16010. }
  16011. this.fov = this._storedFov;
  16012. return true;
  16013. };
  16014. /**
  16015. * Restored camera state. You must call storeState() first
  16016. */
  16017. Camera.prototype.restoreState = function () {
  16018. if (this._restoreStateValues()) {
  16019. this.onRestoreStateObservable.notifyObservers(this);
  16020. return true;
  16021. }
  16022. return false;
  16023. };
  16024. Camera.prototype.getClassName = function () {
  16025. return "Camera";
  16026. };
  16027. /**
  16028. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16029. */
  16030. Camera.prototype.toString = function (fullDetails) {
  16031. var ret = "Name: " + this.name;
  16032. ret += ", type: " + this.getClassName();
  16033. if (this.animations) {
  16034. for (var i = 0; i < this.animations.length; i++) {
  16035. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16036. }
  16037. }
  16038. if (fullDetails) {
  16039. }
  16040. return ret;
  16041. };
  16042. Object.defineProperty(Camera.prototype, "globalPosition", {
  16043. get: function () {
  16044. return this._globalPosition;
  16045. },
  16046. enumerable: true,
  16047. configurable: true
  16048. });
  16049. Camera.prototype.getActiveMeshes = function () {
  16050. return this._activeMeshes;
  16051. };
  16052. Camera.prototype.isActiveMesh = function (mesh) {
  16053. return (this._activeMeshes.indexOf(mesh) !== -1);
  16054. };
  16055. //Cache
  16056. Camera.prototype._initCache = function () {
  16057. _super.prototype._initCache.call(this);
  16058. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16059. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16060. this._cache.mode = undefined;
  16061. this._cache.minZ = undefined;
  16062. this._cache.maxZ = undefined;
  16063. this._cache.fov = undefined;
  16064. this._cache.fovMode = undefined;
  16065. this._cache.aspectRatio = undefined;
  16066. this._cache.orthoLeft = undefined;
  16067. this._cache.orthoRight = undefined;
  16068. this._cache.orthoBottom = undefined;
  16069. this._cache.orthoTop = undefined;
  16070. this._cache.renderWidth = undefined;
  16071. this._cache.renderHeight = undefined;
  16072. };
  16073. Camera.prototype._updateCache = function (ignoreParentClass) {
  16074. if (!ignoreParentClass) {
  16075. _super.prototype._updateCache.call(this);
  16076. }
  16077. this._cache.position.copyFrom(this.position);
  16078. this._cache.upVector.copyFrom(this.upVector);
  16079. };
  16080. // Synchronized
  16081. Camera.prototype._isSynchronized = function () {
  16082. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16083. };
  16084. Camera.prototype._isSynchronizedViewMatrix = function () {
  16085. if (!_super.prototype._isSynchronized.call(this))
  16086. return false;
  16087. return this._cache.position.equals(this.position)
  16088. && this._cache.upVector.equals(this.upVector)
  16089. && this.isSynchronizedWithParent();
  16090. };
  16091. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16092. var check = this._cache.mode === this.mode
  16093. && this._cache.minZ === this.minZ
  16094. && this._cache.maxZ === this.maxZ;
  16095. if (!check) {
  16096. return false;
  16097. }
  16098. var engine = this.getEngine();
  16099. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16100. check = this._cache.fov === this.fov
  16101. && this._cache.fovMode === this.fovMode
  16102. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16103. }
  16104. else {
  16105. check = this._cache.orthoLeft === this.orthoLeft
  16106. && this._cache.orthoRight === this.orthoRight
  16107. && this._cache.orthoBottom === this.orthoBottom
  16108. && this._cache.orthoTop === this.orthoTop
  16109. && this._cache.renderWidth === engine.getRenderWidth()
  16110. && this._cache.renderHeight === engine.getRenderHeight();
  16111. }
  16112. return check;
  16113. };
  16114. // Controls
  16115. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16116. };
  16117. Camera.prototype.detachControl = function (element) {
  16118. };
  16119. Camera.prototype.update = function () {
  16120. this._checkInputs();
  16121. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16122. this._updateRigCameras();
  16123. }
  16124. };
  16125. Camera.prototype._checkInputs = function () {
  16126. this.onAfterCheckInputsObservable.notifyObservers(this);
  16127. };
  16128. Object.defineProperty(Camera.prototype, "rigCameras", {
  16129. get: function () {
  16130. return this._rigCameras;
  16131. },
  16132. enumerable: true,
  16133. configurable: true
  16134. });
  16135. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16136. get: function () {
  16137. return this._rigPostProcess;
  16138. },
  16139. enumerable: true,
  16140. configurable: true
  16141. });
  16142. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16143. // invalidate framebuffer
  16144. if (this._postProcesses.length > 0) {
  16145. this._postProcesses[0].markTextureDirty();
  16146. }
  16147. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16148. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16149. var cam = this._rigCameras[i];
  16150. var rigPostProcess = cam._rigPostProcess;
  16151. // for VR rig, there does not have to be a post process
  16152. if (rigPostProcess) {
  16153. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16154. if (isPass) {
  16155. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16156. cam.isIntermediate = this._postProcesses.length === 0;
  16157. }
  16158. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16159. rigPostProcess.markTextureDirty();
  16160. }
  16161. else {
  16162. cam._postProcesses = this._postProcesses.slice(0);
  16163. }
  16164. }
  16165. };
  16166. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16167. if (insertAt === void 0) { insertAt = null; }
  16168. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16169. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16170. return 0;
  16171. }
  16172. if (insertAt == null || insertAt < 0) {
  16173. this._postProcesses.push(postProcess);
  16174. }
  16175. else {
  16176. this._postProcesses.splice(insertAt, 0, postProcess);
  16177. }
  16178. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16179. return this._postProcesses.indexOf(postProcess);
  16180. };
  16181. Camera.prototype.detachPostProcess = function (postProcess) {
  16182. var idx = this._postProcesses.indexOf(postProcess);
  16183. if (idx !== -1) {
  16184. this._postProcesses.splice(idx, 1);
  16185. }
  16186. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16187. };
  16188. Camera.prototype.getWorldMatrix = function () {
  16189. if (!this._worldMatrix) {
  16190. this._worldMatrix = BABYLON.Matrix.Identity();
  16191. }
  16192. var viewMatrix = this.getViewMatrix();
  16193. viewMatrix.invertToRef(this._worldMatrix);
  16194. return this._worldMatrix;
  16195. };
  16196. Camera.prototype._getViewMatrix = function () {
  16197. return BABYLON.Matrix.Identity();
  16198. };
  16199. Camera.prototype.getViewMatrix = function (force) {
  16200. if (!force && this._isSynchronizedViewMatrix()) {
  16201. return this._computedViewMatrix;
  16202. }
  16203. this.updateCache();
  16204. this._computedViewMatrix = this._getViewMatrix();
  16205. this._currentRenderId = this.getScene().getRenderId();
  16206. this._refreshFrustumPlanes = true;
  16207. if (!this.parent || !this.parent.getWorldMatrix) {
  16208. this._globalPosition.copyFrom(this.position);
  16209. }
  16210. else {
  16211. if (!this._worldMatrix) {
  16212. this._worldMatrix = BABYLON.Matrix.Identity();
  16213. }
  16214. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16215. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16216. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16217. this._computedViewMatrix.invert();
  16218. this._markSyncedWithParent();
  16219. }
  16220. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16221. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16222. }
  16223. this.onViewMatrixChangedObservable.notifyObservers(this);
  16224. return this._computedViewMatrix;
  16225. };
  16226. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16227. this._doNotComputeProjectionMatrix = true;
  16228. if (projection !== undefined) {
  16229. this._projectionMatrix = projection;
  16230. }
  16231. };
  16232. ;
  16233. Camera.prototype.unfreezeProjectionMatrix = function () {
  16234. this._doNotComputeProjectionMatrix = false;
  16235. };
  16236. ;
  16237. Camera.prototype.getProjectionMatrix = function (force) {
  16238. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16239. return this._projectionMatrix;
  16240. }
  16241. // Cache
  16242. this._cache.mode = this.mode;
  16243. this._cache.minZ = this.minZ;
  16244. this._cache.maxZ = this.maxZ;
  16245. // Matrix
  16246. this._refreshFrustumPlanes = true;
  16247. var engine = this.getEngine();
  16248. var scene = this.getScene();
  16249. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16250. this._cache.fov = this.fov;
  16251. this._cache.fovMode = this.fovMode;
  16252. this._cache.aspectRatio = engine.getAspectRatio(this);
  16253. if (this.minZ <= 0) {
  16254. this.minZ = 0.1;
  16255. }
  16256. if (scene.useRightHandedSystem) {
  16257. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16258. }
  16259. else {
  16260. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16261. }
  16262. }
  16263. else {
  16264. var halfWidth = engine.getRenderWidth() / 2.0;
  16265. var halfHeight = engine.getRenderHeight() / 2.0;
  16266. if (scene.useRightHandedSystem) {
  16267. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16268. }
  16269. else {
  16270. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16271. }
  16272. this._cache.orthoLeft = this.orthoLeft;
  16273. this._cache.orthoRight = this.orthoRight;
  16274. this._cache.orthoBottom = this.orthoBottom;
  16275. this._cache.orthoTop = this.orthoTop;
  16276. this._cache.renderWidth = engine.getRenderWidth();
  16277. this._cache.renderHeight = engine.getRenderHeight();
  16278. }
  16279. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16280. return this._projectionMatrix;
  16281. };
  16282. Camera.prototype.getTranformationMatrix = function () {
  16283. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16284. return this._transformMatrix;
  16285. };
  16286. Camera.prototype.updateFrustumPlanes = function () {
  16287. if (!this._refreshFrustumPlanes) {
  16288. return;
  16289. }
  16290. this.getTranformationMatrix();
  16291. if (!this._frustumPlanes) {
  16292. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16293. }
  16294. else {
  16295. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16296. }
  16297. this._refreshFrustumPlanes = false;
  16298. };
  16299. Camera.prototype.isInFrustum = function (target) {
  16300. this.updateFrustumPlanes();
  16301. return target.isInFrustum(this._frustumPlanes);
  16302. };
  16303. Camera.prototype.isCompletelyInFrustum = function (target) {
  16304. this.updateFrustumPlanes();
  16305. return target.isCompletelyInFrustum(this._frustumPlanes);
  16306. };
  16307. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16308. if (length === void 0) { length = 100; }
  16309. if (!transform) {
  16310. transform = this.getWorldMatrix();
  16311. }
  16312. if (!origin) {
  16313. origin = this.position;
  16314. }
  16315. var forward = new BABYLON.Vector3(0, 0, 1);
  16316. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16317. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16318. return new BABYLON.Ray(origin, direction, length);
  16319. };
  16320. Camera.prototype.dispose = function () {
  16321. // Observables
  16322. this.onViewMatrixChangedObservable.clear();
  16323. this.onProjectionMatrixChangedObservable.clear();
  16324. this.onAfterCheckInputsObservable.clear();
  16325. this.onRestoreStateObservable.clear();
  16326. // Inputs
  16327. if (this.inputs) {
  16328. this.inputs.clear();
  16329. }
  16330. // Animations
  16331. this.getScene().stopAnimation(this);
  16332. // Remove from scene
  16333. this.getScene().removeCamera(this);
  16334. while (this._rigCameras.length > 0) {
  16335. var camera = this._rigCameras.pop();
  16336. if (camera) {
  16337. camera.dispose();
  16338. }
  16339. }
  16340. // Postprocesses
  16341. if (this._rigPostProcess) {
  16342. this._rigPostProcess.dispose(this);
  16343. this._rigPostProcess = null;
  16344. this._postProcesses = [];
  16345. }
  16346. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16347. this._rigPostProcess = null;
  16348. this._postProcesses = [];
  16349. }
  16350. else {
  16351. var i = this._postProcesses.length;
  16352. while (--i >= 0) {
  16353. this._postProcesses[i].dispose(this);
  16354. }
  16355. }
  16356. // Render targets
  16357. var i = this.customRenderTargets.length;
  16358. while (--i >= 0) {
  16359. this.customRenderTargets[i].dispose();
  16360. }
  16361. this.customRenderTargets = [];
  16362. // Active Meshes
  16363. this._activeMeshes.dispose();
  16364. _super.prototype.dispose.call(this);
  16365. };
  16366. Object.defineProperty(Camera.prototype, "leftCamera", {
  16367. // ---- Camera rigs section ----
  16368. get: function () {
  16369. if (this._rigCameras.length < 1) {
  16370. return null;
  16371. }
  16372. return this._rigCameras[0];
  16373. },
  16374. enumerable: true,
  16375. configurable: true
  16376. });
  16377. Object.defineProperty(Camera.prototype, "rightCamera", {
  16378. get: function () {
  16379. if (this._rigCameras.length < 2) {
  16380. return null;
  16381. }
  16382. return this._rigCameras[1];
  16383. },
  16384. enumerable: true,
  16385. configurable: true
  16386. });
  16387. Camera.prototype.getLeftTarget = function () {
  16388. if (this._rigCameras.length < 1) {
  16389. return null;
  16390. }
  16391. return this._rigCameras[0].getTarget();
  16392. };
  16393. Camera.prototype.getRightTarget = function () {
  16394. if (this._rigCameras.length < 2) {
  16395. return null;
  16396. }
  16397. return this._rigCameras[1].getTarget();
  16398. };
  16399. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16400. if (this.cameraRigMode === mode) {
  16401. return;
  16402. }
  16403. while (this._rigCameras.length > 0) {
  16404. var camera = this._rigCameras.pop();
  16405. if (camera) {
  16406. camera.dispose();
  16407. }
  16408. }
  16409. this.cameraRigMode = mode;
  16410. this._cameraRigParams = {};
  16411. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16412. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16413. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16414. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16415. // create the rig cameras, unless none
  16416. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16417. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16418. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16419. if (leftCamera && rightCamera) {
  16420. this._rigCameras.push(leftCamera);
  16421. this._rigCameras.push(rightCamera);
  16422. }
  16423. }
  16424. switch (this.cameraRigMode) {
  16425. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16426. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16427. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16428. break;
  16429. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16430. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16431. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16432. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16433. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16434. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16435. break;
  16436. case Camera.RIG_MODE_VR:
  16437. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16438. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16439. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16440. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16441. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16442. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16443. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16444. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16445. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16446. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16447. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16448. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16449. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16450. if (metrics.compensateDistortion) {
  16451. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16452. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16453. }
  16454. break;
  16455. case Camera.RIG_MODE_WEBVR:
  16456. if (rigParams.vrDisplay) {
  16457. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16458. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16459. //Left eye
  16460. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16461. this._rigCameras[0].setCameraRigParameter("left", true);
  16462. //leaving this for future reference
  16463. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16464. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16465. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16466. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16467. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16468. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16469. this._rigCameras[0].parent = this;
  16470. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16471. //Right eye
  16472. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16473. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16474. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16475. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16476. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16477. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16478. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16479. this._rigCameras[1].parent = this;
  16480. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16481. if (Camera.UseAlternateWebVRRendering) {
  16482. this._rigCameras[1]._skipRendering = true;
  16483. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16484. }
  16485. }
  16486. break;
  16487. }
  16488. this._cascadePostProcessesToRigCams();
  16489. this.update();
  16490. };
  16491. Camera.prototype._getVRProjectionMatrix = function () {
  16492. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16493. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16494. return this._projectionMatrix;
  16495. };
  16496. Camera.prototype._updateCameraRotationMatrix = function () {
  16497. //Here for WebVR
  16498. };
  16499. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16500. //Here for WebVR
  16501. };
  16502. /**
  16503. * This function MUST be overwritten by the different WebVR cameras available.
  16504. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16505. */
  16506. Camera.prototype._getWebVRProjectionMatrix = function () {
  16507. return BABYLON.Matrix.Identity();
  16508. };
  16509. /**
  16510. * This function MUST be overwritten by the different WebVR cameras available.
  16511. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16512. */
  16513. Camera.prototype._getWebVRViewMatrix = function () {
  16514. return BABYLON.Matrix.Identity();
  16515. };
  16516. Camera.prototype.setCameraRigParameter = function (name, value) {
  16517. if (!this._cameraRigParams) {
  16518. this._cameraRigParams = {};
  16519. }
  16520. this._cameraRigParams[name] = value;
  16521. //provisionnally:
  16522. if (name === "interaxialDistance") {
  16523. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16524. }
  16525. };
  16526. /**
  16527. * needs to be overridden by children so sub has required properties to be copied
  16528. */
  16529. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16530. return null;
  16531. };
  16532. /**
  16533. * May need to be overridden by children
  16534. */
  16535. Camera.prototype._updateRigCameras = function () {
  16536. for (var i = 0; i < this._rigCameras.length; i++) {
  16537. this._rigCameras[i].minZ = this.minZ;
  16538. this._rigCameras[i].maxZ = this.maxZ;
  16539. this._rigCameras[i].fov = this.fov;
  16540. }
  16541. // only update viewport when ANAGLYPH
  16542. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16543. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16544. }
  16545. };
  16546. Camera.prototype._setupInputs = function () {
  16547. };
  16548. Camera.prototype.serialize = function () {
  16549. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16550. // Type
  16551. serializationObject.type = this.getClassName();
  16552. // Parent
  16553. if (this.parent) {
  16554. serializationObject.parentId = this.parent.id;
  16555. }
  16556. if (this.inputs) {
  16557. this.inputs.serialize(serializationObject);
  16558. }
  16559. // Animations
  16560. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16561. serializationObject.ranges = this.serializeAnimationRanges();
  16562. return serializationObject;
  16563. };
  16564. Camera.prototype.clone = function (name) {
  16565. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16566. };
  16567. Camera.prototype.getDirection = function (localAxis) {
  16568. var result = BABYLON.Vector3.Zero();
  16569. this.getDirectionToRef(localAxis, result);
  16570. return result;
  16571. };
  16572. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16573. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16574. };
  16575. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16576. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16577. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16578. switch (type) {
  16579. case "ArcRotateCamera":
  16580. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16581. case "DeviceOrientationCamera":
  16582. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16583. case "FollowCamera":
  16584. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16585. case "ArcFollowCamera":
  16586. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16587. case "GamepadCamera":
  16588. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16589. case "TouchCamera":
  16590. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16591. case "VirtualJoysticksCamera":
  16592. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16593. case "WebVRFreeCamera":
  16594. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16595. case "WebVRGamepadCamera":
  16596. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16597. case "VRDeviceOrientationFreeCamera":
  16598. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16599. case "VRDeviceOrientationGamepadCamera":
  16600. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16601. case "AnaglyphArcRotateCamera":
  16602. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16603. case "AnaglyphFreeCamera":
  16604. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16605. case "AnaglyphGamepadCamera":
  16606. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16607. case "AnaglyphUniversalCamera":
  16608. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16609. case "StereoscopicArcRotateCamera":
  16610. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16611. case "StereoscopicFreeCamera":
  16612. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16613. case "StereoscopicGamepadCamera":
  16614. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16615. case "StereoscopicUniversalCamera":
  16616. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16617. case "FreeCamera":// Forcing Universal here
  16618. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16619. default:// Universal Camera is the default value
  16620. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16621. }
  16622. };
  16623. Camera.Parse = function (parsedCamera, scene) {
  16624. var type = parsedCamera.type;
  16625. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16626. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16627. // Parent
  16628. if (parsedCamera.parentId) {
  16629. camera._waitingParentId = parsedCamera.parentId;
  16630. }
  16631. //If camera has an input manager, let it parse inputs settings
  16632. if (camera.inputs) {
  16633. camera.inputs.parse(parsedCamera);
  16634. camera._setupInputs();
  16635. }
  16636. if (camera.setPosition) {
  16637. camera.position.copyFromFloats(0, 0, 0);
  16638. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16639. }
  16640. // Target
  16641. if (parsedCamera.target) {
  16642. if (camera.setTarget) {
  16643. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16644. }
  16645. }
  16646. // Apply 3d rig, when found
  16647. if (parsedCamera.cameraRigMode) {
  16648. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16649. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16650. }
  16651. // Animations
  16652. if (parsedCamera.animations) {
  16653. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16654. var parsedAnimation = parsedCamera.animations[animationIndex];
  16655. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16656. }
  16657. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16658. }
  16659. if (parsedCamera.autoAnimate) {
  16660. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16661. }
  16662. return camera;
  16663. };
  16664. // Statics
  16665. Camera._PERSPECTIVE_CAMERA = 0;
  16666. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16667. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16668. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16669. Camera._RIG_MODE_NONE = 0;
  16670. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16671. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16672. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16673. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16674. Camera._RIG_MODE_VR = 20;
  16675. Camera._RIG_MODE_WEBVR = 21;
  16676. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16677. Camera.UseAlternateWebVRRendering = false;
  16678. __decorate([
  16679. BABYLON.serializeAsVector3()
  16680. ], Camera.prototype, "position", void 0);
  16681. __decorate([
  16682. BABYLON.serializeAsVector3()
  16683. ], Camera.prototype, "upVector", void 0);
  16684. __decorate([
  16685. BABYLON.serialize()
  16686. ], Camera.prototype, "orthoLeft", void 0);
  16687. __decorate([
  16688. BABYLON.serialize()
  16689. ], Camera.prototype, "orthoRight", void 0);
  16690. __decorate([
  16691. BABYLON.serialize()
  16692. ], Camera.prototype, "orthoBottom", void 0);
  16693. __decorate([
  16694. BABYLON.serialize()
  16695. ], Camera.prototype, "orthoTop", void 0);
  16696. __decorate([
  16697. BABYLON.serialize()
  16698. ], Camera.prototype, "fov", void 0);
  16699. __decorate([
  16700. BABYLON.serialize()
  16701. ], Camera.prototype, "minZ", void 0);
  16702. __decorate([
  16703. BABYLON.serialize()
  16704. ], Camera.prototype, "maxZ", void 0);
  16705. __decorate([
  16706. BABYLON.serialize()
  16707. ], Camera.prototype, "inertia", void 0);
  16708. __decorate([
  16709. BABYLON.serialize()
  16710. ], Camera.prototype, "mode", void 0);
  16711. __decorate([
  16712. BABYLON.serialize()
  16713. ], Camera.prototype, "layerMask", void 0);
  16714. __decorate([
  16715. BABYLON.serialize()
  16716. ], Camera.prototype, "fovMode", void 0);
  16717. __decorate([
  16718. BABYLON.serialize()
  16719. ], Camera.prototype, "cameraRigMode", void 0);
  16720. __decorate([
  16721. BABYLON.serialize()
  16722. ], Camera.prototype, "interaxialDistance", void 0);
  16723. __decorate([
  16724. BABYLON.serialize()
  16725. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16726. return Camera;
  16727. }(BABYLON.Node));
  16728. BABYLON.Camera = Camera;
  16729. })(BABYLON || (BABYLON = {}));
  16730. //# sourceMappingURL=babylon.camera.js.map
  16731. var BABYLON;
  16732. (function (BABYLON) {
  16733. var RenderingManager = /** @class */ (function () {
  16734. function RenderingManager(scene) {
  16735. this._renderingGroups = new Array();
  16736. this._autoClearDepthStencil = {};
  16737. this._customOpaqueSortCompareFn = {};
  16738. this._customAlphaTestSortCompareFn = {};
  16739. this._customTransparentSortCompareFn = {};
  16740. this._renderinGroupInfo = null;
  16741. this._scene = scene;
  16742. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16743. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16744. }
  16745. }
  16746. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16747. if (depth === void 0) { depth = true; }
  16748. if (stencil === void 0) { stencil = true; }
  16749. if (this._depthStencilBufferAlreadyCleaned) {
  16750. return;
  16751. }
  16752. this._scene.getEngine().clear(null, false, depth, stencil);
  16753. this._depthStencilBufferAlreadyCleaned = true;
  16754. };
  16755. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16756. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16757. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16758. var info = null;
  16759. if (observable) {
  16760. if (!this._renderinGroupInfo) {
  16761. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16762. }
  16763. info = this._renderinGroupInfo;
  16764. info.scene = this._scene;
  16765. info.camera = this._scene.activeCamera;
  16766. }
  16767. // Dispatch sprites
  16768. if (renderSprites) {
  16769. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16770. var manager = this._scene.spriteManagers[index];
  16771. this.dispatchSprites(manager);
  16772. }
  16773. }
  16774. // Render
  16775. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16776. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16777. var renderingGroup = this._renderingGroups[index];
  16778. if (!renderingGroup && !observable)
  16779. continue;
  16780. this._currentIndex = index;
  16781. var renderingGroupMask = 0;
  16782. // Fire PRECLEAR stage
  16783. if (observable && info) {
  16784. renderingGroupMask = Math.pow(2, index);
  16785. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16786. info.renderingGroupId = index;
  16787. observable.notifyObservers(info, renderingGroupMask);
  16788. }
  16789. // Clear depth/stencil if needed
  16790. if (RenderingManager.AUTOCLEAR) {
  16791. var autoClear = this._autoClearDepthStencil[index];
  16792. if (autoClear && autoClear.autoClear) {
  16793. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16794. }
  16795. }
  16796. if (observable && info) {
  16797. // Fire PREOPAQUE stage
  16798. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16799. observable.notifyObservers(info, renderingGroupMask);
  16800. // Fire PRETRANSPARENT stage
  16801. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16802. observable.notifyObservers(info, renderingGroupMask);
  16803. }
  16804. if (renderingGroup)
  16805. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16806. // Fire POSTTRANSPARENT stage
  16807. if (observable && info) {
  16808. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16809. observable.notifyObservers(info, renderingGroupMask);
  16810. }
  16811. }
  16812. };
  16813. RenderingManager.prototype.reset = function () {
  16814. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16815. var renderingGroup = this._renderingGroups[index];
  16816. if (renderingGroup) {
  16817. renderingGroup.prepare();
  16818. }
  16819. }
  16820. };
  16821. RenderingManager.prototype.dispose = function () {
  16822. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16823. var renderingGroup = this._renderingGroups[index];
  16824. if (renderingGroup) {
  16825. renderingGroup.dispose();
  16826. }
  16827. }
  16828. this._renderingGroups.length = 0;
  16829. };
  16830. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16831. if (!this._renderingGroups[renderingGroupId]) {
  16832. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16833. }
  16834. };
  16835. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16836. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16837. this._prepareRenderingGroup(renderingGroupId);
  16838. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16839. };
  16840. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16841. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16842. this._prepareRenderingGroup(renderingGroupId);
  16843. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16844. };
  16845. RenderingManager.prototype.dispatch = function (subMesh) {
  16846. var mesh = subMesh.getMesh();
  16847. var renderingGroupId = mesh.renderingGroupId || 0;
  16848. this._prepareRenderingGroup(renderingGroupId);
  16849. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16850. };
  16851. /**
  16852. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16853. * This allowed control for front to back rendering or reversly depending of the special needs.
  16854. *
  16855. * @param renderingGroupId The rendering group id corresponding to its index
  16856. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16857. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16858. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16859. */
  16860. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16861. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16862. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16863. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16864. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16865. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16866. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16867. if (this._renderingGroups[renderingGroupId]) {
  16868. var group = this._renderingGroups[renderingGroupId];
  16869. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16870. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16871. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16872. }
  16873. };
  16874. /**
  16875. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16876. *
  16877. * @param renderingGroupId The rendering group id corresponding to its index
  16878. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16879. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16880. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16881. */
  16882. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16883. if (depth === void 0) { depth = true; }
  16884. if (stencil === void 0) { stencil = true; }
  16885. this._autoClearDepthStencil[renderingGroupId] = {
  16886. autoClear: autoClearDepthStencil,
  16887. depth: depth,
  16888. stencil: stencil
  16889. };
  16890. };
  16891. /**
  16892. * The max id used for rendering groups (not included)
  16893. */
  16894. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16895. /**
  16896. * The min id used for rendering groups (included)
  16897. */
  16898. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16899. /**
  16900. * Used to globally prevent autoclearing scenes.
  16901. */
  16902. RenderingManager.AUTOCLEAR = true;
  16903. return RenderingManager;
  16904. }());
  16905. BABYLON.RenderingManager = RenderingManager;
  16906. })(BABYLON || (BABYLON = {}));
  16907. //# sourceMappingURL=babylon.renderingManager.js.map
  16908. var BABYLON;
  16909. (function (BABYLON) {
  16910. var RenderingGroup = /** @class */ (function () {
  16911. /**
  16912. * Creates a new rendering group.
  16913. * @param index The rendering group index
  16914. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16915. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16916. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16917. */
  16918. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16919. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16920. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16921. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16922. this.index = index;
  16923. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16924. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16925. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16926. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16927. this._particleSystems = new BABYLON.SmartArray(256);
  16928. this._spriteManagers = new BABYLON.SmartArray(256);
  16929. this._edgesRenderers = new BABYLON.SmartArray(16);
  16930. this._scene = scene;
  16931. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16932. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16933. this.transparentSortCompareFn = transparentSortCompareFn;
  16934. }
  16935. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16936. /**
  16937. * Set the opaque sort comparison function.
  16938. * If null the sub meshes will be render in the order they were created
  16939. */
  16940. set: function (value) {
  16941. this._opaqueSortCompareFn = value;
  16942. if (value) {
  16943. this._renderOpaque = this.renderOpaqueSorted;
  16944. }
  16945. else {
  16946. this._renderOpaque = RenderingGroup.renderUnsorted;
  16947. }
  16948. },
  16949. enumerable: true,
  16950. configurable: true
  16951. });
  16952. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16953. /**
  16954. * Set the alpha test sort comparison function.
  16955. * If null the sub meshes will be render in the order they were created
  16956. */
  16957. set: function (value) {
  16958. this._alphaTestSortCompareFn = value;
  16959. if (value) {
  16960. this._renderAlphaTest = this.renderAlphaTestSorted;
  16961. }
  16962. else {
  16963. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16964. }
  16965. },
  16966. enumerable: true,
  16967. configurable: true
  16968. });
  16969. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16970. /**
  16971. * Set the transparent sort comparison function.
  16972. * If null the sub meshes will be render in the order they were created
  16973. */
  16974. set: function (value) {
  16975. if (value) {
  16976. this._transparentSortCompareFn = value;
  16977. }
  16978. else {
  16979. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16980. }
  16981. this._renderTransparent = this.renderTransparentSorted;
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. /**
  16987. * Render all the sub meshes contained in the group.
  16988. * @param customRenderFunction Used to override the default render behaviour of the group.
  16989. * @returns true if rendered some submeshes.
  16990. */
  16991. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16992. if (customRenderFunction) {
  16993. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16994. return;
  16995. }
  16996. var engine = this._scene.getEngine();
  16997. // Depth only
  16998. if (this._depthOnlySubMeshes.length !== 0) {
  16999. engine.setAlphaTesting(true);
  17000. engine.setColorWrite(false);
  17001. this._renderAlphaTest(this._depthOnlySubMeshes);
  17002. engine.setAlphaTesting(false);
  17003. engine.setColorWrite(true);
  17004. }
  17005. // Opaque
  17006. if (this._opaqueSubMeshes.length !== 0) {
  17007. this._renderOpaque(this._opaqueSubMeshes);
  17008. }
  17009. // Alpha test
  17010. if (this._alphaTestSubMeshes.length !== 0) {
  17011. engine.setAlphaTesting(true);
  17012. this._renderAlphaTest(this._alphaTestSubMeshes);
  17013. engine.setAlphaTesting(false);
  17014. }
  17015. var stencilState = engine.getStencilBuffer();
  17016. engine.setStencilBuffer(false);
  17017. // Sprites
  17018. if (renderSprites) {
  17019. this._renderSprites();
  17020. }
  17021. // Particles
  17022. if (renderParticles) {
  17023. this._renderParticles(activeMeshes);
  17024. }
  17025. if (this.onBeforeTransparentRendering) {
  17026. this.onBeforeTransparentRendering();
  17027. }
  17028. // Transparent
  17029. if (this._transparentSubMeshes.length !== 0) {
  17030. this._renderTransparent(this._transparentSubMeshes);
  17031. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17032. }
  17033. // Set back stencil to false in case it changes before the edge renderer.
  17034. engine.setStencilBuffer(false);
  17035. // Edges
  17036. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17037. this._edgesRenderers.data[edgesRendererIndex].render();
  17038. }
  17039. // Restore Stencil state.
  17040. engine.setStencilBuffer(stencilState);
  17041. };
  17042. /**
  17043. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17044. * @param subMeshes The submeshes to render
  17045. */
  17046. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17047. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17048. };
  17049. /**
  17050. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17051. * @param subMeshes The submeshes to render
  17052. */
  17053. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17054. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17055. };
  17056. /**
  17057. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17058. * @param subMeshes The submeshes to render
  17059. */
  17060. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17061. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17062. };
  17063. /**
  17064. * Renders the submeshes in a specified order.
  17065. * @param subMeshes The submeshes to sort before render
  17066. * @param sortCompareFn The comparison function use to sort
  17067. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17068. * @param transparent Specifies to activate blending if true
  17069. */
  17070. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17071. var subIndex = 0;
  17072. var subMesh;
  17073. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17074. for (; subIndex < subMeshes.length; subIndex++) {
  17075. subMesh = subMeshes.data[subIndex];
  17076. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17077. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17078. }
  17079. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17080. if (sortCompareFn) {
  17081. sortedArray.sort(sortCompareFn);
  17082. }
  17083. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17084. subMesh = sortedArray[subIndex];
  17085. if (transparent) {
  17086. var material = subMesh.getMaterial();
  17087. if (material && material.needDepthPrePass) {
  17088. var engine = material.getScene().getEngine();
  17089. engine.setColorWrite(false);
  17090. engine.setAlphaTesting(true);
  17091. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17092. subMesh.render(false);
  17093. engine.setAlphaTesting(false);
  17094. engine.setColorWrite(true);
  17095. }
  17096. }
  17097. subMesh.render(transparent);
  17098. }
  17099. };
  17100. /**
  17101. * Renders the submeshes in the order they were dispatched (no sort applied).
  17102. * @param subMeshes The submeshes to render
  17103. */
  17104. RenderingGroup.renderUnsorted = function (subMeshes) {
  17105. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17106. var submesh = subMeshes.data[subIndex];
  17107. submesh.render(false);
  17108. }
  17109. };
  17110. /**
  17111. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17112. * are rendered back to front if in the same alpha index.
  17113. *
  17114. * @param a The first submesh
  17115. * @param b The second submesh
  17116. * @returns The result of the comparison
  17117. */
  17118. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17119. // Alpha index first
  17120. if (a._alphaIndex > b._alphaIndex) {
  17121. return 1;
  17122. }
  17123. if (a._alphaIndex < b._alphaIndex) {
  17124. return -1;
  17125. }
  17126. // Then distance to camera
  17127. return RenderingGroup.backToFrontSortCompare(a, b);
  17128. };
  17129. /**
  17130. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17131. * are rendered back to front.
  17132. *
  17133. * @param a The first submesh
  17134. * @param b The second submesh
  17135. * @returns The result of the comparison
  17136. */
  17137. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17138. // Then distance to camera
  17139. if (a._distanceToCamera < b._distanceToCamera) {
  17140. return 1;
  17141. }
  17142. if (a._distanceToCamera > b._distanceToCamera) {
  17143. return -1;
  17144. }
  17145. return 0;
  17146. };
  17147. /**
  17148. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17149. * are rendered front to back (prevent overdraw).
  17150. *
  17151. * @param a The first submesh
  17152. * @param b The second submesh
  17153. * @returns The result of the comparison
  17154. */
  17155. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17156. // Then distance to camera
  17157. if (a._distanceToCamera < b._distanceToCamera) {
  17158. return -1;
  17159. }
  17160. if (a._distanceToCamera > b._distanceToCamera) {
  17161. return 1;
  17162. }
  17163. return 0;
  17164. };
  17165. /**
  17166. * Resets the different lists of submeshes to prepare a new frame.
  17167. */
  17168. RenderingGroup.prototype.prepare = function () {
  17169. this._opaqueSubMeshes.reset();
  17170. this._transparentSubMeshes.reset();
  17171. this._alphaTestSubMeshes.reset();
  17172. this._depthOnlySubMeshes.reset();
  17173. this._particleSystems.reset();
  17174. this._spriteManagers.reset();
  17175. this._edgesRenderers.reset();
  17176. };
  17177. RenderingGroup.prototype.dispose = function () {
  17178. this._opaqueSubMeshes.dispose();
  17179. this._transparentSubMeshes.dispose();
  17180. this._alphaTestSubMeshes.dispose();
  17181. this._depthOnlySubMeshes.dispose();
  17182. this._particleSystems.dispose();
  17183. this._spriteManagers.dispose();
  17184. this._edgesRenderers.dispose();
  17185. };
  17186. /**
  17187. * Inserts the submesh in its correct queue depending on its material.
  17188. * @param subMesh The submesh to dispatch
  17189. */
  17190. RenderingGroup.prototype.dispatch = function (subMesh) {
  17191. var material = subMesh.getMaterial();
  17192. var mesh = subMesh.getMesh();
  17193. if (!material) {
  17194. return;
  17195. }
  17196. if (material.needAlphaBlending() || material.needAlphaBlendingForMesh(mesh)) {
  17197. this._transparentSubMeshes.push(subMesh);
  17198. }
  17199. else if (material.needAlphaTesting()) {
  17200. if (material.needDepthPrePass) {
  17201. this._depthOnlySubMeshes.push(subMesh);
  17202. }
  17203. this._alphaTestSubMeshes.push(subMesh);
  17204. }
  17205. else {
  17206. if (material.needDepthPrePass) {
  17207. this._depthOnlySubMeshes.push(subMesh);
  17208. }
  17209. this._opaqueSubMeshes.push(subMesh); // Opaque
  17210. }
  17211. if (mesh._edgesRenderer) {
  17212. this._edgesRenderers.push(mesh._edgesRenderer);
  17213. }
  17214. };
  17215. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17216. this._spriteManagers.push(spriteManager);
  17217. };
  17218. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17219. this._particleSystems.push(particleSystem);
  17220. };
  17221. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17222. if (this._particleSystems.length === 0) {
  17223. return;
  17224. }
  17225. // Particles
  17226. var activeCamera = this._scene.activeCamera;
  17227. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17228. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17229. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17230. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17231. continue;
  17232. }
  17233. var emitter = particleSystem.emitter;
  17234. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17235. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17236. }
  17237. }
  17238. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17239. };
  17240. RenderingGroup.prototype._renderSprites = function () {
  17241. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17242. return;
  17243. }
  17244. // Sprites
  17245. var activeCamera = this._scene.activeCamera;
  17246. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17247. for (var id = 0; id < this._spriteManagers.length; id++) {
  17248. var spriteManager = this._spriteManagers.data[id];
  17249. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17250. spriteManager.render();
  17251. }
  17252. }
  17253. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17254. };
  17255. return RenderingGroup;
  17256. }());
  17257. BABYLON.RenderingGroup = RenderingGroup;
  17258. })(BABYLON || (BABYLON = {}));
  17259. //# sourceMappingURL=babylon.renderingGroup.js.map
  17260. var BABYLON;
  17261. (function (BABYLON) {
  17262. var ClickInfo = /** @class */ (function () {
  17263. function ClickInfo() {
  17264. this._singleClick = false;
  17265. this._doubleClick = false;
  17266. this._hasSwiped = false;
  17267. this._ignore = false;
  17268. }
  17269. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17270. get: function () {
  17271. return this._singleClick;
  17272. },
  17273. set: function (b) {
  17274. this._singleClick = b;
  17275. },
  17276. enumerable: true,
  17277. configurable: true
  17278. });
  17279. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17280. get: function () {
  17281. return this._doubleClick;
  17282. },
  17283. set: function (b) {
  17284. this._doubleClick = b;
  17285. },
  17286. enumerable: true,
  17287. configurable: true
  17288. });
  17289. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17290. get: function () {
  17291. return this._hasSwiped;
  17292. },
  17293. set: function (b) {
  17294. this._hasSwiped = b;
  17295. },
  17296. enumerable: true,
  17297. configurable: true
  17298. });
  17299. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17300. get: function () {
  17301. return this._ignore;
  17302. },
  17303. set: function (b) {
  17304. this._ignore = b;
  17305. },
  17306. enumerable: true,
  17307. configurable: true
  17308. });
  17309. return ClickInfo;
  17310. }());
  17311. /**
  17312. * This class is used by the onRenderingGroupObservable
  17313. */
  17314. var RenderingGroupInfo = /** @class */ (function () {
  17315. function RenderingGroupInfo() {
  17316. }
  17317. /**
  17318. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17319. * This stage will be fired no matter what
  17320. */
  17321. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17322. /**
  17323. * Called before opaque object are rendered.
  17324. * This stage will be fired only if there's 3D Opaque content to render
  17325. */
  17326. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17327. /**
  17328. * Called after the opaque objects are rendered and before the transparent ones
  17329. * This stage will be fired only if there's 3D transparent content to render
  17330. */
  17331. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17332. /**
  17333. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17334. * This stage will be fired no matter what
  17335. */
  17336. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17337. return RenderingGroupInfo;
  17338. }());
  17339. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17340. /**
  17341. * Represents a scene to be rendered by the engine.
  17342. * @see http://doc.babylonjs.com/page.php?p=21911
  17343. */
  17344. var Scene = /** @class */ (function () {
  17345. /**
  17346. * @constructor
  17347. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17348. */
  17349. function Scene(engine) {
  17350. // Members
  17351. this.autoClear = true;
  17352. this.autoClearDepthAndStencil = true;
  17353. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17354. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17355. this.forceWireframe = false;
  17356. this._forcePointsCloud = false;
  17357. this.forceShowBoundingBoxes = false;
  17358. this.animationsEnabled = true;
  17359. this.constantlyUpdateMeshUnderPointer = false;
  17360. this.hoverCursor = "pointer";
  17361. this.defaultCursor = "";
  17362. /**
  17363. * This is used to call preventDefault() on pointer down
  17364. * in order to block unwanted artifacts like system double clicks
  17365. */
  17366. this.preventDefaultOnPointerDown = true;
  17367. // Metadata
  17368. this.metadata = null;
  17369. /**
  17370. * An event triggered when the scene is disposed.
  17371. * @type {BABYLON.Observable}
  17372. */
  17373. this.onDisposeObservable = new BABYLON.Observable();
  17374. /**
  17375. * An event triggered before rendering the scene (right after animations and physics)
  17376. * @type {BABYLON.Observable}
  17377. */
  17378. this.onBeforeRenderObservable = new BABYLON.Observable();
  17379. /**
  17380. * An event triggered after rendering the scene
  17381. * @type {BABYLON.Observable}
  17382. */
  17383. this.onAfterRenderObservable = new BABYLON.Observable();
  17384. /**
  17385. * An event triggered before animating the scene
  17386. * @type {BABYLON.Observable}
  17387. */
  17388. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17389. /**
  17390. * An event triggered after animations processing
  17391. * @type {BABYLON.Observable}
  17392. */
  17393. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17394. /**
  17395. * An event triggered before draw calls are ready to be sent
  17396. * @type {BABYLON.Observable}
  17397. */
  17398. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17399. /**
  17400. * An event triggered after draw calls have been sent
  17401. * @type {BABYLON.Observable}
  17402. */
  17403. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17404. /**
  17405. * An event triggered when physic simulation is about to be run
  17406. * @type {BABYLON.Observable}
  17407. */
  17408. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17409. /**
  17410. * An event triggered when physic simulation has been done
  17411. * @type {BABYLON.Observable}
  17412. */
  17413. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17414. /**
  17415. * An event triggered when the scene is ready
  17416. * @type {BABYLON.Observable}
  17417. */
  17418. this.onReadyObservable = new BABYLON.Observable();
  17419. /**
  17420. * An event triggered before rendering a camera
  17421. * @type {BABYLON.Observable}
  17422. */
  17423. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17424. /**
  17425. * An event triggered after rendering a camera
  17426. * @type {BABYLON.Observable}
  17427. */
  17428. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17429. /**
  17430. * An event triggered when active meshes evaluation is about to start
  17431. * @type {BABYLON.Observable}
  17432. */
  17433. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17434. /**
  17435. * An event triggered when active meshes evaluation is done
  17436. * @type {BABYLON.Observable}
  17437. */
  17438. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17439. /**
  17440. * An event triggered when particles rendering is about to start
  17441. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17442. * @type {BABYLON.Observable}
  17443. */
  17444. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17445. /**
  17446. * An event triggered when particles rendering is done
  17447. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17448. * @type {BABYLON.Observable}
  17449. */
  17450. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17451. /**
  17452. * An event triggered when sprites rendering is about to start
  17453. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17454. * @type {BABYLON.Observable}
  17455. */
  17456. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17457. /**
  17458. * An event triggered when sprites rendering is done
  17459. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17460. * @type {BABYLON.Observable}
  17461. */
  17462. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17463. /**
  17464. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  17465. * @type {BABYLON.Observable}
  17466. */
  17467. this.onDataLoadedObservable = new BABYLON.Observable();
  17468. /**
  17469. * An event triggered when a camera is created
  17470. * @type {BABYLON.Observable}
  17471. */
  17472. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17473. /**
  17474. * An event triggered when a camera is removed
  17475. * @type {BABYLON.Observable}
  17476. */
  17477. this.onCameraRemovedObservable = new BABYLON.Observable();
  17478. /**
  17479. * An event triggered when a light is created
  17480. * @type {BABYLON.Observable}
  17481. */
  17482. this.onNewLightAddedObservable = new BABYLON.Observable();
  17483. /**
  17484. * An event triggered when a light is removed
  17485. * @type {BABYLON.Observable}
  17486. */
  17487. this.onLightRemovedObservable = new BABYLON.Observable();
  17488. /**
  17489. * An event triggered when a geometry is created
  17490. * @type {BABYLON.Observable}
  17491. */
  17492. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17493. /**
  17494. * An event triggered when a geometry is removed
  17495. * @type {BABYLON.Observable}
  17496. */
  17497. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17498. /**
  17499. * An event triggered when a mesh is created
  17500. * @type {BABYLON.Observable}
  17501. */
  17502. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17503. /**
  17504. * An event triggered when a mesh is removed
  17505. * @type {BABYLON.Observable}
  17506. */
  17507. this.onMeshRemovedObservable = new BABYLON.Observable();
  17508. /**
  17509. * An event triggered when render targets are about to be rendered
  17510. * Can happen multiple times per frame.
  17511. * @type {BABYLON.Observable}
  17512. */
  17513. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17514. /**
  17515. * An event triggered when render targets were rendered.
  17516. * Can happen multiple times per frame.
  17517. * @type {BABYLON.Observable}
  17518. */
  17519. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17520. /**
  17521. * An event triggered before calculating deterministic simulation step
  17522. * @type {BABYLON.Observable}
  17523. */
  17524. this.onBeforeStepObservable = new BABYLON.Observable();
  17525. /**
  17526. * An event triggered after calculating deterministic simulation step
  17527. * @type {BABYLON.Observable}
  17528. */
  17529. this.onAfterStepObservable = new BABYLON.Observable();
  17530. /**
  17531. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17532. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17533. * 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)
  17534. */
  17535. this.onRenderingGroupObservable = new BABYLON.Observable();
  17536. // Animations
  17537. this.animations = [];
  17538. /**
  17539. * 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).
  17540. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17541. */
  17542. this.onPrePointerObservable = new BABYLON.Observable();
  17543. /**
  17544. * Observable event triggered each time an input event is received from the rendering canvas
  17545. */
  17546. this.onPointerObservable = new BABYLON.Observable();
  17547. this._meshPickProceed = false;
  17548. this._previousHasSwiped = false;
  17549. this._currentPickResult = null;
  17550. this._previousPickResult = null;
  17551. this._totalPointersPressed = 0;
  17552. this._doubleClickOccured = false;
  17553. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17554. this.cameraToUseForPointers = null;
  17555. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17556. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17557. this._startingPointerTime = 0;
  17558. this._previousStartingPointerTime = 0;
  17559. // Deterministic lockstep
  17560. this._timeAccumulator = 0;
  17561. this._currentStepId = 0;
  17562. this._currentInternalStep = 0;
  17563. // Keyboard
  17564. /**
  17565. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17566. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17567. */
  17568. this.onPreKeyboardObservable = new BABYLON.Observable();
  17569. /**
  17570. * Observable event triggered each time an keyboard event is received from the hosting window
  17571. */
  17572. this.onKeyboardObservable = new BABYLON.Observable();
  17573. // Coordinate system
  17574. /**
  17575. * use right-handed coordinate system on this scene.
  17576. * @type {boolean}
  17577. */
  17578. this._useRightHandedSystem = false;
  17579. // Fog
  17580. this._fogEnabled = true;
  17581. this._fogMode = Scene.FOGMODE_NONE;
  17582. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17583. this.fogDensity = 0.1;
  17584. this.fogStart = 0;
  17585. this.fogEnd = 1000.0;
  17586. // Lights
  17587. /**
  17588. * is shadow enabled on this scene.
  17589. * @type {boolean}
  17590. */
  17591. this._shadowsEnabled = true;
  17592. /**
  17593. * is light enabled on this scene.
  17594. * @type {boolean}
  17595. */
  17596. this._lightsEnabled = true;
  17597. /**
  17598. * All of the lights added to this scene.
  17599. * @see BABYLON.Light
  17600. * @type {BABYLON.Light[]}
  17601. */
  17602. this.lights = new Array();
  17603. // Cameras
  17604. /** All of the cameras added to this scene. */
  17605. this.cameras = new Array();
  17606. /** All of the active cameras added to this scene. */
  17607. this.activeCameras = new Array();
  17608. // Meshes
  17609. /**
  17610. * All of the (abstract) meshes added to this scene.
  17611. * @see BABYLON.AbstractMesh
  17612. * @type {BABYLON.AbstractMesh[]}
  17613. */
  17614. this.meshes = new Array();
  17615. // Geometries
  17616. this._geometries = new Array();
  17617. this.materials = new Array();
  17618. this.multiMaterials = new Array();
  17619. // Textures
  17620. this._texturesEnabled = true;
  17621. this.textures = new Array();
  17622. // Particles
  17623. this.particlesEnabled = true;
  17624. this.particleSystems = new Array();
  17625. // Sprites
  17626. this.spritesEnabled = true;
  17627. this.spriteManagers = new Array();
  17628. // Layers
  17629. this.layers = new Array();
  17630. this.highlightLayers = new Array();
  17631. // Skeletons
  17632. this._skeletonsEnabled = true;
  17633. this.skeletons = new Array();
  17634. // Morph targets
  17635. this.morphTargetManagers = new Array();
  17636. // Lens flares
  17637. this.lensFlaresEnabled = true;
  17638. this.lensFlareSystems = new Array();
  17639. // Collisions
  17640. this.collisionsEnabled = true;
  17641. /** Defines the gravity applied to this scene */
  17642. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17643. // Postprocesses
  17644. this.postProcesses = new Array();
  17645. this.postProcessesEnabled = true;
  17646. // Customs render targets
  17647. this.renderTargetsEnabled = true;
  17648. this.dumpNextRenderTargets = false;
  17649. this.customRenderTargets = new Array();
  17650. // Imported meshes
  17651. this.importedMeshesFiles = new Array();
  17652. // Probes
  17653. this.probesEnabled = true;
  17654. this.reflectionProbes = new Array();
  17655. this._actionManagers = new Array();
  17656. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  17657. // Procedural textures
  17658. this.proceduralTexturesEnabled = true;
  17659. this._proceduralTextures = new Array();
  17660. this.soundTracks = new Array();
  17661. this._audioEnabled = true;
  17662. this._headphone = false;
  17663. // Performance counters
  17664. this._totalVertices = new BABYLON.PerfCounter();
  17665. this._activeIndices = new BABYLON.PerfCounter();
  17666. this._activeParticles = new BABYLON.PerfCounter();
  17667. this._activeBones = new BABYLON.PerfCounter();
  17668. this._animationTime = 0;
  17669. this.animationTimeScale = 1;
  17670. this._renderId = 0;
  17671. this._executeWhenReadyTimeoutId = -1;
  17672. this._intermediateRendering = false;
  17673. this._viewUpdateFlag = -1;
  17674. this._projectionUpdateFlag = -1;
  17675. this._alternateViewUpdateFlag = -1;
  17676. this._alternateProjectionUpdateFlag = -1;
  17677. this._toBeDisposed = new BABYLON.SmartArray(256);
  17678. this._pendingData = new Array();
  17679. this._isDisposed = false;
  17680. this._activeMeshes = new BABYLON.SmartArray(256);
  17681. this._processedMaterials = new BABYLON.SmartArray(256);
  17682. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  17683. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17684. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  17685. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  17686. this._activeAnimatables = new Array();
  17687. this._transformMatrix = BABYLON.Matrix.Zero();
  17688. this._useAlternateCameraConfiguration = false;
  17689. this._alternateRendering = false;
  17690. this.requireLightSorting = false;
  17691. this._activeMeshesFrozen = false;
  17692. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17693. this._engine.scenes.push(this);
  17694. this._uid = null;
  17695. this._renderingManager = new BABYLON.RenderingManager(this);
  17696. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17697. if (BABYLON.OutlineRenderer) {
  17698. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17699. }
  17700. if (BABYLON.Tools.IsWindowObjectExist()) {
  17701. this.attachControl();
  17702. }
  17703. //simplification queue
  17704. if (BABYLON.SimplificationQueue) {
  17705. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17706. }
  17707. //collision coordinator initialization. For now legacy per default.
  17708. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17709. // Uniform Buffer
  17710. this._createUbo();
  17711. // Default Image processing definition.
  17712. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17713. }
  17714. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17715. /** The fog is deactivated */
  17716. get: function () {
  17717. return Scene._FOGMODE_NONE;
  17718. },
  17719. enumerable: true,
  17720. configurable: true
  17721. });
  17722. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17723. /** The fog density is following an exponential function */
  17724. get: function () {
  17725. return Scene._FOGMODE_EXP;
  17726. },
  17727. enumerable: true,
  17728. configurable: true
  17729. });
  17730. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17731. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17732. get: function () {
  17733. return Scene._FOGMODE_EXP2;
  17734. },
  17735. enumerable: true,
  17736. configurable: true
  17737. });
  17738. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17739. /** The fog density is following a linear function. */
  17740. get: function () {
  17741. return Scene._FOGMODE_LINEAR;
  17742. },
  17743. enumerable: true,
  17744. configurable: true
  17745. });
  17746. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17747. /**
  17748. * Texture used in all pbr material as the reflection texture.
  17749. * As in the majority of the scene they are the same (exception for multi room and so on),
  17750. * this is easier to reference from here than from all the materials.
  17751. */
  17752. get: function () {
  17753. return this._environmentTexture;
  17754. },
  17755. /**
  17756. * Texture used in all pbr material as the reflection texture.
  17757. * As in the majority of the scene they are the same (exception for multi room and so on),
  17758. * this is easier to set here than in all the materials.
  17759. */
  17760. set: function (value) {
  17761. if (this._environmentTexture === value) {
  17762. return;
  17763. }
  17764. this._environmentTexture = value;
  17765. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17766. },
  17767. enumerable: true,
  17768. configurable: true
  17769. });
  17770. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17771. /**
  17772. * Default image processing configuration used either in the rendering
  17773. * Forward main pass or through the imageProcessingPostProcess if present.
  17774. * As in the majority of the scene they are the same (exception for multi camera),
  17775. * this is easier to reference from here than from all the materials and post process.
  17776. *
  17777. * No setter as we it is a shared configuration, you can set the values instead.
  17778. */
  17779. get: function () {
  17780. return this._imageProcessingConfiguration;
  17781. },
  17782. enumerable: true,
  17783. configurable: true
  17784. });
  17785. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17786. get: function () {
  17787. return this._forcePointsCloud;
  17788. },
  17789. set: function (value) {
  17790. if (this._forcePointsCloud === value) {
  17791. return;
  17792. }
  17793. this._forcePointsCloud = value;
  17794. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17795. },
  17796. enumerable: true,
  17797. configurable: true
  17798. });
  17799. Object.defineProperty(Scene.prototype, "onDispose", {
  17800. /** A function to be executed when this scene is disposed. */
  17801. set: function (callback) {
  17802. if (this._onDisposeObserver) {
  17803. this.onDisposeObservable.remove(this._onDisposeObserver);
  17804. }
  17805. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17806. },
  17807. enumerable: true,
  17808. configurable: true
  17809. });
  17810. Object.defineProperty(Scene.prototype, "beforeRender", {
  17811. /** A function to be executed before rendering this scene */
  17812. set: function (callback) {
  17813. if (this._onBeforeRenderObserver) {
  17814. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17815. }
  17816. if (callback) {
  17817. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17818. }
  17819. },
  17820. enumerable: true,
  17821. configurable: true
  17822. });
  17823. Object.defineProperty(Scene.prototype, "afterRender", {
  17824. /** A function to be executed after rendering this scene */
  17825. set: function (callback) {
  17826. if (this._onAfterRenderObserver) {
  17827. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17828. }
  17829. if (callback) {
  17830. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17831. }
  17832. },
  17833. enumerable: true,
  17834. configurable: true
  17835. });
  17836. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17837. set: function (callback) {
  17838. if (this._onBeforeCameraRenderObserver) {
  17839. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17840. }
  17841. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17847. set: function (callback) {
  17848. if (this._onAfterCameraRenderObserver) {
  17849. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17850. }
  17851. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17852. },
  17853. enumerable: true,
  17854. configurable: true
  17855. });
  17856. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17857. get: function () {
  17858. if (!this._gamepadManager) {
  17859. this._gamepadManager = new BABYLON.GamepadManager();
  17860. }
  17861. return this._gamepadManager;
  17862. },
  17863. enumerable: true,
  17864. configurable: true
  17865. });
  17866. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17867. get: function () {
  17868. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17869. },
  17870. enumerable: true,
  17871. configurable: true
  17872. });
  17873. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17874. get: function () {
  17875. return this._useRightHandedSystem;
  17876. },
  17877. set: function (value) {
  17878. if (this._useRightHandedSystem === value) {
  17879. return;
  17880. }
  17881. this._useRightHandedSystem = value;
  17882. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17883. },
  17884. enumerable: true,
  17885. configurable: true
  17886. });
  17887. Scene.prototype.setStepId = function (newStepId) {
  17888. this._currentStepId = newStepId;
  17889. };
  17890. ;
  17891. Scene.prototype.getStepId = function () {
  17892. return this._currentStepId;
  17893. };
  17894. ;
  17895. Scene.prototype.getInternalStep = function () {
  17896. return this._currentInternalStep;
  17897. };
  17898. ;
  17899. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17900. get: function () {
  17901. return this._fogEnabled;
  17902. },
  17903. /**
  17904. * is fog enabled on this scene.
  17905. */
  17906. set: function (value) {
  17907. if (this._fogEnabled === value) {
  17908. return;
  17909. }
  17910. this._fogEnabled = value;
  17911. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17912. },
  17913. enumerable: true,
  17914. configurable: true
  17915. });
  17916. Object.defineProperty(Scene.prototype, "fogMode", {
  17917. get: function () {
  17918. return this._fogMode;
  17919. },
  17920. set: function (value) {
  17921. if (this._fogMode === value) {
  17922. return;
  17923. }
  17924. this._fogMode = value;
  17925. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17926. },
  17927. enumerable: true,
  17928. configurable: true
  17929. });
  17930. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17931. get: function () {
  17932. return this._shadowsEnabled;
  17933. },
  17934. set: function (value) {
  17935. if (this._shadowsEnabled === value) {
  17936. return;
  17937. }
  17938. this._shadowsEnabled = value;
  17939. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17940. },
  17941. enumerable: true,
  17942. configurable: true
  17943. });
  17944. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17945. get: function () {
  17946. return this._lightsEnabled;
  17947. },
  17948. set: function (value) {
  17949. if (this._lightsEnabled === value) {
  17950. return;
  17951. }
  17952. this._lightsEnabled = value;
  17953. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17954. },
  17955. enumerable: true,
  17956. configurable: true
  17957. });
  17958. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17959. /** The default material used on meshes when no material is affected */
  17960. get: function () {
  17961. if (!this._defaultMaterial) {
  17962. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17963. }
  17964. return this._defaultMaterial;
  17965. },
  17966. /** The default material used on meshes when no material is affected */
  17967. set: function (value) {
  17968. this._defaultMaterial = value;
  17969. },
  17970. enumerable: true,
  17971. configurable: true
  17972. });
  17973. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17974. get: function () {
  17975. return this._texturesEnabled;
  17976. },
  17977. set: function (value) {
  17978. if (this._texturesEnabled === value) {
  17979. return;
  17980. }
  17981. this._texturesEnabled = value;
  17982. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17983. },
  17984. enumerable: true,
  17985. configurable: true
  17986. });
  17987. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17988. get: function () {
  17989. return this._skeletonsEnabled;
  17990. },
  17991. set: function (value) {
  17992. if (this._skeletonsEnabled === value) {
  17993. return;
  17994. }
  17995. this._skeletonsEnabled = value;
  17996. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17997. },
  17998. enumerable: true,
  17999. configurable: true
  18000. });
  18001. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18002. get: function () {
  18003. if (!this._postProcessRenderPipelineManager) {
  18004. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18005. }
  18006. return this._postProcessRenderPipelineManager;
  18007. },
  18008. enumerable: true,
  18009. configurable: true
  18010. });
  18011. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18012. get: function () {
  18013. if (!this._mainSoundTrack) {
  18014. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18015. }
  18016. return this._mainSoundTrack;
  18017. },
  18018. enumerable: true,
  18019. configurable: true
  18020. });
  18021. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18022. get: function () {
  18023. return this._alternateRendering;
  18024. },
  18025. enumerable: true,
  18026. configurable: true
  18027. });
  18028. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18029. get: function () {
  18030. return this._frustumPlanes;
  18031. },
  18032. enumerable: true,
  18033. configurable: true
  18034. });
  18035. Object.defineProperty(Scene.prototype, "debugLayer", {
  18036. // Properties
  18037. get: function () {
  18038. if (!this._debugLayer) {
  18039. this._debugLayer = new BABYLON.DebugLayer(this);
  18040. }
  18041. return this._debugLayer;
  18042. },
  18043. enumerable: true,
  18044. configurable: true
  18045. });
  18046. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18047. get: function () {
  18048. return this._workerCollisions;
  18049. },
  18050. set: function (enabled) {
  18051. if (!BABYLON.CollisionCoordinatorLegacy) {
  18052. return;
  18053. }
  18054. enabled = (enabled && !!Worker);
  18055. this._workerCollisions = enabled;
  18056. if (this.collisionCoordinator) {
  18057. this.collisionCoordinator.destroy();
  18058. }
  18059. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18060. this.collisionCoordinator.init(this);
  18061. },
  18062. enumerable: true,
  18063. configurable: true
  18064. });
  18065. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18066. get: function () {
  18067. return this._selectionOctree;
  18068. },
  18069. enumerable: true,
  18070. configurable: true
  18071. });
  18072. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18073. /**
  18074. * The mesh that is currently under the pointer.
  18075. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18076. */
  18077. get: function () {
  18078. return this._pointerOverMesh;
  18079. },
  18080. enumerable: true,
  18081. configurable: true
  18082. });
  18083. Object.defineProperty(Scene.prototype, "pointerX", {
  18084. /**
  18085. * Current on-screen X position of the pointer
  18086. * @return {number} X position of the pointer
  18087. */
  18088. get: function () {
  18089. return this._pointerX;
  18090. },
  18091. enumerable: true,
  18092. configurable: true
  18093. });
  18094. Object.defineProperty(Scene.prototype, "pointerY", {
  18095. /**
  18096. * Current on-screen Y position of the pointer
  18097. * @return {number} Y position of the pointer
  18098. */
  18099. get: function () {
  18100. return this._pointerY;
  18101. },
  18102. enumerable: true,
  18103. configurable: true
  18104. });
  18105. Scene.prototype.getCachedMaterial = function () {
  18106. return this._cachedMaterial;
  18107. };
  18108. Scene.prototype.getCachedEffect = function () {
  18109. return this._cachedEffect;
  18110. };
  18111. Scene.prototype.getCachedVisibility = function () {
  18112. return this._cachedVisibility;
  18113. };
  18114. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18115. if (visibility === void 0) { visibility = 1; }
  18116. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18117. };
  18118. Scene.prototype.getBoundingBoxRenderer = function () {
  18119. if (!this._boundingBoxRenderer) {
  18120. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18121. }
  18122. return this._boundingBoxRenderer;
  18123. };
  18124. Scene.prototype.getOutlineRenderer = function () {
  18125. return this._outlineRenderer;
  18126. };
  18127. Scene.prototype.getEngine = function () {
  18128. return this._engine;
  18129. };
  18130. Scene.prototype.getTotalVertices = function () {
  18131. return this._totalVertices.current;
  18132. };
  18133. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18134. get: function () {
  18135. return this._totalVertices;
  18136. },
  18137. enumerable: true,
  18138. configurable: true
  18139. });
  18140. Scene.prototype.getActiveIndices = function () {
  18141. return this._activeIndices.current;
  18142. };
  18143. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18144. get: function () {
  18145. return this._activeIndices;
  18146. },
  18147. enumerable: true,
  18148. configurable: true
  18149. });
  18150. Scene.prototype.getActiveParticles = function () {
  18151. return this._activeParticles.current;
  18152. };
  18153. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18154. get: function () {
  18155. return this._activeParticles;
  18156. },
  18157. enumerable: true,
  18158. configurable: true
  18159. });
  18160. Scene.prototype.getActiveBones = function () {
  18161. return this._activeBones.current;
  18162. };
  18163. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18164. get: function () {
  18165. return this._activeBones;
  18166. },
  18167. enumerable: true,
  18168. configurable: true
  18169. });
  18170. // Stats
  18171. Scene.prototype.getInterFramePerfCounter = function () {
  18172. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18173. return 0;
  18174. };
  18175. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18176. get: function () {
  18177. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18178. return null;
  18179. },
  18180. enumerable: true,
  18181. configurable: true
  18182. });
  18183. Scene.prototype.getLastFrameDuration = function () {
  18184. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18185. return 0;
  18186. };
  18187. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18188. get: function () {
  18189. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18190. return null;
  18191. },
  18192. enumerable: true,
  18193. configurable: true
  18194. });
  18195. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18196. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18197. return 0;
  18198. };
  18199. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18200. get: function () {
  18201. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18202. return null;
  18203. },
  18204. enumerable: true,
  18205. configurable: true
  18206. });
  18207. Scene.prototype.getActiveMeshes = function () {
  18208. return this._activeMeshes;
  18209. };
  18210. Scene.prototype.getRenderTargetsDuration = function () {
  18211. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18212. return 0;
  18213. };
  18214. Scene.prototype.getRenderDuration = function () {
  18215. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18216. return 0;
  18217. };
  18218. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18219. get: function () {
  18220. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18221. return null;
  18222. },
  18223. enumerable: true,
  18224. configurable: true
  18225. });
  18226. Scene.prototype.getParticlesDuration = function () {
  18227. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18228. return 0;
  18229. };
  18230. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18231. get: function () {
  18232. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18233. return null;
  18234. },
  18235. enumerable: true,
  18236. configurable: true
  18237. });
  18238. Scene.prototype.getSpritesDuration = function () {
  18239. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18240. return 0;
  18241. };
  18242. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18243. get: function () {
  18244. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18245. return null;
  18246. },
  18247. enumerable: true,
  18248. configurable: true
  18249. });
  18250. Scene.prototype.getAnimationRatio = function () {
  18251. return this._animationRatio;
  18252. };
  18253. Scene.prototype.getRenderId = function () {
  18254. return this._renderId;
  18255. };
  18256. Scene.prototype.incrementRenderId = function () {
  18257. this._renderId++;
  18258. };
  18259. Scene.prototype._updatePointerPosition = function (evt) {
  18260. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18261. if (!canvasRect) {
  18262. return;
  18263. }
  18264. this._pointerX = evt.clientX - canvasRect.left;
  18265. this._pointerY = evt.clientY - canvasRect.top;
  18266. this._unTranslatedPointerX = this._pointerX;
  18267. this._unTranslatedPointerY = this._pointerY;
  18268. };
  18269. Scene.prototype._createUbo = function () {
  18270. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18271. this._sceneUbo.addUniform("viewProjection", 16);
  18272. this._sceneUbo.addUniform("view", 16);
  18273. };
  18274. Scene.prototype._createAlternateUbo = function () {
  18275. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18276. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18277. this._alternateSceneUbo.addUniform("view", 16);
  18278. };
  18279. // Pointers handling
  18280. /**
  18281. * Use this method to simulate a pointer move on a mesh
  18282. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18283. */
  18284. Scene.prototype.simulatePointerMove = function (pickResult) {
  18285. var evt = new PointerEvent("pointermove");
  18286. return this._processPointerMove(pickResult, evt);
  18287. };
  18288. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18289. var canvas = this._engine.getRenderingCanvas();
  18290. if (!canvas) {
  18291. return this;
  18292. }
  18293. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18294. this.setPointerOverSprite(null);
  18295. this.setPointerOverMesh(pickResult.pickedMesh);
  18296. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18297. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18298. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18299. }
  18300. else {
  18301. canvas.style.cursor = this.hoverCursor;
  18302. }
  18303. }
  18304. else {
  18305. canvas.style.cursor = this.defaultCursor;
  18306. }
  18307. }
  18308. else {
  18309. this.setPointerOverMesh(null);
  18310. // Sprites
  18311. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18312. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18313. this.setPointerOverSprite(pickResult.pickedSprite);
  18314. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18315. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18316. }
  18317. else {
  18318. canvas.style.cursor = this.hoverCursor;
  18319. }
  18320. }
  18321. else {
  18322. this.setPointerOverSprite(null);
  18323. // Restore pointer
  18324. canvas.style.cursor = this.defaultCursor;
  18325. }
  18326. }
  18327. if (pickResult) {
  18328. if (this.onPointerMove) {
  18329. this.onPointerMove(evt, pickResult);
  18330. }
  18331. if (this.onPointerObservable.hasObservers()) {
  18332. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18333. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18334. this.onPointerObservable.notifyObservers(pi, type);
  18335. }
  18336. }
  18337. return this;
  18338. };
  18339. /**
  18340. * Use this method to simulate a pointer down on a mesh
  18341. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18342. */
  18343. Scene.prototype.simulatePointerDown = function (pickResult) {
  18344. var evt = new PointerEvent("pointerdown");
  18345. return this._processPointerDown(pickResult, evt);
  18346. };
  18347. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18348. var _this = this;
  18349. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18350. this._pickedDownMesh = pickResult.pickedMesh;
  18351. var actionManager = pickResult.pickedMesh.actionManager;
  18352. if (actionManager) {
  18353. if (actionManager.hasPickTriggers) {
  18354. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18355. switch (evt.button) {
  18356. case 0:
  18357. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18358. break;
  18359. case 1:
  18360. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18361. break;
  18362. case 2:
  18363. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18364. break;
  18365. }
  18366. }
  18367. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18368. window.setTimeout(function () {
  18369. 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);
  18370. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18371. if (_this._totalPointersPressed !== 0 &&
  18372. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18373. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18374. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18375. _this._startingPointerTime = 0;
  18376. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18377. }
  18378. }
  18379. }, Scene.LongPressDelay);
  18380. }
  18381. }
  18382. }
  18383. if (pickResult) {
  18384. if (this.onPointerDown) {
  18385. this.onPointerDown(evt, pickResult);
  18386. }
  18387. if (this.onPointerObservable.hasObservers()) {
  18388. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18389. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18390. this.onPointerObservable.notifyObservers(pi, type);
  18391. }
  18392. }
  18393. return this;
  18394. };
  18395. /**
  18396. * Use this method to simulate a pointer up on a mesh
  18397. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18398. */
  18399. Scene.prototype.simulatePointerUp = function (pickResult) {
  18400. var evt = new PointerEvent("pointerup");
  18401. var clickInfo = new ClickInfo();
  18402. clickInfo.singleClick = true;
  18403. return this._processPointerUp(pickResult, evt, clickInfo);
  18404. };
  18405. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18406. if (pickResult && pickResult && pickResult.pickedMesh) {
  18407. this._pickedUpMesh = pickResult.pickedMesh;
  18408. if (this._pickedDownMesh === this._pickedUpMesh) {
  18409. if (this.onPointerPick) {
  18410. this.onPointerPick(evt, pickResult);
  18411. }
  18412. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18413. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18414. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18415. this.onPointerObservable.notifyObservers(pi, type);
  18416. }
  18417. }
  18418. if (pickResult.pickedMesh.actionManager) {
  18419. if (clickInfo.ignore) {
  18420. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18421. }
  18422. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18423. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18424. }
  18425. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18426. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18427. }
  18428. }
  18429. }
  18430. if (this._pickedDownMesh &&
  18431. this._pickedDownMesh.actionManager &&
  18432. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18433. this._pickedDownMesh !== this._pickedUpMesh) {
  18434. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18435. }
  18436. if (this.onPointerUp) {
  18437. this.onPointerUp(evt, pickResult);
  18438. }
  18439. if (this.onPointerObservable.hasObservers()) {
  18440. if (!clickInfo.ignore) {
  18441. if (!clickInfo.hasSwiped) {
  18442. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18443. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18444. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18445. this.onPointerObservable.notifyObservers(pi, type);
  18446. }
  18447. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18448. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18449. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18450. this.onPointerObservable.notifyObservers(pi, type);
  18451. }
  18452. }
  18453. }
  18454. else {
  18455. var type = BABYLON.PointerEventTypes.POINTERUP;
  18456. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18457. this.onPointerObservable.notifyObservers(pi, type);
  18458. }
  18459. }
  18460. return this;
  18461. };
  18462. /**
  18463. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18464. * @param attachUp defines if you want to attach events to pointerup
  18465. * @param attachDown defines if you want to attach events to pointerdown
  18466. * @param attachMove defines if you want to attach events to pointermove
  18467. */
  18468. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18469. var _this = this;
  18470. if (attachUp === void 0) { attachUp = true; }
  18471. if (attachDown === void 0) { attachDown = true; }
  18472. if (attachMove === void 0) { attachMove = true; }
  18473. this._initActionManager = function (act, clickInfo) {
  18474. if (!_this._meshPickProceed) {
  18475. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18476. _this._currentPickResult = pickResult;
  18477. if (pickResult) {
  18478. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18479. }
  18480. _this._meshPickProceed = true;
  18481. }
  18482. return act;
  18483. };
  18484. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18485. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18486. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18487. btn !== _this._previousButtonPressed) {
  18488. _this._doubleClickOccured = false;
  18489. clickInfo.singleClick = true;
  18490. clickInfo.ignore = false;
  18491. cb(clickInfo, _this._currentPickResult);
  18492. }
  18493. };
  18494. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18495. var clickInfo = new ClickInfo();
  18496. _this._currentPickResult = null;
  18497. var act = null;
  18498. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18499. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18500. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18501. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18502. act = _this._initActionManager(act, clickInfo);
  18503. if (act)
  18504. checkPicking = act.hasPickTriggers;
  18505. }
  18506. if (checkPicking) {
  18507. var btn = evt.button;
  18508. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18509. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18510. if (!clickInfo.hasSwiped) {
  18511. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18512. if (!checkSingleClickImmediately) {
  18513. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18514. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18515. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18516. act = _this._initActionManager(act, clickInfo);
  18517. if (act)
  18518. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18519. }
  18520. }
  18521. if (checkSingleClickImmediately) {
  18522. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18523. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18524. btn !== _this._previousButtonPressed) {
  18525. clickInfo.singleClick = true;
  18526. cb(clickInfo, _this._currentPickResult);
  18527. }
  18528. }
  18529. else {
  18530. // wait that no double click has been raised during the double click delay
  18531. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18532. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18533. }
  18534. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18535. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18536. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18537. act = _this._initActionManager(act, clickInfo);
  18538. if (act)
  18539. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18540. }
  18541. if (checkDoubleClick) {
  18542. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18543. if (btn === _this._previousButtonPressed &&
  18544. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18545. !_this._doubleClickOccured) {
  18546. // pointer has not moved for 2 clicks, it's a double click
  18547. if (!clickInfo.hasSwiped &&
  18548. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18549. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18550. _this._previousStartingPointerTime = 0;
  18551. _this._doubleClickOccured = true;
  18552. clickInfo.doubleClick = true;
  18553. clickInfo.ignore = false;
  18554. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18555. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18556. }
  18557. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18558. cb(clickInfo, _this._currentPickResult);
  18559. }
  18560. else {
  18561. _this._doubleClickOccured = false;
  18562. _this._previousStartingPointerTime = _this._startingPointerTime;
  18563. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18564. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18565. _this._previousButtonPressed = btn;
  18566. _this._previousHasSwiped = clickInfo.hasSwiped;
  18567. if (Scene.ExclusiveDoubleClickMode) {
  18568. if (_this._previousDelayedSimpleClickTimeout) {
  18569. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18570. }
  18571. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18572. cb(clickInfo, _this._previousPickResult);
  18573. }
  18574. else {
  18575. cb(clickInfo, _this._currentPickResult);
  18576. }
  18577. }
  18578. }
  18579. else {
  18580. _this._doubleClickOccured = false;
  18581. _this._previousStartingPointerTime = _this._startingPointerTime;
  18582. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18583. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18584. _this._previousButtonPressed = btn;
  18585. _this._previousHasSwiped = clickInfo.hasSwiped;
  18586. }
  18587. }
  18588. }
  18589. }
  18590. clickInfo.ignore = true;
  18591. cb(clickInfo, _this._currentPickResult);
  18592. };
  18593. this._spritePredicate = function (sprite) {
  18594. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18595. };
  18596. this._onPointerMove = function (evt) {
  18597. _this._updatePointerPosition(evt);
  18598. // PreObservable support
  18599. if (_this.onPrePointerObservable.hasObservers()) {
  18600. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18601. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18602. _this.onPrePointerObservable.notifyObservers(pi, type);
  18603. if (pi.skipOnPointerObservable) {
  18604. return;
  18605. }
  18606. }
  18607. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18608. return;
  18609. }
  18610. if (!_this.pointerMovePredicate) {
  18611. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18612. }
  18613. // Meshes
  18614. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18615. _this._processPointerMove(pickResult, evt);
  18616. };
  18617. this._onPointerDown = function (evt) {
  18618. _this._totalPointersPressed++;
  18619. _this._pickedDownMesh = null;
  18620. _this._meshPickProceed = false;
  18621. _this._updatePointerPosition(evt);
  18622. if (_this.preventDefaultOnPointerDown && canvas) {
  18623. evt.preventDefault();
  18624. canvas.focus();
  18625. }
  18626. // PreObservable support
  18627. if (_this.onPrePointerObservable.hasObservers()) {
  18628. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18629. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18630. _this.onPrePointerObservable.notifyObservers(pi, type);
  18631. if (pi.skipOnPointerObservable) {
  18632. return;
  18633. }
  18634. }
  18635. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18636. return;
  18637. }
  18638. _this._startingPointerPosition.x = _this._pointerX;
  18639. _this._startingPointerPosition.y = _this._pointerY;
  18640. _this._startingPointerTime = new Date().getTime();
  18641. if (!_this.pointerDownPredicate) {
  18642. _this.pointerDownPredicate = function (mesh) {
  18643. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18644. };
  18645. }
  18646. // Meshes
  18647. _this._pickedDownMesh = null;
  18648. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18649. _this._processPointerDown(pickResult, evt);
  18650. // Sprites
  18651. _this._pickedDownSprite = null;
  18652. if (_this.spriteManagers.length > 0) {
  18653. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18654. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18655. if (pickResult.pickedSprite.actionManager) {
  18656. _this._pickedDownSprite = pickResult.pickedSprite;
  18657. switch (evt.button) {
  18658. case 0:
  18659. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18660. break;
  18661. case 1:
  18662. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18663. break;
  18664. case 2:
  18665. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18666. break;
  18667. }
  18668. if (pickResult.pickedSprite.actionManager) {
  18669. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18670. }
  18671. }
  18672. }
  18673. }
  18674. };
  18675. this._onPointerUp = function (evt) {
  18676. if (_this._totalPointersPressed === 0) {
  18677. return; // So we need to test it the pointer down was pressed before.
  18678. }
  18679. _this._totalPointersPressed--;
  18680. _this._pickedUpMesh = null;
  18681. _this._meshPickProceed = false;
  18682. _this._updatePointerPosition(evt);
  18683. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18684. // PreObservable support
  18685. if (_this.onPrePointerObservable.hasObservers()) {
  18686. if (!clickInfo.ignore) {
  18687. if (!clickInfo.hasSwiped) {
  18688. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18689. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18690. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18691. _this.onPrePointerObservable.notifyObservers(pi, type);
  18692. if (pi.skipOnPointerObservable) {
  18693. return;
  18694. }
  18695. }
  18696. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18697. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18698. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18699. _this.onPrePointerObservable.notifyObservers(pi, type);
  18700. if (pi.skipOnPointerObservable) {
  18701. return;
  18702. }
  18703. }
  18704. }
  18705. }
  18706. else {
  18707. var type = BABYLON.PointerEventTypes.POINTERUP;
  18708. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18709. _this.onPrePointerObservable.notifyObservers(pi, type);
  18710. if (pi.skipOnPointerObservable) {
  18711. return;
  18712. }
  18713. }
  18714. }
  18715. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18716. return;
  18717. }
  18718. if (!_this.pointerUpPredicate) {
  18719. _this.pointerUpPredicate = function (mesh) {
  18720. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18721. };
  18722. }
  18723. // Meshes
  18724. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18725. _this._initActionManager(null, clickInfo);
  18726. }
  18727. if (!pickResult) {
  18728. pickResult = _this._currentPickResult;
  18729. }
  18730. _this._processPointerUp(pickResult, evt, clickInfo);
  18731. // Sprites
  18732. if (_this.spriteManagers.length > 0) {
  18733. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18734. if (spritePickResult) {
  18735. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18736. if (spritePickResult.pickedSprite.actionManager) {
  18737. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18738. if (spritePickResult.pickedSprite.actionManager) {
  18739. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18740. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18741. }
  18742. }
  18743. }
  18744. }
  18745. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18746. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18747. }
  18748. }
  18749. }
  18750. _this._previousPickResult = _this._currentPickResult;
  18751. });
  18752. };
  18753. this._onKeyDown = function (evt) {
  18754. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18755. if (_this.onPreKeyboardObservable.hasObservers()) {
  18756. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18757. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18758. if (pi.skipOnPointerObservable) {
  18759. return;
  18760. }
  18761. }
  18762. if (_this.onKeyboardObservable.hasObservers()) {
  18763. var pi = new BABYLON.KeyboardInfo(type, evt);
  18764. _this.onKeyboardObservable.notifyObservers(pi, type);
  18765. }
  18766. if (_this.actionManager) {
  18767. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18768. }
  18769. };
  18770. this._onKeyUp = function (evt) {
  18771. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18772. if (_this.onPreKeyboardObservable.hasObservers()) {
  18773. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18774. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18775. if (pi.skipOnPointerObservable) {
  18776. return;
  18777. }
  18778. }
  18779. if (_this.onKeyboardObservable.hasObservers()) {
  18780. var pi = new BABYLON.KeyboardInfo(type, evt);
  18781. _this.onKeyboardObservable.notifyObservers(pi, type);
  18782. }
  18783. if (_this.actionManager) {
  18784. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18785. }
  18786. };
  18787. var engine = this.getEngine();
  18788. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18789. if (!canvas) {
  18790. return;
  18791. }
  18792. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18793. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18794. });
  18795. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18796. if (!canvas) {
  18797. return;
  18798. }
  18799. canvas.removeEventListener("keydown", _this._onKeyDown);
  18800. canvas.removeEventListener("keyup", _this._onKeyUp);
  18801. });
  18802. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18803. var canvas = this._engine.getRenderingCanvas();
  18804. if (!canvas) {
  18805. return;
  18806. }
  18807. if (attachMove) {
  18808. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18809. // Wheel
  18810. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18811. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18812. }
  18813. if (attachDown) {
  18814. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18815. }
  18816. if (attachUp) {
  18817. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18818. }
  18819. canvas.tabIndex = 1;
  18820. };
  18821. Scene.prototype.detachControl = function () {
  18822. var engine = this.getEngine();
  18823. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18824. var canvas = engine.getRenderingCanvas();
  18825. if (!canvas) {
  18826. return;
  18827. }
  18828. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18829. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18830. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18831. if (this._onCanvasBlurObserver) {
  18832. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18833. }
  18834. if (this._onCanvasFocusObserver) {
  18835. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18836. }
  18837. // Wheel
  18838. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18839. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18840. // Keyboard
  18841. canvas.removeEventListener("keydown", this._onKeyDown);
  18842. canvas.removeEventListener("keyup", this._onKeyUp);
  18843. // Observables
  18844. this.onKeyboardObservable.clear();
  18845. this.onPreKeyboardObservable.clear();
  18846. this.onPointerObservable.clear();
  18847. this.onPrePointerObservable.clear();
  18848. };
  18849. // Ready
  18850. Scene.prototype.isReady = function () {
  18851. if (this._isDisposed) {
  18852. return false;
  18853. }
  18854. if (this._pendingData.length > 0) {
  18855. return false;
  18856. }
  18857. var index;
  18858. // Geometries
  18859. for (index = 0; index < this._geometries.length; index++) {
  18860. var geometry = this._geometries[index];
  18861. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18862. return false;
  18863. }
  18864. }
  18865. // Meshes
  18866. for (index = 0; index < this.meshes.length; index++) {
  18867. var mesh = this.meshes[index];
  18868. if (!mesh.isEnabled()) {
  18869. continue;
  18870. }
  18871. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18872. continue;
  18873. }
  18874. if (!mesh.isReady()) {
  18875. return false;
  18876. }
  18877. var mat = mesh.material;
  18878. if (mat) {
  18879. if (!mat.isReady(mesh)) {
  18880. return false;
  18881. }
  18882. }
  18883. }
  18884. return true;
  18885. };
  18886. Scene.prototype.resetCachedMaterial = function () {
  18887. this._cachedMaterial = null;
  18888. this._cachedEffect = null;
  18889. this._cachedVisibility = null;
  18890. };
  18891. Scene.prototype.registerBeforeRender = function (func) {
  18892. this.onBeforeRenderObservable.add(func);
  18893. };
  18894. Scene.prototype.unregisterBeforeRender = function (func) {
  18895. this.onBeforeRenderObservable.removeCallback(func);
  18896. };
  18897. Scene.prototype.registerAfterRender = function (func) {
  18898. this.onAfterRenderObservable.add(func);
  18899. };
  18900. Scene.prototype.unregisterAfterRender = function (func) {
  18901. this.onAfterRenderObservable.removeCallback(func);
  18902. };
  18903. Scene.prototype._addPendingData = function (data) {
  18904. this._pendingData.push(data);
  18905. };
  18906. Scene.prototype._removePendingData = function (data) {
  18907. var wasLoading = this.isLoading;
  18908. var index = this._pendingData.indexOf(data);
  18909. if (index !== -1) {
  18910. this._pendingData.splice(index, 1);
  18911. }
  18912. if (wasLoading && !this.isLoading) {
  18913. this.onDataLoadedObservable.notifyObservers(this);
  18914. }
  18915. };
  18916. Scene.prototype.getWaitingItemsCount = function () {
  18917. return this._pendingData.length;
  18918. };
  18919. Object.defineProperty(Scene.prototype, "isLoading", {
  18920. get: function () {
  18921. return this._pendingData.length > 0;
  18922. },
  18923. enumerable: true,
  18924. configurable: true
  18925. });
  18926. /**
  18927. * Registers a function to be executed when the scene is ready.
  18928. * @param {Function} func - the function to be executed.
  18929. */
  18930. Scene.prototype.executeWhenReady = function (func) {
  18931. var _this = this;
  18932. this.onReadyObservable.add(func);
  18933. if (this._executeWhenReadyTimeoutId !== -1) {
  18934. return;
  18935. }
  18936. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18937. _this._checkIsReady();
  18938. }, 150);
  18939. };
  18940. Scene.prototype._checkIsReady = function () {
  18941. var _this = this;
  18942. if (this.isReady()) {
  18943. this.onReadyObservable.notifyObservers(this);
  18944. this.onReadyObservable.clear();
  18945. this._executeWhenReadyTimeoutId = -1;
  18946. return;
  18947. }
  18948. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18949. _this._checkIsReady();
  18950. }, 150);
  18951. };
  18952. // Animations
  18953. /**
  18954. * Will start the animation sequence of a given target
  18955. * @param target - the target
  18956. * @param {number} from - from which frame should animation start
  18957. * @param {number} to - till which frame should animation run.
  18958. * @param {boolean} [loop] - should the animation loop
  18959. * @param {number} [speedRatio] - the speed in which to run the animation
  18960. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18961. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18962. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18963. * See BABYLON.Animatable
  18964. */
  18965. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18966. if (speedRatio === void 0) { speedRatio = 1.0; }
  18967. if (from > to && speedRatio > 0) {
  18968. speedRatio *= -1;
  18969. }
  18970. this.stopAnimation(target);
  18971. if (!animatable) {
  18972. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18973. }
  18974. // Local animations
  18975. if (target.animations) {
  18976. animatable.appendAnimations(target, target.animations);
  18977. }
  18978. // Children animations
  18979. if (target.getAnimatables) {
  18980. var animatables = target.getAnimatables();
  18981. for (var index = 0; index < animatables.length; index++) {
  18982. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18983. }
  18984. }
  18985. animatable.reset();
  18986. return animatable;
  18987. };
  18988. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18989. if (speedRatio === undefined) {
  18990. speedRatio = 1.0;
  18991. }
  18992. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18993. return animatable;
  18994. };
  18995. Scene.prototype.getAnimatableByTarget = function (target) {
  18996. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18997. if (this._activeAnimatables[index].target === target) {
  18998. return this._activeAnimatables[index];
  18999. }
  19000. }
  19001. return null;
  19002. };
  19003. Object.defineProperty(Scene.prototype, "Animatables", {
  19004. get: function () {
  19005. return this._activeAnimatables;
  19006. },
  19007. enumerable: true,
  19008. configurable: true
  19009. });
  19010. /**
  19011. * Will stop the animation of the given target
  19012. * @param target - the target
  19013. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19014. * @see beginAnimation
  19015. */
  19016. Scene.prototype.stopAnimation = function (target, animationName) {
  19017. var animatable = this.getAnimatableByTarget(target);
  19018. if (animatable) {
  19019. animatable.stop(animationName);
  19020. }
  19021. };
  19022. Scene.prototype._animate = function () {
  19023. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19024. return;
  19025. }
  19026. // Getting time
  19027. var now = BABYLON.Tools.Now;
  19028. if (!this._animationTimeLast) {
  19029. if (this._pendingData.length > 0) {
  19030. return;
  19031. }
  19032. this._animationTimeLast = now;
  19033. }
  19034. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  19035. this._animationTime += deltaTime;
  19036. this._animationTimeLast = now;
  19037. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19038. this._activeAnimatables[index]._animate(this._animationTime);
  19039. }
  19040. };
  19041. // Matrix
  19042. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19043. this._useAlternateCameraConfiguration = active;
  19044. };
  19045. Scene.prototype.getViewMatrix = function () {
  19046. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19047. };
  19048. Scene.prototype.getProjectionMatrix = function () {
  19049. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19050. };
  19051. Scene.prototype.getTransformMatrix = function () {
  19052. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19053. };
  19054. Scene.prototype.setTransformMatrix = function (view, projection) {
  19055. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19056. return;
  19057. }
  19058. this._viewUpdateFlag = view.updateFlag;
  19059. this._projectionUpdateFlag = projection.updateFlag;
  19060. this._viewMatrix = view;
  19061. this._projectionMatrix = projection;
  19062. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19063. // Update frustum
  19064. if (!this._frustumPlanes) {
  19065. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19066. }
  19067. else {
  19068. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19069. }
  19070. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19071. var otherCamera = this.activeCamera._alternateCamera;
  19072. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19073. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19074. }
  19075. if (this._sceneUbo.useUbo) {
  19076. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19077. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19078. this._sceneUbo.update();
  19079. }
  19080. };
  19081. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19082. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19083. return;
  19084. }
  19085. this._alternateViewUpdateFlag = view.updateFlag;
  19086. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19087. this._alternateViewMatrix = view;
  19088. this._alternateProjectionMatrix = projection;
  19089. if (!this._alternateTransformMatrix) {
  19090. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19091. }
  19092. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19093. if (!this._alternateSceneUbo) {
  19094. this._createAlternateUbo();
  19095. }
  19096. if (this._alternateSceneUbo.useUbo) {
  19097. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19098. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19099. this._alternateSceneUbo.update();
  19100. }
  19101. };
  19102. Scene.prototype.getSceneUniformBuffer = function () {
  19103. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19104. };
  19105. // Methods
  19106. Scene.prototype.getUniqueId = function () {
  19107. var result = Scene._uniqueIdCounter;
  19108. Scene._uniqueIdCounter++;
  19109. return result;
  19110. };
  19111. Scene.prototype.addMesh = function (newMesh) {
  19112. this.meshes.push(newMesh);
  19113. //notify the collision coordinator
  19114. if (this.collisionCoordinator) {
  19115. this.collisionCoordinator.onMeshAdded(newMesh);
  19116. }
  19117. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19118. };
  19119. Scene.prototype.removeMesh = function (toRemove) {
  19120. var index = this.meshes.indexOf(toRemove);
  19121. if (index !== -1) {
  19122. // Remove from the scene if mesh found
  19123. this.meshes.splice(index, 1);
  19124. }
  19125. //notify the collision coordinator
  19126. if (this.collisionCoordinator) {
  19127. this.collisionCoordinator.onMeshRemoved(toRemove);
  19128. }
  19129. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19130. return index;
  19131. };
  19132. Scene.prototype.removeSkeleton = function (toRemove) {
  19133. var index = this.skeletons.indexOf(toRemove);
  19134. if (index !== -1) {
  19135. // Remove from the scene if found
  19136. this.skeletons.splice(index, 1);
  19137. }
  19138. return index;
  19139. };
  19140. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19141. var index = this.morphTargetManagers.indexOf(toRemove);
  19142. if (index !== -1) {
  19143. // Remove from the scene if found
  19144. this.morphTargetManagers.splice(index, 1);
  19145. }
  19146. return index;
  19147. };
  19148. Scene.prototype.removeLight = function (toRemove) {
  19149. var index = this.lights.indexOf(toRemove);
  19150. if (index !== -1) {
  19151. // Remove from the scene if mesh found
  19152. this.lights.splice(index, 1);
  19153. this.sortLightsByPriority();
  19154. }
  19155. this.onLightRemovedObservable.notifyObservers(toRemove);
  19156. return index;
  19157. };
  19158. Scene.prototype.removeCamera = function (toRemove) {
  19159. var index = this.cameras.indexOf(toRemove);
  19160. if (index !== -1) {
  19161. // Remove from the scene if mesh found
  19162. this.cameras.splice(index, 1);
  19163. }
  19164. // Remove from activeCameras
  19165. var index2 = this.activeCameras.indexOf(toRemove);
  19166. if (index2 !== -1) {
  19167. // Remove from the scene if mesh found
  19168. this.activeCameras.splice(index2, 1);
  19169. }
  19170. // Reset the activeCamera
  19171. if (this.activeCamera === toRemove) {
  19172. if (this.cameras.length > 0) {
  19173. this.activeCamera = this.cameras[0];
  19174. }
  19175. else {
  19176. this.activeCamera = null;
  19177. }
  19178. }
  19179. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19180. return index;
  19181. };
  19182. Scene.prototype.addLight = function (newLight) {
  19183. this.lights.push(newLight);
  19184. this.sortLightsByPriority();
  19185. this.onNewLightAddedObservable.notifyObservers(newLight);
  19186. };
  19187. Scene.prototype.sortLightsByPriority = function () {
  19188. if (this.requireLightSorting) {
  19189. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19190. }
  19191. };
  19192. Scene.prototype.addCamera = function (newCamera) {
  19193. this.cameras.push(newCamera);
  19194. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19195. };
  19196. /**
  19197. * Switch active camera
  19198. * @param {Camera} newCamera - new active camera
  19199. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19200. */
  19201. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19202. if (attachControl === void 0) { attachControl = true; }
  19203. var canvas = this._engine.getRenderingCanvas();
  19204. if (!canvas) {
  19205. return;
  19206. }
  19207. if (this.activeCamera) {
  19208. this.activeCamera.detachControl(canvas);
  19209. }
  19210. this.activeCamera = newCamera;
  19211. if (attachControl) {
  19212. newCamera.attachControl(canvas);
  19213. }
  19214. };
  19215. /**
  19216. * sets the active camera of the scene using its ID
  19217. * @param {string} id - the camera's ID
  19218. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19219. * @see activeCamera
  19220. */
  19221. Scene.prototype.setActiveCameraByID = function (id) {
  19222. var camera = this.getCameraByID(id);
  19223. if (camera) {
  19224. this.activeCamera = camera;
  19225. return camera;
  19226. }
  19227. return null;
  19228. };
  19229. /**
  19230. * sets the active camera of the scene using its name
  19231. * @param {string} name - the camera's name
  19232. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19233. * @see activeCamera
  19234. */
  19235. Scene.prototype.setActiveCameraByName = function (name) {
  19236. var camera = this.getCameraByName(name);
  19237. if (camera) {
  19238. this.activeCamera = camera;
  19239. return camera;
  19240. }
  19241. return null;
  19242. };
  19243. /**
  19244. * get a material using its id
  19245. * @param {string} the material's ID
  19246. * @return {BABYLON.Material|null} the material or null if none found.
  19247. */
  19248. Scene.prototype.getMaterialByID = function (id) {
  19249. for (var index = 0; index < this.materials.length; index++) {
  19250. if (this.materials[index].id === id) {
  19251. return this.materials[index];
  19252. }
  19253. }
  19254. return null;
  19255. };
  19256. /**
  19257. * get a material using its name
  19258. * @param {string} the material's name
  19259. * @return {BABYLON.Material|null} the material or null if none found.
  19260. */
  19261. Scene.prototype.getMaterialByName = function (name) {
  19262. for (var index = 0; index < this.materials.length; index++) {
  19263. if (this.materials[index].name === name) {
  19264. return this.materials[index];
  19265. }
  19266. }
  19267. return null;
  19268. };
  19269. Scene.prototype.getLensFlareSystemByName = function (name) {
  19270. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19271. if (this.lensFlareSystems[index].name === name) {
  19272. return this.lensFlareSystems[index];
  19273. }
  19274. }
  19275. return null;
  19276. };
  19277. Scene.prototype.getLensFlareSystemByID = function (id) {
  19278. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19279. if (this.lensFlareSystems[index].id === id) {
  19280. return this.lensFlareSystems[index];
  19281. }
  19282. }
  19283. return null;
  19284. };
  19285. Scene.prototype.getCameraByID = function (id) {
  19286. for (var index = 0; index < this.cameras.length; index++) {
  19287. if (this.cameras[index].id === id) {
  19288. return this.cameras[index];
  19289. }
  19290. }
  19291. return null;
  19292. };
  19293. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19294. for (var index = 0; index < this.cameras.length; index++) {
  19295. if (this.cameras[index].uniqueId === uniqueId) {
  19296. return this.cameras[index];
  19297. }
  19298. }
  19299. return null;
  19300. };
  19301. /**
  19302. * get a camera using its name
  19303. * @param {string} the camera's name
  19304. * @return {BABYLON.Camera|null} the camera or null if none found.
  19305. */
  19306. Scene.prototype.getCameraByName = function (name) {
  19307. for (var index = 0; index < this.cameras.length; index++) {
  19308. if (this.cameras[index].name === name) {
  19309. return this.cameras[index];
  19310. }
  19311. }
  19312. return null;
  19313. };
  19314. /**
  19315. * get a bone using its id
  19316. * @param {string} the bone's id
  19317. * @return {BABYLON.Bone|null} the bone or null if not found
  19318. */
  19319. Scene.prototype.getBoneByID = function (id) {
  19320. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19321. var skeleton = this.skeletons[skeletonIndex];
  19322. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19323. if (skeleton.bones[boneIndex].id === id) {
  19324. return skeleton.bones[boneIndex];
  19325. }
  19326. }
  19327. }
  19328. return null;
  19329. };
  19330. /**
  19331. * get a bone using its id
  19332. * @param {string} the bone's name
  19333. * @return {BABYLON.Bone|null} the bone or null if not found
  19334. */
  19335. Scene.prototype.getBoneByName = function (name) {
  19336. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19337. var skeleton = this.skeletons[skeletonIndex];
  19338. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19339. if (skeleton.bones[boneIndex].name === name) {
  19340. return skeleton.bones[boneIndex];
  19341. }
  19342. }
  19343. }
  19344. return null;
  19345. };
  19346. /**
  19347. * get a light node using its name
  19348. * @param {string} the light's name
  19349. * @return {BABYLON.Light|null} the light or null if none found.
  19350. */
  19351. Scene.prototype.getLightByName = function (name) {
  19352. for (var index = 0; index < this.lights.length; index++) {
  19353. if (this.lights[index].name === name) {
  19354. return this.lights[index];
  19355. }
  19356. }
  19357. return null;
  19358. };
  19359. /**
  19360. * get a light node using its ID
  19361. * @param {string} the light's id
  19362. * @return {BABYLON.Light|null} the light or null if none found.
  19363. */
  19364. Scene.prototype.getLightByID = function (id) {
  19365. for (var index = 0; index < this.lights.length; index++) {
  19366. if (this.lights[index].id === id) {
  19367. return this.lights[index];
  19368. }
  19369. }
  19370. return null;
  19371. };
  19372. /**
  19373. * get a light node using its scene-generated unique ID
  19374. * @param {number} the light's unique id
  19375. * @return {BABYLON.Light|null} the light or null if none found.
  19376. */
  19377. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19378. for (var index = 0; index < this.lights.length; index++) {
  19379. if (this.lights[index].uniqueId === uniqueId) {
  19380. return this.lights[index];
  19381. }
  19382. }
  19383. return null;
  19384. };
  19385. /**
  19386. * get a particle system by id
  19387. * @param id {number} the particle system id
  19388. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19389. */
  19390. Scene.prototype.getParticleSystemByID = function (id) {
  19391. for (var index = 0; index < this.particleSystems.length; index++) {
  19392. if (this.particleSystems[index].id === id) {
  19393. return this.particleSystems[index];
  19394. }
  19395. }
  19396. return null;
  19397. };
  19398. /**
  19399. * get a geometry using its ID
  19400. * @param {string} the geometry's id
  19401. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19402. */
  19403. Scene.prototype.getGeometryByID = function (id) {
  19404. for (var index = 0; index < this._geometries.length; index++) {
  19405. if (this._geometries[index].id === id) {
  19406. return this._geometries[index];
  19407. }
  19408. }
  19409. return null;
  19410. };
  19411. /**
  19412. * add a new geometry to this scene.
  19413. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19414. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19415. * @return {boolean} was the geometry added or not
  19416. */
  19417. Scene.prototype.pushGeometry = function (geometry, force) {
  19418. if (!force && this.getGeometryByID(geometry.id)) {
  19419. return false;
  19420. }
  19421. this._geometries.push(geometry);
  19422. //notify the collision coordinator
  19423. if (this.collisionCoordinator) {
  19424. this.collisionCoordinator.onGeometryAdded(geometry);
  19425. }
  19426. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19427. return true;
  19428. };
  19429. /**
  19430. * Removes an existing geometry
  19431. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19432. * @return {boolean} was the geometry removed or not
  19433. */
  19434. Scene.prototype.removeGeometry = function (geometry) {
  19435. var index = this._geometries.indexOf(geometry);
  19436. if (index > -1) {
  19437. this._geometries.splice(index, 1);
  19438. //notify the collision coordinator
  19439. if (this.collisionCoordinator) {
  19440. this.collisionCoordinator.onGeometryDeleted(geometry);
  19441. }
  19442. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19443. return true;
  19444. }
  19445. return false;
  19446. };
  19447. Scene.prototype.getGeometries = function () {
  19448. return this._geometries;
  19449. };
  19450. /**
  19451. * Get the first added mesh found of a given ID
  19452. * @param {string} id - the id to search for
  19453. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19454. */
  19455. Scene.prototype.getMeshByID = function (id) {
  19456. for (var index = 0; index < this.meshes.length; index++) {
  19457. if (this.meshes[index].id === id) {
  19458. return this.meshes[index];
  19459. }
  19460. }
  19461. return null;
  19462. };
  19463. Scene.prototype.getMeshesByID = function (id) {
  19464. return this.meshes.filter(function (m) {
  19465. return m.id === id;
  19466. });
  19467. };
  19468. /**
  19469. * Get a mesh with its auto-generated unique id
  19470. * @param {number} uniqueId - the unique id to search for
  19471. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19472. */
  19473. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19474. for (var index = 0; index < this.meshes.length; index++) {
  19475. if (this.meshes[index].uniqueId === uniqueId) {
  19476. return this.meshes[index];
  19477. }
  19478. }
  19479. return null;
  19480. };
  19481. /**
  19482. * Get a the last added mesh found of a given ID
  19483. * @param {string} id - the id to search for
  19484. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19485. */
  19486. Scene.prototype.getLastMeshByID = function (id) {
  19487. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19488. if (this.meshes[index].id === id) {
  19489. return this.meshes[index];
  19490. }
  19491. }
  19492. return null;
  19493. };
  19494. /**
  19495. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19496. * @param {string} id - the id to search for
  19497. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19498. */
  19499. Scene.prototype.getLastEntryByID = function (id) {
  19500. var index;
  19501. for (index = this.meshes.length - 1; index >= 0; index--) {
  19502. if (this.meshes[index].id === id) {
  19503. return this.meshes[index];
  19504. }
  19505. }
  19506. for (index = this.cameras.length - 1; index >= 0; index--) {
  19507. if (this.cameras[index].id === id) {
  19508. return this.cameras[index];
  19509. }
  19510. }
  19511. for (index = this.lights.length - 1; index >= 0; index--) {
  19512. if (this.lights[index].id === id) {
  19513. return this.lights[index];
  19514. }
  19515. }
  19516. return null;
  19517. };
  19518. Scene.prototype.getNodeByID = function (id) {
  19519. var mesh = this.getMeshByID(id);
  19520. if (mesh) {
  19521. return mesh;
  19522. }
  19523. var light = this.getLightByID(id);
  19524. if (light) {
  19525. return light;
  19526. }
  19527. var camera = this.getCameraByID(id);
  19528. if (camera) {
  19529. return camera;
  19530. }
  19531. var bone = this.getBoneByID(id);
  19532. return bone;
  19533. };
  19534. Scene.prototype.getNodeByName = function (name) {
  19535. var mesh = this.getMeshByName(name);
  19536. if (mesh) {
  19537. return mesh;
  19538. }
  19539. var light = this.getLightByName(name);
  19540. if (light) {
  19541. return light;
  19542. }
  19543. var camera = this.getCameraByName(name);
  19544. if (camera) {
  19545. return camera;
  19546. }
  19547. var bone = this.getBoneByName(name);
  19548. return bone;
  19549. };
  19550. Scene.prototype.getMeshByName = function (name) {
  19551. for (var index = 0; index < this.meshes.length; index++) {
  19552. if (this.meshes[index].name === name) {
  19553. return this.meshes[index];
  19554. }
  19555. }
  19556. return null;
  19557. };
  19558. Scene.prototype.getSoundByName = function (name) {
  19559. var index;
  19560. if (BABYLON.AudioEngine) {
  19561. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19562. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19563. return this.mainSoundTrack.soundCollection[index];
  19564. }
  19565. }
  19566. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19567. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19568. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19569. return this.soundTracks[sdIndex].soundCollection[index];
  19570. }
  19571. }
  19572. }
  19573. }
  19574. return null;
  19575. };
  19576. Scene.prototype.getLastSkeletonByID = function (id) {
  19577. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19578. if (this.skeletons[index].id === id) {
  19579. return this.skeletons[index];
  19580. }
  19581. }
  19582. return null;
  19583. };
  19584. Scene.prototype.getSkeletonById = function (id) {
  19585. for (var index = 0; index < this.skeletons.length; index++) {
  19586. if (this.skeletons[index].id === id) {
  19587. return this.skeletons[index];
  19588. }
  19589. }
  19590. return null;
  19591. };
  19592. Scene.prototype.getSkeletonByName = function (name) {
  19593. for (var index = 0; index < this.skeletons.length; index++) {
  19594. if (this.skeletons[index].name === name) {
  19595. return this.skeletons[index];
  19596. }
  19597. }
  19598. return null;
  19599. };
  19600. Scene.prototype.getMorphTargetManagerById = function (id) {
  19601. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19602. if (this.morphTargetManagers[index].uniqueId === id) {
  19603. return this.morphTargetManagers[index];
  19604. }
  19605. }
  19606. return null;
  19607. };
  19608. Scene.prototype.isActiveMesh = function (mesh) {
  19609. return (this._activeMeshes.indexOf(mesh) !== -1);
  19610. };
  19611. /**
  19612. * Return a the first highlight layer of the scene with a given name.
  19613. * @param name The name of the highlight layer to look for.
  19614. * @return The highlight layer if found otherwise null.
  19615. */
  19616. Scene.prototype.getHighlightLayerByName = function (name) {
  19617. for (var index = 0; index < this.highlightLayers.length; index++) {
  19618. if (this.highlightLayers[index].name === name) {
  19619. return this.highlightLayers[index];
  19620. }
  19621. }
  19622. return null;
  19623. };
  19624. Object.defineProperty(Scene.prototype, "uid", {
  19625. /**
  19626. * Return a unique id as a string which can serve as an identifier for the scene
  19627. */
  19628. get: function () {
  19629. if (!this._uid) {
  19630. this._uid = BABYLON.Tools.RandomId();
  19631. }
  19632. return this._uid;
  19633. },
  19634. enumerable: true,
  19635. configurable: true
  19636. });
  19637. /**
  19638. * Add an externaly attached data from its key.
  19639. * This method call will fail and return false, if such key already exists.
  19640. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19641. * @param key the unique key that identifies the data
  19642. * @param data the data object to associate to the key for this Engine instance
  19643. * @return true if no such key were already present and the data was added successfully, false otherwise
  19644. */
  19645. Scene.prototype.addExternalData = function (key, data) {
  19646. if (!this._externalData) {
  19647. this._externalData = new BABYLON.StringDictionary();
  19648. }
  19649. return this._externalData.add(key, data);
  19650. };
  19651. /**
  19652. * Get an externaly attached data from its key
  19653. * @param key the unique key that identifies the data
  19654. * @return the associated data, if present (can be null), or undefined if not present
  19655. */
  19656. Scene.prototype.getExternalData = function (key) {
  19657. if (!this._externalData) {
  19658. return null;
  19659. }
  19660. return this._externalData.get(key);
  19661. };
  19662. /**
  19663. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19664. * @param key the unique key that identifies the data
  19665. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19666. * @return the associated data, can be null if the factory returned null.
  19667. */
  19668. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19669. if (!this._externalData) {
  19670. this._externalData = new BABYLON.StringDictionary();
  19671. }
  19672. return this._externalData.getOrAddWithFactory(key, factory);
  19673. };
  19674. /**
  19675. * Remove an externaly attached data from the Engine instance
  19676. * @param key the unique key that identifies the data
  19677. * @return true if the data was successfully removed, false if it doesn't exist
  19678. */
  19679. Scene.prototype.removeExternalData = function (key) {
  19680. return this._externalData.remove(key);
  19681. };
  19682. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19683. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19684. var material = subMesh.getMaterial();
  19685. if (mesh.showSubMeshesBoundingBox) {
  19686. var boundingInfo = subMesh.getBoundingInfo();
  19687. if (boundingInfo) {
  19688. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19689. }
  19690. }
  19691. if (material) {
  19692. // Render targets
  19693. if (material.getRenderTargetTextures) {
  19694. if (this._processedMaterials.indexOf(material) === -1) {
  19695. this._processedMaterials.push(material);
  19696. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19697. }
  19698. }
  19699. // Dispatch
  19700. this._activeIndices.addCount(subMesh.indexCount, false);
  19701. this._renderingManager.dispatch(subMesh);
  19702. }
  19703. }
  19704. };
  19705. Scene.prototype._isInIntermediateRendering = function () {
  19706. return this._intermediateRendering;
  19707. };
  19708. /**
  19709. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19710. */
  19711. Scene.prototype.freezeActiveMeshes = function () {
  19712. this._evaluateActiveMeshes();
  19713. this._activeMeshesFrozen = true;
  19714. return this;
  19715. };
  19716. /**
  19717. * Use this function to restart evaluating active meshes on every frame
  19718. */
  19719. Scene.prototype.unfreezeActiveMeshes = function () {
  19720. this._activeMeshesFrozen = false;
  19721. return this;
  19722. };
  19723. Scene.prototype._evaluateActiveMeshes = function () {
  19724. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19725. return;
  19726. }
  19727. if (!this.activeCamera) {
  19728. return;
  19729. }
  19730. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  19731. this.activeCamera._activeMeshes.reset();
  19732. this._activeMeshes.reset();
  19733. this._renderingManager.reset();
  19734. this._processedMaterials.reset();
  19735. this._activeParticleSystems.reset();
  19736. this._activeSkeletons.reset();
  19737. this._softwareSkinnedMeshes.reset();
  19738. if (this._boundingBoxRenderer) {
  19739. this._boundingBoxRenderer.reset();
  19740. }
  19741. // Meshes
  19742. var meshes;
  19743. var len;
  19744. if (this._selectionOctree) {
  19745. var selection = this._selectionOctree.select(this._frustumPlanes);
  19746. meshes = selection.data;
  19747. len = selection.length;
  19748. }
  19749. else {
  19750. len = this.meshes.length;
  19751. meshes = this.meshes;
  19752. }
  19753. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19754. var mesh = meshes[meshIndex];
  19755. if (mesh.isBlocked) {
  19756. continue;
  19757. }
  19758. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19759. if (!mesh.isReady() || !mesh.isEnabled()) {
  19760. continue;
  19761. }
  19762. mesh.computeWorldMatrix();
  19763. // Intersections
  19764. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19765. this._meshesForIntersections.pushNoDuplicate(mesh);
  19766. }
  19767. // Switch to current LOD
  19768. var meshLOD = mesh.getLOD(this.activeCamera);
  19769. if (!meshLOD) {
  19770. continue;
  19771. }
  19772. mesh._preActivate();
  19773. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19774. this._activeMeshes.push(mesh);
  19775. this.activeCamera._activeMeshes.push(mesh);
  19776. mesh._activate(this._renderId);
  19777. if (meshLOD !== mesh) {
  19778. meshLOD._activate(this._renderId);
  19779. }
  19780. this._activeMesh(mesh, meshLOD);
  19781. }
  19782. }
  19783. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  19784. // Particle systems
  19785. if (this.particlesEnabled) {
  19786. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  19787. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19788. var particleSystem = this.particleSystems[particleIndex];
  19789. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19790. continue;
  19791. }
  19792. var emitter = particleSystem.emitter;
  19793. if (!emitter.position || emitter.isEnabled()) {
  19794. this._activeParticleSystems.push(particleSystem);
  19795. particleSystem.animate();
  19796. this._renderingManager.dispatchParticles(particleSystem);
  19797. }
  19798. }
  19799. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  19800. }
  19801. };
  19802. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19803. if (mesh.skeleton && this.skeletonsEnabled) {
  19804. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19805. mesh.skeleton.prepare();
  19806. }
  19807. if (!mesh.computeBonesUsingShaders) {
  19808. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19809. }
  19810. }
  19811. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19812. var boundingInfo = sourceMesh.getBoundingInfo();
  19813. if (boundingInfo) {
  19814. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19815. }
  19816. }
  19817. if (mesh && mesh.subMeshes) {
  19818. // Submeshes Octrees
  19819. var len;
  19820. var subMeshes;
  19821. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19822. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19823. len = intersections.length;
  19824. subMeshes = intersections.data;
  19825. }
  19826. else {
  19827. subMeshes = mesh.subMeshes;
  19828. len = subMeshes.length;
  19829. }
  19830. for (var subIndex = 0; subIndex < len; subIndex++) {
  19831. var subMesh = subMeshes[subIndex];
  19832. this._evaluateSubMesh(subMesh, mesh);
  19833. }
  19834. }
  19835. };
  19836. Scene.prototype.updateTransformMatrix = function (force) {
  19837. if (!this.activeCamera) {
  19838. return;
  19839. }
  19840. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19841. };
  19842. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19843. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19844. };
  19845. Scene.prototype._renderForCamera = function (camera) {
  19846. if (camera && camera._skipRendering) {
  19847. return;
  19848. }
  19849. var engine = this._engine;
  19850. this.activeCamera = camera;
  19851. if (!this.activeCamera)
  19852. throw new Error("Active camera not set");
  19853. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19854. // Viewport
  19855. engine.setViewport(this.activeCamera.viewport);
  19856. // Camera
  19857. this.resetCachedMaterial();
  19858. this._renderId++;
  19859. this.activeCamera.update();
  19860. this.updateTransformMatrix();
  19861. if (camera._alternateCamera) {
  19862. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19863. this._alternateRendering = true;
  19864. }
  19865. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19866. // Meshes
  19867. this._evaluateActiveMeshes();
  19868. // Software skinning
  19869. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19870. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19871. mesh.applySkeleton(mesh.skeleton);
  19872. }
  19873. // Render targets
  19874. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19875. var needsRestoreFrameBuffer = false;
  19876. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19877. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19878. }
  19879. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19880. this._intermediateRendering = true;
  19881. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19882. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19883. var renderTarget = this._renderTargets.data[renderIndex];
  19884. if (renderTarget._shouldRender()) {
  19885. this._renderId++;
  19886. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19887. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19888. }
  19889. }
  19890. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19891. this._intermediateRendering = false;
  19892. this._renderId++;
  19893. needsRestoreFrameBuffer = true; // Restore back buffer
  19894. }
  19895. // Render HighlightLayer Texture
  19896. var stencilState = this._engine.getStencilBuffer();
  19897. var renderhighlights = false;
  19898. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19899. this._intermediateRendering = true;
  19900. for (var i = 0; i < this.highlightLayers.length; i++) {
  19901. var highlightLayer = this.highlightLayers[i];
  19902. if (highlightLayer.shouldRender() &&
  19903. (!highlightLayer.camera ||
  19904. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19905. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19906. renderhighlights = true;
  19907. var renderTarget = highlightLayer._mainTexture;
  19908. if (renderTarget._shouldRender()) {
  19909. this._renderId++;
  19910. renderTarget.render(false, false);
  19911. needsRestoreFrameBuffer = true;
  19912. }
  19913. }
  19914. }
  19915. this._intermediateRendering = false;
  19916. this._renderId++;
  19917. }
  19918. if (needsRestoreFrameBuffer) {
  19919. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19920. }
  19921. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19922. // Prepare Frame
  19923. this.postProcessManager._prepareFrame();
  19924. // Backgrounds
  19925. var layerIndex;
  19926. var layer;
  19927. if (this.layers.length) {
  19928. engine.setDepthBuffer(false);
  19929. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19930. layer = this.layers[layerIndex];
  19931. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19932. layer.render();
  19933. }
  19934. }
  19935. engine.setDepthBuffer(true);
  19936. }
  19937. // Activate HighlightLayer stencil
  19938. if (renderhighlights) {
  19939. this._engine.setStencilBuffer(true);
  19940. }
  19941. // Render
  19942. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  19943. this._renderingManager.render(null, null, true, true);
  19944. this.onAfterDrawPhaseObservable.notifyObservers(this);
  19945. // Restore HighlightLayer stencil
  19946. if (renderhighlights) {
  19947. this._engine.setStencilBuffer(stencilState);
  19948. }
  19949. // Bounding boxes
  19950. if (this._boundingBoxRenderer) {
  19951. this._boundingBoxRenderer.render();
  19952. }
  19953. // Lens flares
  19954. if (this.lensFlaresEnabled) {
  19955. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19956. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19957. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19958. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19959. lensFlareSystem.render();
  19960. }
  19961. }
  19962. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19963. }
  19964. // Foregrounds
  19965. if (this.layers.length) {
  19966. engine.setDepthBuffer(false);
  19967. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19968. layer = this.layers[layerIndex];
  19969. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19970. layer.render();
  19971. }
  19972. }
  19973. engine.setDepthBuffer(true);
  19974. }
  19975. // Highlight Layer
  19976. if (renderhighlights) {
  19977. engine.setDepthBuffer(false);
  19978. for (var i = 0; i < this.highlightLayers.length; i++) {
  19979. if (this.highlightLayers[i].shouldRender()) {
  19980. this.highlightLayers[i].render();
  19981. }
  19982. }
  19983. engine.setDepthBuffer(true);
  19984. }
  19985. // Finalize frame
  19986. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19987. // Reset some special arrays
  19988. this._renderTargets.reset();
  19989. this._alternateRendering = false;
  19990. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19991. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19992. };
  19993. Scene.prototype._processSubCameras = function (camera) {
  19994. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19995. this._renderForCamera(camera);
  19996. return;
  19997. }
  19998. // Update camera
  19999. if (this.activeCamera) {
  20000. this.activeCamera.update();
  20001. }
  20002. // rig cameras
  20003. for (var index = 0; index < camera._rigCameras.length; index++) {
  20004. this._renderForCamera(camera._rigCameras[index]);
  20005. }
  20006. this.activeCamera = camera;
  20007. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20008. };
  20009. Scene.prototype._checkIntersections = function () {
  20010. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20011. var sourceMesh = this._meshesForIntersections.data[index];
  20012. if (!sourceMesh.actionManager) {
  20013. continue;
  20014. }
  20015. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20016. var action = sourceMesh.actionManager.actions[actionIndex];
  20017. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20018. var parameters = action.getTriggerParameter();
  20019. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20020. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20021. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20022. if (areIntersecting && currentIntersectionInProgress === -1) {
  20023. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20024. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20025. sourceMesh._intersectionsInProgress.push(otherMesh);
  20026. }
  20027. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20028. sourceMesh._intersectionsInProgress.push(otherMesh);
  20029. }
  20030. }
  20031. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20032. //They intersected, and now they don't.
  20033. //is this trigger an exit trigger? execute an event.
  20034. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20035. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20036. }
  20037. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20038. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20039. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20040. }
  20041. }
  20042. }
  20043. }
  20044. }
  20045. };
  20046. Scene.prototype.render = function () {
  20047. if (this.isDisposed) {
  20048. return;
  20049. }
  20050. this._activeParticles.fetchNewFrame();
  20051. this._totalVertices.fetchNewFrame();
  20052. this._activeIndices.fetchNewFrame();
  20053. this._activeBones.fetchNewFrame();
  20054. this._meshesForIntersections.reset();
  20055. this.resetCachedMaterial();
  20056. this.onBeforeAnimationsObservable.notifyObservers(this);
  20057. // Actions
  20058. if (this.actionManager) {
  20059. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20060. }
  20061. //Simplification Queue
  20062. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20063. this.simplificationQueue.executeNext();
  20064. }
  20065. if (this._engine.isDeterministicLockStep()) {
  20066. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  20067. var defaultTimeStep = (60.0 / 1000.0);
  20068. if (this._physicsEngine) {
  20069. defaultTimeStep = this._physicsEngine.getTimeStep();
  20070. }
  20071. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20072. this._timeAccumulator += deltaTime;
  20073. // compute the amount of fixed steps we should have taken since the last step
  20074. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  20075. internalSteps = Math.min(internalSteps, maxSubSteps);
  20076. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  20077. this.onBeforeStepObservable.notifyObservers(this);
  20078. // Animations
  20079. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  20080. this._animate();
  20081. this.onAfterAnimationsObservable.notifyObservers(this);
  20082. // Physics
  20083. if (this._physicsEngine) {
  20084. this.onBeforePhysicsObservable.notifyObservers(this);
  20085. this._physicsEngine._step(defaultTimeStep);
  20086. this.onAfterPhysicsObservable.notifyObservers(this);
  20087. }
  20088. this._timeAccumulator -= defaultTimeStep;
  20089. this.onAfterStepObservable.notifyObservers(this);
  20090. this._currentStepId++;
  20091. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  20092. this._evaluateActiveMeshes();
  20093. }
  20094. }
  20095. }
  20096. else {
  20097. // Animations
  20098. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20099. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20100. this._animate();
  20101. this.onAfterAnimationsObservable.notifyObservers(this);
  20102. // Physics
  20103. if (this._physicsEngine) {
  20104. this.onBeforePhysicsObservable.notifyObservers(this);
  20105. this._physicsEngine._step(deltaTime / 1000.0);
  20106. this.onAfterPhysicsObservable.notifyObservers(this);
  20107. }
  20108. }
  20109. // Before render
  20110. this.onBeforeRenderObservable.notifyObservers(this);
  20111. // Customs render targets
  20112. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20113. var engine = this.getEngine();
  20114. var currentActiveCamera = this.activeCamera;
  20115. if (this.renderTargetsEnabled) {
  20116. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20117. this._intermediateRendering = true;
  20118. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20119. var renderTarget = this.customRenderTargets[customIndex];
  20120. if (renderTarget._shouldRender()) {
  20121. this._renderId++;
  20122. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20123. if (!this.activeCamera)
  20124. throw new Error("Active camera not set");
  20125. // Viewport
  20126. engine.setViewport(this.activeCamera.viewport);
  20127. // Camera
  20128. this.updateTransformMatrix();
  20129. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20130. }
  20131. }
  20132. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20133. this._intermediateRendering = false;
  20134. this._renderId++;
  20135. }
  20136. // Restore back buffer
  20137. if (this.customRenderTargets.length > 0) {
  20138. engine.restoreDefaultFramebuffer();
  20139. }
  20140. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20141. this.activeCamera = currentActiveCamera;
  20142. // Procedural textures
  20143. if (this.proceduralTexturesEnabled) {
  20144. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20145. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20146. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20147. if (proceduralTexture._shouldRender()) {
  20148. proceduralTexture.render();
  20149. }
  20150. }
  20151. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20152. }
  20153. // Clear
  20154. if (this.autoClearDepthAndStencil || this.autoClear) {
  20155. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20156. }
  20157. // Shadows
  20158. if (this.shadowsEnabled) {
  20159. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20160. var light = this.lights[lightIndex];
  20161. var shadowGenerator = light.getShadowGenerator();
  20162. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20163. var shadowMap = (shadowGenerator.getShadowMap());
  20164. if (this.textures.indexOf(shadowMap) !== -1) {
  20165. this._renderTargets.push(shadowMap);
  20166. }
  20167. }
  20168. }
  20169. }
  20170. // Depth renderer
  20171. if (this._depthRenderer) {
  20172. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20173. }
  20174. // Geometry renderer
  20175. if (this._geometryBufferRenderer) {
  20176. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20177. }
  20178. // RenderPipeline
  20179. if (this._postProcessRenderPipelineManager) {
  20180. this._postProcessRenderPipelineManager.update();
  20181. }
  20182. // Multi-cameras?
  20183. if (this.activeCameras.length > 0) {
  20184. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20185. if (cameraIndex > 0) {
  20186. this._engine.clear(null, false, true, true);
  20187. }
  20188. this._processSubCameras(this.activeCameras[cameraIndex]);
  20189. }
  20190. }
  20191. else {
  20192. if (!this.activeCamera) {
  20193. throw new Error("No camera defined");
  20194. }
  20195. this._processSubCameras(this.activeCamera);
  20196. }
  20197. // Intersection checks
  20198. this._checkIntersections();
  20199. // Update the audio listener attached to the camera
  20200. if (BABYLON.AudioEngine) {
  20201. this._updateAudioParameters();
  20202. }
  20203. // After render
  20204. if (this.afterRender) {
  20205. this.afterRender();
  20206. }
  20207. this.onAfterRenderObservable.notifyObservers(this);
  20208. // Cleaning
  20209. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20210. var data = this._toBeDisposed.data[index];
  20211. if (data) {
  20212. data.dispose();
  20213. }
  20214. this._toBeDisposed[index] = null;
  20215. }
  20216. this._toBeDisposed.reset();
  20217. if (this.dumpNextRenderTargets) {
  20218. this.dumpNextRenderTargets = false;
  20219. }
  20220. this._activeBones.addCount(0, true);
  20221. this._activeIndices.addCount(0, true);
  20222. this._activeParticles.addCount(0, true);
  20223. };
  20224. Scene.prototype._updateAudioParameters = function () {
  20225. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20226. return;
  20227. }
  20228. var listeningCamera;
  20229. var audioEngine = BABYLON.Engine.audioEngine;
  20230. if (this.activeCameras.length > 0) {
  20231. listeningCamera = this.activeCameras[0];
  20232. }
  20233. else {
  20234. listeningCamera = this.activeCamera;
  20235. }
  20236. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20237. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20238. // for VR cameras
  20239. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20240. listeningCamera = listeningCamera.rigCameras[0];
  20241. }
  20242. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20243. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20244. cameraDirection.normalize();
  20245. // To avoid some errors on GearVR
  20246. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20247. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20248. }
  20249. var i;
  20250. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20251. var sound = this.mainSoundTrack.soundCollection[i];
  20252. if (sound.useCustomAttenuation) {
  20253. sound.updateDistanceFromListener();
  20254. }
  20255. }
  20256. for (i = 0; i < this.soundTracks.length; i++) {
  20257. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20258. sound = this.soundTracks[i].soundCollection[j];
  20259. if (sound.useCustomAttenuation) {
  20260. sound.updateDistanceFromListener();
  20261. }
  20262. }
  20263. }
  20264. }
  20265. };
  20266. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20267. // Audio
  20268. get: function () {
  20269. return this._audioEnabled;
  20270. },
  20271. set: function (value) {
  20272. this._audioEnabled = value;
  20273. if (BABYLON.AudioEngine) {
  20274. if (this._audioEnabled) {
  20275. this._enableAudio();
  20276. }
  20277. else {
  20278. this._disableAudio();
  20279. }
  20280. }
  20281. },
  20282. enumerable: true,
  20283. configurable: true
  20284. });
  20285. Scene.prototype._disableAudio = function () {
  20286. var i;
  20287. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20288. this.mainSoundTrack.soundCollection[i].pause();
  20289. }
  20290. for (i = 0; i < this.soundTracks.length; i++) {
  20291. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20292. this.soundTracks[i].soundCollection[j].pause();
  20293. }
  20294. }
  20295. };
  20296. Scene.prototype._enableAudio = function () {
  20297. var i;
  20298. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20299. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20300. this.mainSoundTrack.soundCollection[i].play();
  20301. }
  20302. }
  20303. for (i = 0; i < this.soundTracks.length; i++) {
  20304. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20305. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20306. this.soundTracks[i].soundCollection[j].play();
  20307. }
  20308. }
  20309. }
  20310. };
  20311. Object.defineProperty(Scene.prototype, "headphone", {
  20312. get: function () {
  20313. return this._headphone;
  20314. },
  20315. set: function (value) {
  20316. this._headphone = value;
  20317. if (BABYLON.AudioEngine) {
  20318. if (this._headphone) {
  20319. this._switchAudioModeForHeadphones();
  20320. }
  20321. else {
  20322. this._switchAudioModeForNormalSpeakers();
  20323. }
  20324. }
  20325. },
  20326. enumerable: true,
  20327. configurable: true
  20328. });
  20329. Scene.prototype._switchAudioModeForHeadphones = function () {
  20330. this.mainSoundTrack.switchPanningModelToHRTF();
  20331. for (var i = 0; i < this.soundTracks.length; i++) {
  20332. this.soundTracks[i].switchPanningModelToHRTF();
  20333. }
  20334. };
  20335. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20336. this.mainSoundTrack.switchPanningModelToEqualPower();
  20337. for (var i = 0; i < this.soundTracks.length; i++) {
  20338. this.soundTracks[i].switchPanningModelToEqualPower();
  20339. }
  20340. };
  20341. Scene.prototype.enableDepthRenderer = function () {
  20342. if (this._depthRenderer) {
  20343. return this._depthRenderer;
  20344. }
  20345. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20346. return this._depthRenderer;
  20347. };
  20348. Scene.prototype.disableDepthRenderer = function () {
  20349. if (!this._depthRenderer) {
  20350. return;
  20351. }
  20352. this._depthRenderer.dispose();
  20353. this._depthRenderer = null;
  20354. };
  20355. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20356. if (ratio === void 0) { ratio = 1; }
  20357. if (this._geometryBufferRenderer) {
  20358. return this._geometryBufferRenderer;
  20359. }
  20360. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20361. if (!this._geometryBufferRenderer.isSupported) {
  20362. this._geometryBufferRenderer = null;
  20363. }
  20364. return this._geometryBufferRenderer;
  20365. };
  20366. Scene.prototype.disableGeometryBufferRenderer = function () {
  20367. if (!this._geometryBufferRenderer) {
  20368. return;
  20369. }
  20370. this._geometryBufferRenderer.dispose();
  20371. this._geometryBufferRenderer = null;
  20372. };
  20373. Scene.prototype.freezeMaterials = function () {
  20374. for (var i = 0; i < this.materials.length; i++) {
  20375. this.materials[i].freeze();
  20376. }
  20377. };
  20378. Scene.prototype.unfreezeMaterials = function () {
  20379. for (var i = 0; i < this.materials.length; i++) {
  20380. this.materials[i].unfreeze();
  20381. }
  20382. };
  20383. Scene.prototype.dispose = function () {
  20384. this.beforeRender = null;
  20385. this.afterRender = null;
  20386. this.skeletons = [];
  20387. this.morphTargetManagers = [];
  20388. this.importedMeshesFiles = new Array();
  20389. this.resetCachedMaterial();
  20390. if (this._depthRenderer) {
  20391. this._depthRenderer.dispose();
  20392. }
  20393. if (this._gamepadManager) {
  20394. this._gamepadManager.dispose();
  20395. this._gamepadManager = null;
  20396. }
  20397. // Smart arrays
  20398. if (this.activeCamera) {
  20399. this.activeCamera._activeMeshes.dispose();
  20400. this.activeCamera = null;
  20401. }
  20402. this._activeMeshes.dispose();
  20403. this._renderingManager.dispose();
  20404. this._processedMaterials.dispose();
  20405. this._activeParticleSystems.dispose();
  20406. this._activeSkeletons.dispose();
  20407. this._softwareSkinnedMeshes.dispose();
  20408. this._renderTargets.dispose();
  20409. if (this._boundingBoxRenderer) {
  20410. this._boundingBoxRenderer.dispose();
  20411. }
  20412. this._meshesForIntersections.dispose();
  20413. this._toBeDisposed.dispose();
  20414. // Debug layer
  20415. if (this._debugLayer) {
  20416. this._debugLayer.hide();
  20417. }
  20418. // Events
  20419. this.onDisposeObservable.notifyObservers(this);
  20420. this.onDisposeObservable.clear();
  20421. this.onBeforeRenderObservable.clear();
  20422. this.onAfterRenderObservable.clear();
  20423. this.OnBeforeRenderTargetsRenderObservable.clear();
  20424. this.OnAfterRenderTargetsRenderObservable.clear();
  20425. this.onAfterStepObservable.clear();
  20426. this.onBeforeStepObservable.clear();
  20427. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20428. this.onAfterActiveMeshesEvaluationObservable.clear();
  20429. this.onBeforeParticlesRenderingObservable.clear();
  20430. this.onAfterParticlesRenderingObservable.clear();
  20431. this.onBeforeSpritesRenderingObservable.clear();
  20432. this.onAfterSpritesRenderingObservable.clear();
  20433. this.onBeforeDrawPhaseObservable.clear();
  20434. this.onAfterDrawPhaseObservable.clear();
  20435. this.onBeforePhysicsObservable.clear();
  20436. this.onAfterPhysicsObservable.clear();
  20437. this.onBeforeAnimationsObservable.clear();
  20438. this.onAfterAnimationsObservable.clear();
  20439. this.onDataLoadedObservable.clear();
  20440. this.detachControl();
  20441. // Release sounds & sounds tracks
  20442. if (BABYLON.AudioEngine) {
  20443. this.disposeSounds();
  20444. }
  20445. // VR Helper
  20446. if (this.VRHelper) {
  20447. this.VRHelper.dispose();
  20448. }
  20449. // Detach cameras
  20450. var canvas = this._engine.getRenderingCanvas();
  20451. if (canvas) {
  20452. var index;
  20453. for (index = 0; index < this.cameras.length; index++) {
  20454. this.cameras[index].detachControl(canvas);
  20455. }
  20456. }
  20457. // Release lights
  20458. while (this.lights.length) {
  20459. this.lights[0].dispose();
  20460. }
  20461. // Release meshes
  20462. while (this.meshes.length) {
  20463. this.meshes[0].dispose(true);
  20464. }
  20465. // Release cameras
  20466. while (this.cameras.length) {
  20467. this.cameras[0].dispose();
  20468. }
  20469. // Release materials
  20470. if (this.defaultMaterial) {
  20471. this.defaultMaterial.dispose();
  20472. }
  20473. while (this.multiMaterials.length) {
  20474. this.multiMaterials[0].dispose();
  20475. }
  20476. while (this.materials.length) {
  20477. this.materials[0].dispose();
  20478. }
  20479. // Release particles
  20480. while (this.particleSystems.length) {
  20481. this.particleSystems[0].dispose();
  20482. }
  20483. // Release sprites
  20484. while (this.spriteManagers.length) {
  20485. this.spriteManagers[0].dispose();
  20486. }
  20487. // Release postProcesses
  20488. while (this.postProcesses.length) {
  20489. this.postProcesses[0].dispose();
  20490. }
  20491. // Release layers
  20492. while (this.layers.length) {
  20493. this.layers[0].dispose();
  20494. }
  20495. while (this.highlightLayers.length) {
  20496. this.highlightLayers[0].dispose();
  20497. }
  20498. // Release textures
  20499. while (this.textures.length) {
  20500. this.textures[0].dispose();
  20501. }
  20502. // Release UBO
  20503. this._sceneUbo.dispose();
  20504. if (this._alternateSceneUbo) {
  20505. this._alternateSceneUbo.dispose();
  20506. }
  20507. // Post-processes
  20508. this.postProcessManager.dispose();
  20509. if (this._postProcessRenderPipelineManager) {
  20510. this._postProcessRenderPipelineManager.dispose();
  20511. }
  20512. // Physics
  20513. if (this._physicsEngine) {
  20514. this.disablePhysicsEngine();
  20515. }
  20516. // Remove from engine
  20517. index = this._engine.scenes.indexOf(this);
  20518. if (index > -1) {
  20519. this._engine.scenes.splice(index, 1);
  20520. }
  20521. this._engine.wipeCaches();
  20522. this._isDisposed = true;
  20523. };
  20524. Object.defineProperty(Scene.prototype, "isDisposed", {
  20525. get: function () {
  20526. return this._isDisposed;
  20527. },
  20528. enumerable: true,
  20529. configurable: true
  20530. });
  20531. // Release sounds & sounds tracks
  20532. Scene.prototype.disposeSounds = function () {
  20533. if (!this._mainSoundTrack) {
  20534. return;
  20535. }
  20536. this.mainSoundTrack.dispose();
  20537. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20538. this.soundTracks[scIndex].dispose();
  20539. }
  20540. };
  20541. // Octrees
  20542. Scene.prototype.getWorldExtends = function () {
  20543. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20544. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20545. for (var index = 0; index < this.meshes.length; index++) {
  20546. var mesh = this.meshes[index];
  20547. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20548. continue;
  20549. }
  20550. mesh.computeWorldMatrix(true);
  20551. var boundingInfo = mesh.getBoundingInfo();
  20552. if (boundingInfo) {
  20553. var minBox = boundingInfo.boundingBox.minimumWorld;
  20554. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20555. BABYLON.Tools.CheckExtends(minBox, min, max);
  20556. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20557. }
  20558. }
  20559. return {
  20560. min: min,
  20561. max: max
  20562. };
  20563. };
  20564. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20565. if (maxCapacity === void 0) { maxCapacity = 64; }
  20566. if (maxDepth === void 0) { maxDepth = 2; }
  20567. if (!this._selectionOctree) {
  20568. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20569. }
  20570. var worldExtends = this.getWorldExtends();
  20571. // Update octree
  20572. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20573. return this._selectionOctree;
  20574. };
  20575. // Picking
  20576. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20577. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20578. var engine = this._engine;
  20579. if (!camera) {
  20580. if (!this.activeCamera)
  20581. throw new Error("Active camera not set");
  20582. camera = this.activeCamera;
  20583. }
  20584. var cameraViewport = camera.viewport;
  20585. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20586. // Moving coordinates to local viewport world
  20587. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20588. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20589. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20590. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20591. };
  20592. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20593. if (!BABYLON.PickingInfo) {
  20594. return null;
  20595. }
  20596. var engine = this._engine;
  20597. if (!camera) {
  20598. if (!this.activeCamera)
  20599. throw new Error("Active camera not set");
  20600. camera = this.activeCamera;
  20601. }
  20602. var cameraViewport = camera.viewport;
  20603. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20604. var identity = BABYLON.Matrix.Identity();
  20605. // Moving coordinates to local viewport world
  20606. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20607. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20608. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20609. };
  20610. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20611. if (!BABYLON.PickingInfo) {
  20612. return null;
  20613. }
  20614. var pickingInfo = null;
  20615. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20616. var mesh = this.meshes[meshIndex];
  20617. if (predicate) {
  20618. if (!predicate(mesh)) {
  20619. continue;
  20620. }
  20621. }
  20622. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20623. continue;
  20624. }
  20625. var world = mesh.getWorldMatrix();
  20626. var ray = rayFunction(world);
  20627. var result = mesh.intersects(ray, fastCheck);
  20628. if (!result || !result.hit)
  20629. continue;
  20630. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20631. continue;
  20632. pickingInfo = result;
  20633. if (fastCheck) {
  20634. break;
  20635. }
  20636. }
  20637. return pickingInfo || new BABYLON.PickingInfo();
  20638. };
  20639. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20640. if (!BABYLON.PickingInfo) {
  20641. return null;
  20642. }
  20643. var pickingInfos = new Array();
  20644. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20645. var mesh = this.meshes[meshIndex];
  20646. if (predicate) {
  20647. if (!predicate(mesh)) {
  20648. continue;
  20649. }
  20650. }
  20651. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20652. continue;
  20653. }
  20654. var world = mesh.getWorldMatrix();
  20655. var ray = rayFunction(world);
  20656. var result = mesh.intersects(ray, false);
  20657. if (!result || !result.hit)
  20658. continue;
  20659. pickingInfos.push(result);
  20660. }
  20661. return pickingInfos;
  20662. };
  20663. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20664. if (!BABYLON.PickingInfo) {
  20665. return null;
  20666. }
  20667. var pickingInfo = null;
  20668. if (!camera) {
  20669. if (!this.activeCamera) {
  20670. return null;
  20671. }
  20672. camera = this.activeCamera;
  20673. }
  20674. if (this.spriteManagers.length > 0) {
  20675. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20676. var spriteManager = this.spriteManagers[spriteIndex];
  20677. if (!spriteManager.isPickable) {
  20678. continue;
  20679. }
  20680. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20681. if (!result || !result.hit)
  20682. continue;
  20683. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20684. continue;
  20685. pickingInfo = result;
  20686. if (fastCheck) {
  20687. break;
  20688. }
  20689. }
  20690. }
  20691. return pickingInfo || new BABYLON.PickingInfo();
  20692. };
  20693. /** Launch a ray to try to pick a mesh in the scene
  20694. * @param x position on screen
  20695. * @param y position on screen
  20696. * @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
  20697. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20698. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20699. */
  20700. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20701. var _this = this;
  20702. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20703. };
  20704. /** Launch a ray to try to pick a sprite in the scene
  20705. * @param x position on screen
  20706. * @param y position on screen
  20707. * @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
  20708. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20709. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20710. */
  20711. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20712. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20713. if (!ray) {
  20714. return null;
  20715. }
  20716. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20717. };
  20718. /** Use the given ray to pick a mesh in the scene
  20719. * @param ray The ray to use to pick meshes
  20720. * @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
  20721. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20722. */
  20723. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20724. var _this = this;
  20725. return this._internalPick(function (world) {
  20726. if (!_this._pickWithRayInverseMatrix) {
  20727. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20728. }
  20729. world.invertToRef(_this._pickWithRayInverseMatrix);
  20730. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20731. }, predicate, fastCheck);
  20732. };
  20733. /**
  20734. * Launch a ray to try to pick a mesh in the scene
  20735. * @param x X position on screen
  20736. * @param y Y position on screen
  20737. * @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
  20738. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20739. */
  20740. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20741. var _this = this;
  20742. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20743. };
  20744. /**
  20745. * Launch a ray to try to pick a mesh in the scene
  20746. * @param ray Ray to use
  20747. * @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
  20748. */
  20749. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20750. var _this = this;
  20751. return this._internalMultiPick(function (world) {
  20752. if (!_this._pickWithRayInverseMatrix) {
  20753. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20754. }
  20755. world.invertToRef(_this._pickWithRayInverseMatrix);
  20756. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20757. }, predicate);
  20758. };
  20759. Scene.prototype.setPointerOverMesh = function (mesh) {
  20760. if (this._pointerOverMesh === mesh) {
  20761. return;
  20762. }
  20763. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20764. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20765. }
  20766. this._pointerOverMesh = mesh;
  20767. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20768. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20769. }
  20770. };
  20771. Scene.prototype.getPointerOverMesh = function () {
  20772. return this._pointerOverMesh;
  20773. };
  20774. Scene.prototype.setPointerOverSprite = function (sprite) {
  20775. if (this._pointerOverSprite === sprite) {
  20776. return;
  20777. }
  20778. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20779. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20780. }
  20781. this._pointerOverSprite = sprite;
  20782. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20783. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20784. }
  20785. };
  20786. Scene.prototype.getPointerOverSprite = function () {
  20787. return this._pointerOverSprite;
  20788. };
  20789. // Physics
  20790. Scene.prototype.getPhysicsEngine = function () {
  20791. return this._physicsEngine;
  20792. };
  20793. /**
  20794. * Enables physics to the current scene
  20795. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20796. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20797. * @return {boolean} was the physics engine initialized
  20798. */
  20799. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20800. if (gravity === void 0) { gravity = null; }
  20801. if (this._physicsEngine) {
  20802. return true;
  20803. }
  20804. try {
  20805. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20806. return true;
  20807. }
  20808. catch (e) {
  20809. BABYLON.Tools.Error(e.message);
  20810. return false;
  20811. }
  20812. };
  20813. Scene.prototype.disablePhysicsEngine = function () {
  20814. if (!this._physicsEngine) {
  20815. return;
  20816. }
  20817. this._physicsEngine.dispose();
  20818. this._physicsEngine = null;
  20819. };
  20820. Scene.prototype.isPhysicsEnabled = function () {
  20821. return this._physicsEngine !== undefined;
  20822. };
  20823. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20824. var mesh = compound.parts[0].mesh;
  20825. if (mesh.physicsImpostor) {
  20826. mesh.physicsImpostor.dispose();
  20827. mesh.physicsImpostor = null;
  20828. }
  20829. };
  20830. // Misc.
  20831. Scene.prototype._rebuildGeometries = function () {
  20832. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20833. var geometry = _a[_i];
  20834. geometry._rebuild();
  20835. }
  20836. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20837. var mesh = _c[_b];
  20838. mesh._rebuild();
  20839. }
  20840. if (this.postProcessManager) {
  20841. this.postProcessManager._rebuild();
  20842. }
  20843. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20844. var layer = _e[_d];
  20845. layer._rebuild();
  20846. }
  20847. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20848. var highlightLayer = _g[_f];
  20849. highlightLayer._rebuild();
  20850. }
  20851. if (this._boundingBoxRenderer) {
  20852. this._boundingBoxRenderer._rebuild();
  20853. }
  20854. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20855. var system = _j[_h];
  20856. system.rebuild();
  20857. }
  20858. if (this._postProcessRenderPipelineManager) {
  20859. this._postProcessRenderPipelineManager._rebuild();
  20860. }
  20861. };
  20862. Scene.prototype._rebuildTextures = function () {
  20863. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20864. var texture = _a[_i];
  20865. texture._rebuild();
  20866. }
  20867. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20868. };
  20869. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20870. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20871. if (replace === void 0) { replace = false; }
  20872. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20873. // Dispose existing camera or light in replace mode.
  20874. if (replace) {
  20875. if (this.activeCamera) {
  20876. this.activeCamera.dispose();
  20877. this.activeCamera = null;
  20878. }
  20879. if (this.lights) {
  20880. for (var i = 0; i < this.lights.length; i++) {
  20881. this.lights[i].dispose();
  20882. }
  20883. }
  20884. }
  20885. // Light
  20886. if (this.lights.length === 0) {
  20887. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20888. }
  20889. // Camera
  20890. if (!this.activeCamera) {
  20891. var worldExtends = this.getWorldExtends();
  20892. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20893. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20894. var camera;
  20895. var radius = worldSize.length() * 1.5;
  20896. if (createArcRotateCamera) {
  20897. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20898. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20899. arcRotateCamera.wheelPrecision = 100 / radius;
  20900. camera = arcRotateCamera;
  20901. }
  20902. else {
  20903. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20904. freeCamera.setTarget(worldCenter);
  20905. camera = freeCamera;
  20906. }
  20907. camera.minZ = radius * 0.01;
  20908. camera.maxZ = radius * 100;
  20909. camera.speed = radius * 0.2;
  20910. this.activeCamera = camera;
  20911. var canvas = this.getEngine().getRenderingCanvas();
  20912. if (attachCameraControls && canvas) {
  20913. camera.attachControl(canvas);
  20914. }
  20915. }
  20916. };
  20917. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20918. if (pbr === void 0) { pbr = false; }
  20919. if (scale === void 0) { scale = 1000; }
  20920. if (blur === void 0) { blur = 0; }
  20921. if (environmentTexture) {
  20922. this.environmentTexture = environmentTexture;
  20923. }
  20924. if (!this.environmentTexture) {
  20925. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20926. return null;
  20927. }
  20928. // Skybox
  20929. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20930. if (pbr) {
  20931. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20932. hdrSkyboxMaterial.backFaceCulling = false;
  20933. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20934. if (hdrSkyboxMaterial.reflectionTexture) {
  20935. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20936. }
  20937. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20938. hdrSkyboxMaterial.disableLighting = true;
  20939. hdrSkyboxMaterial.twoSidedLighting = true;
  20940. hdrSkybox.infiniteDistance = true;
  20941. hdrSkybox.material = hdrSkyboxMaterial;
  20942. }
  20943. else {
  20944. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20945. skyboxMaterial.backFaceCulling = false;
  20946. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20947. if (skyboxMaterial.reflectionTexture) {
  20948. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20949. }
  20950. skyboxMaterial.disableLighting = true;
  20951. hdrSkybox.infiniteDistance = true;
  20952. hdrSkybox.material = skyboxMaterial;
  20953. }
  20954. return hdrSkybox;
  20955. };
  20956. Scene.prototype.createDefaultEnvironment = function (options) {
  20957. if (BABYLON.EnvironmentHelper) {
  20958. return new BABYLON.EnvironmentHelper(options, this);
  20959. }
  20960. return null;
  20961. };
  20962. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20963. if (webVROptions === void 0) { webVROptions = {}; }
  20964. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20965. };
  20966. // Tags
  20967. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20968. if (tagsQuery === undefined) {
  20969. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20970. return list;
  20971. }
  20972. var listByTags = [];
  20973. forEach = forEach || (function (item) { return; });
  20974. for (var i in list) {
  20975. var item = list[i];
  20976. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20977. listByTags.push(item);
  20978. forEach(item);
  20979. }
  20980. }
  20981. return listByTags;
  20982. };
  20983. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20984. return this._getByTags(this.meshes, tagsQuery, forEach);
  20985. };
  20986. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20987. return this._getByTags(this.cameras, tagsQuery, forEach);
  20988. };
  20989. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20990. return this._getByTags(this.lights, tagsQuery, forEach);
  20991. };
  20992. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20993. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20994. };
  20995. /**
  20996. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20997. * This allowed control for front to back rendering or reversly depending of the special needs.
  20998. *
  20999. * @param renderingGroupId The rendering group id corresponding to its index
  21000. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21001. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21002. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21003. */
  21004. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21005. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21006. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21007. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21008. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21009. };
  21010. /**
  21011. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21012. *
  21013. * @param renderingGroupId The rendering group id corresponding to its index
  21014. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21015. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21016. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21017. */
  21018. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21019. if (depth === void 0) { depth = true; }
  21020. if (stencil === void 0) { stencil = true; }
  21021. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21022. };
  21023. /**
  21024. * Will flag all materials as dirty to trigger new shader compilation
  21025. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  21026. */
  21027. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  21028. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  21029. var material = _a[_i];
  21030. if (predicate && !predicate(material)) {
  21031. continue;
  21032. }
  21033. material.markAsDirty(flag);
  21034. }
  21035. };
  21036. // Statics
  21037. Scene._FOGMODE_NONE = 0;
  21038. Scene._FOGMODE_EXP = 1;
  21039. Scene._FOGMODE_EXP2 = 2;
  21040. Scene._FOGMODE_LINEAR = 3;
  21041. Scene._uniqueIdCounter = 0;
  21042. Scene.MinDeltaTime = 1.0;
  21043. Scene.MaxDeltaTime = 1000.0;
  21044. /** The distance in pixel that you have to move to prevent some events */
  21045. Scene.DragMovementThreshold = 10; // in pixels
  21046. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21047. Scene.LongPressDelay = 500; // in milliseconds
  21048. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21049. Scene.DoubleClickDelay = 300; // in milliseconds
  21050. /** If you need to check double click without raising a single click at first click, enable this flag */
  21051. Scene.ExclusiveDoubleClickMode = false;
  21052. return Scene;
  21053. }());
  21054. BABYLON.Scene = Scene;
  21055. })(BABYLON || (BABYLON = {}));
  21056. //# sourceMappingURL=babylon.scene.js.map
  21057. var BABYLON;
  21058. (function (BABYLON) {
  21059. var Buffer = /** @class */ (function () {
  21060. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21061. if (instanced === void 0) { instanced = false; }
  21062. if (engine instanceof BABYLON.Mesh) {
  21063. this._engine = engine.getScene().getEngine();
  21064. }
  21065. else {
  21066. this._engine = engine;
  21067. }
  21068. this._updatable = updatable;
  21069. this._data = data;
  21070. this._strideSize = stride;
  21071. if (!postponeInternalCreation) {
  21072. this.create();
  21073. }
  21074. this._instanced = instanced;
  21075. this._instanceDivisor = instanced ? 1 : 0;
  21076. }
  21077. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21078. // a lot of these parameters are ignored as they are overriden by the buffer
  21079. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21080. };
  21081. // Properties
  21082. Buffer.prototype.isUpdatable = function () {
  21083. return this._updatable;
  21084. };
  21085. Buffer.prototype.getData = function () {
  21086. return this._data;
  21087. };
  21088. Buffer.prototype.getBuffer = function () {
  21089. return this._buffer;
  21090. };
  21091. Buffer.prototype.getStrideSize = function () {
  21092. return this._strideSize;
  21093. };
  21094. Buffer.prototype.getIsInstanced = function () {
  21095. return this._instanced;
  21096. };
  21097. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21098. get: function () {
  21099. return this._instanceDivisor;
  21100. },
  21101. set: function (value) {
  21102. this._instanceDivisor = value;
  21103. if (value == 0) {
  21104. this._instanced = false;
  21105. }
  21106. else {
  21107. this._instanced = true;
  21108. }
  21109. },
  21110. enumerable: true,
  21111. configurable: true
  21112. });
  21113. // Methods
  21114. Buffer.prototype.create = function (data) {
  21115. if (data === void 0) { data = null; }
  21116. if (!data && this._buffer) {
  21117. return; // nothing to do
  21118. }
  21119. data = data || this._data;
  21120. if (!data) {
  21121. return;
  21122. }
  21123. if (!this._buffer) {
  21124. if (this._updatable) {
  21125. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21126. this._data = data;
  21127. }
  21128. else {
  21129. this._buffer = this._engine.createVertexBuffer(data);
  21130. }
  21131. }
  21132. else if (this._updatable) {
  21133. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21134. this._data = data;
  21135. }
  21136. };
  21137. Buffer.prototype._rebuild = function () {
  21138. this._buffer = null;
  21139. this.create(this._data);
  21140. };
  21141. Buffer.prototype.update = function (data) {
  21142. this.create(data);
  21143. };
  21144. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21145. if (!this._buffer) {
  21146. return;
  21147. }
  21148. if (this._updatable) {
  21149. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21150. this._data = null;
  21151. }
  21152. };
  21153. Buffer.prototype.dispose = function () {
  21154. if (!this._buffer) {
  21155. return;
  21156. }
  21157. if (this._engine._releaseBuffer(this._buffer)) {
  21158. this._buffer = null;
  21159. }
  21160. };
  21161. return Buffer;
  21162. }());
  21163. BABYLON.Buffer = Buffer;
  21164. })(BABYLON || (BABYLON = {}));
  21165. //# sourceMappingURL=babylon.buffer.js.map
  21166. var BABYLON;
  21167. (function (BABYLON) {
  21168. var VertexBuffer = /** @class */ (function () {
  21169. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21170. if (!stride) {
  21171. // Deduce stride from kind
  21172. switch (kind) {
  21173. case VertexBuffer.PositionKind:
  21174. stride = 3;
  21175. break;
  21176. case VertexBuffer.NormalKind:
  21177. stride = 3;
  21178. break;
  21179. case VertexBuffer.UVKind:
  21180. case VertexBuffer.UV2Kind:
  21181. case VertexBuffer.UV3Kind:
  21182. case VertexBuffer.UV4Kind:
  21183. case VertexBuffer.UV5Kind:
  21184. case VertexBuffer.UV6Kind:
  21185. stride = 2;
  21186. break;
  21187. case VertexBuffer.TangentKind:
  21188. case VertexBuffer.ColorKind:
  21189. stride = 4;
  21190. break;
  21191. case VertexBuffer.MatricesIndicesKind:
  21192. case VertexBuffer.MatricesIndicesExtraKind:
  21193. stride = 4;
  21194. break;
  21195. case VertexBuffer.MatricesWeightsKind:
  21196. case VertexBuffer.MatricesWeightsExtraKind:
  21197. default:
  21198. stride = 4;
  21199. break;
  21200. }
  21201. }
  21202. if (data instanceof BABYLON.Buffer) {
  21203. if (!stride) {
  21204. stride = data.getStrideSize();
  21205. }
  21206. this._buffer = data;
  21207. this._ownsBuffer = false;
  21208. }
  21209. else {
  21210. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21211. this._ownsBuffer = true;
  21212. }
  21213. this._stride = stride;
  21214. this._offset = offset ? offset : 0;
  21215. this._size = size ? size : stride;
  21216. this._kind = kind;
  21217. }
  21218. VertexBuffer.prototype._rebuild = function () {
  21219. if (!this._buffer) {
  21220. return;
  21221. }
  21222. this._buffer._rebuild();
  21223. };
  21224. /**
  21225. * Returns the kind of the VertexBuffer (string).
  21226. */
  21227. VertexBuffer.prototype.getKind = function () {
  21228. return this._kind;
  21229. };
  21230. // Properties
  21231. /**
  21232. * Boolean : is the VertexBuffer updatable ?
  21233. */
  21234. VertexBuffer.prototype.isUpdatable = function () {
  21235. return this._buffer.isUpdatable();
  21236. };
  21237. /**
  21238. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21239. */
  21240. VertexBuffer.prototype.getData = function () {
  21241. return this._buffer.getData();
  21242. };
  21243. /**
  21244. * Returns the WebGLBuffer associated to the VertexBuffer.
  21245. */
  21246. VertexBuffer.prototype.getBuffer = function () {
  21247. return this._buffer.getBuffer();
  21248. };
  21249. /**
  21250. * Returns the stride of the VertexBuffer (integer).
  21251. */
  21252. VertexBuffer.prototype.getStrideSize = function () {
  21253. return this._stride;
  21254. };
  21255. /**
  21256. * Returns the offset (integer).
  21257. */
  21258. VertexBuffer.prototype.getOffset = function () {
  21259. return this._offset;
  21260. };
  21261. /**
  21262. * Returns the VertexBuffer total size (integer).
  21263. */
  21264. VertexBuffer.prototype.getSize = function () {
  21265. return this._size;
  21266. };
  21267. /**
  21268. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21269. */
  21270. VertexBuffer.prototype.getIsInstanced = function () {
  21271. return this._buffer.getIsInstanced();
  21272. };
  21273. /**
  21274. * Returns the instancing divisor, zero for non-instanced (integer).
  21275. */
  21276. VertexBuffer.prototype.getInstanceDivisor = function () {
  21277. return this._buffer.instanceDivisor;
  21278. };
  21279. // Methods
  21280. /**
  21281. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21282. * Returns the created WebGLBuffer.
  21283. */
  21284. VertexBuffer.prototype.create = function (data) {
  21285. return this._buffer.create(data);
  21286. };
  21287. /**
  21288. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21289. * Returns the updated WebGLBuffer.
  21290. */
  21291. VertexBuffer.prototype.update = function (data) {
  21292. return this._buffer.update(data);
  21293. };
  21294. /**
  21295. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21296. * Returns the directly updated WebGLBuffer.
  21297. */
  21298. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21299. return this._buffer.updateDirectly(data, offset);
  21300. };
  21301. /**
  21302. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21303. */
  21304. VertexBuffer.prototype.dispose = function () {
  21305. if (this._ownsBuffer) {
  21306. this._buffer.dispose();
  21307. }
  21308. };
  21309. Object.defineProperty(VertexBuffer, "PositionKind", {
  21310. get: function () {
  21311. return VertexBuffer._PositionKind;
  21312. },
  21313. enumerable: true,
  21314. configurable: true
  21315. });
  21316. Object.defineProperty(VertexBuffer, "NormalKind", {
  21317. get: function () {
  21318. return VertexBuffer._NormalKind;
  21319. },
  21320. enumerable: true,
  21321. configurable: true
  21322. });
  21323. Object.defineProperty(VertexBuffer, "TangentKind", {
  21324. get: function () {
  21325. return VertexBuffer._TangentKind;
  21326. },
  21327. enumerable: true,
  21328. configurable: true
  21329. });
  21330. Object.defineProperty(VertexBuffer, "UVKind", {
  21331. get: function () {
  21332. return VertexBuffer._UVKind;
  21333. },
  21334. enumerable: true,
  21335. configurable: true
  21336. });
  21337. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21338. get: function () {
  21339. return VertexBuffer._UV2Kind;
  21340. },
  21341. enumerable: true,
  21342. configurable: true
  21343. });
  21344. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21345. get: function () {
  21346. return VertexBuffer._UV3Kind;
  21347. },
  21348. enumerable: true,
  21349. configurable: true
  21350. });
  21351. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21352. get: function () {
  21353. return VertexBuffer._UV4Kind;
  21354. },
  21355. enumerable: true,
  21356. configurable: true
  21357. });
  21358. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21359. get: function () {
  21360. return VertexBuffer._UV5Kind;
  21361. },
  21362. enumerable: true,
  21363. configurable: true
  21364. });
  21365. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21366. get: function () {
  21367. return VertexBuffer._UV6Kind;
  21368. },
  21369. enumerable: true,
  21370. configurable: true
  21371. });
  21372. Object.defineProperty(VertexBuffer, "ColorKind", {
  21373. get: function () {
  21374. return VertexBuffer._ColorKind;
  21375. },
  21376. enumerable: true,
  21377. configurable: true
  21378. });
  21379. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21380. get: function () {
  21381. return VertexBuffer._MatricesIndicesKind;
  21382. },
  21383. enumerable: true,
  21384. configurable: true
  21385. });
  21386. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21387. get: function () {
  21388. return VertexBuffer._MatricesWeightsKind;
  21389. },
  21390. enumerable: true,
  21391. configurable: true
  21392. });
  21393. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21394. get: function () {
  21395. return VertexBuffer._MatricesIndicesExtraKind;
  21396. },
  21397. enumerable: true,
  21398. configurable: true
  21399. });
  21400. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21401. get: function () {
  21402. return VertexBuffer._MatricesWeightsExtraKind;
  21403. },
  21404. enumerable: true,
  21405. configurable: true
  21406. });
  21407. // Enums
  21408. VertexBuffer._PositionKind = "position";
  21409. VertexBuffer._NormalKind = "normal";
  21410. VertexBuffer._TangentKind = "tangent";
  21411. VertexBuffer._UVKind = "uv";
  21412. VertexBuffer._UV2Kind = "uv2";
  21413. VertexBuffer._UV3Kind = "uv3";
  21414. VertexBuffer._UV4Kind = "uv4";
  21415. VertexBuffer._UV5Kind = "uv5";
  21416. VertexBuffer._UV6Kind = "uv6";
  21417. VertexBuffer._ColorKind = "color";
  21418. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21419. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21420. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21421. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21422. return VertexBuffer;
  21423. }());
  21424. BABYLON.VertexBuffer = VertexBuffer;
  21425. })(BABYLON || (BABYLON = {}));
  21426. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21427. var BABYLON;
  21428. (function (BABYLON) {
  21429. var InternalTexture = /** @class */ (function () {
  21430. function InternalTexture(engine, dataSource) {
  21431. this.onLoadedObservable = new BABYLON.Observable();
  21432. // Private
  21433. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21434. this._references = 1;
  21435. this._engine = engine;
  21436. this._dataSource = dataSource;
  21437. this._webGLTexture = engine._createTexture();
  21438. }
  21439. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21440. get: function () {
  21441. return this._dataSource;
  21442. },
  21443. enumerable: true,
  21444. configurable: true
  21445. });
  21446. InternalTexture.prototype.incrementReferences = function () {
  21447. this._references++;
  21448. };
  21449. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21450. if (depth === void 0) { depth = 1; }
  21451. this.width = width;
  21452. this.height = height;
  21453. this.depth = depth;
  21454. this.baseWidth = width;
  21455. this.baseHeight = height;
  21456. this.baseDepth = depth;
  21457. this._size = width * height * depth;
  21458. };
  21459. InternalTexture.prototype._rebuild = function () {
  21460. var _this = this;
  21461. var proxy;
  21462. this.isReady = false;
  21463. this._cachedCoordinatesMode = null;
  21464. this._cachedWrapU = null;
  21465. this._cachedWrapV = null;
  21466. this._cachedAnisotropicFilteringLevel = null;
  21467. switch (this._dataSource) {
  21468. case InternalTexture.DATASOURCE_TEMP:
  21469. return;
  21470. case InternalTexture.DATASOURCE_URL:
  21471. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21472. _this.isReady = true;
  21473. }, null, this._buffer, undefined, this.format);
  21474. proxy._swapAndDie(this);
  21475. return;
  21476. case InternalTexture.DATASOURCE_RAW:
  21477. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21478. proxy._swapAndDie(this);
  21479. this.isReady = true;
  21480. return;
  21481. case InternalTexture.DATASOURCE_RAW3D:
  21482. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21483. proxy._swapAndDie(this);
  21484. this.isReady = true;
  21485. return;
  21486. case InternalTexture.DATASOURCE_DYNAMIC:
  21487. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21488. proxy._swapAndDie(this);
  21489. // The engine will make sure to update content so no need to flag it as isReady = true
  21490. return;
  21491. case InternalTexture.DATASOURCE_RENDERTARGET:
  21492. var options = new BABYLON.RenderTargetCreationOptions();
  21493. options.generateDepthBuffer = this._generateDepthBuffer;
  21494. options.generateMipMaps = this.generateMipMaps;
  21495. options.generateStencilBuffer = this._generateStencilBuffer;
  21496. options.samplingMode = this.samplingMode;
  21497. options.type = this.type;
  21498. if (this.isCube) {
  21499. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21500. }
  21501. else {
  21502. var size = {
  21503. width: this.width,
  21504. height: this.height
  21505. };
  21506. proxy = this._engine.createRenderTargetTexture(size, options);
  21507. }
  21508. proxy._swapAndDie(this);
  21509. this.isReady = true;
  21510. return;
  21511. case InternalTexture.DATASOURCE_CUBE:
  21512. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21513. _this.isReady = true;
  21514. }, null, this.format, this._extension);
  21515. proxy._swapAndDie(this);
  21516. return;
  21517. case InternalTexture.DATASOURCE_CUBERAW:
  21518. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21519. proxy._swapAndDie(this);
  21520. this.isReady = true;
  21521. return;
  21522. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21523. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21524. if (proxy) {
  21525. proxy._swapAndDie(_this);
  21526. }
  21527. _this.isReady = true;
  21528. }, null, this.format, this._extension);
  21529. return;
  21530. }
  21531. };
  21532. InternalTexture.prototype._swapAndDie = function (target) {
  21533. target._webGLTexture = this._webGLTexture;
  21534. if (this._framebuffer) {
  21535. target._framebuffer = this._framebuffer;
  21536. }
  21537. if (this._depthStencilBuffer) {
  21538. target._depthStencilBuffer = this._depthStencilBuffer;
  21539. }
  21540. if (this._lodTextureHigh) {
  21541. if (target._lodTextureHigh) {
  21542. target._lodTextureHigh.dispose();
  21543. }
  21544. target._lodTextureHigh = this._lodTextureHigh;
  21545. }
  21546. if (this._lodTextureMid) {
  21547. if (target._lodTextureMid) {
  21548. target._lodTextureMid.dispose();
  21549. }
  21550. target._lodTextureMid = this._lodTextureMid;
  21551. }
  21552. if (this._lodTextureLow) {
  21553. if (target._lodTextureLow) {
  21554. target._lodTextureLow.dispose();
  21555. }
  21556. target._lodTextureLow = this._lodTextureLow;
  21557. }
  21558. var cache = this._engine.getLoadedTexturesCache();
  21559. var index = cache.indexOf(this);
  21560. if (index !== -1) {
  21561. cache.splice(index, 1);
  21562. }
  21563. };
  21564. InternalTexture.prototype.dispose = function () {
  21565. if (!this._webGLTexture) {
  21566. return;
  21567. }
  21568. this._references--;
  21569. if (this._references === 0) {
  21570. this._engine._releaseTexture(this);
  21571. this._webGLTexture = null;
  21572. }
  21573. };
  21574. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21575. InternalTexture.DATASOURCE_URL = 1;
  21576. InternalTexture.DATASOURCE_TEMP = 2;
  21577. InternalTexture.DATASOURCE_RAW = 3;
  21578. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21579. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21580. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21581. InternalTexture.DATASOURCE_CUBE = 7;
  21582. InternalTexture.DATASOURCE_CUBERAW = 8;
  21583. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21584. InternalTexture.DATASOURCE_RAW3D = 10;
  21585. return InternalTexture;
  21586. }());
  21587. BABYLON.InternalTexture = InternalTexture;
  21588. })(BABYLON || (BABYLON = {}));
  21589. //# sourceMappingURL=babylon.internalTexture.js.map
  21590. var BABYLON;
  21591. (function (BABYLON) {
  21592. var BaseTexture = /** @class */ (function () {
  21593. function BaseTexture(scene) {
  21594. this._hasAlpha = false;
  21595. this.getAlphaFromRGB = false;
  21596. this.level = 1;
  21597. this.coordinatesIndex = 0;
  21598. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21599. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21600. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21601. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  21602. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21603. this.isCube = false;
  21604. this.is3D = false;
  21605. this.gammaSpace = true;
  21606. this.invertZ = false;
  21607. this.lodLevelInAlpha = false;
  21608. this.lodGenerationOffset = 0.0;
  21609. this.lodGenerationScale = 0.8;
  21610. this.isRenderTarget = false;
  21611. this.animations = new Array();
  21612. /**
  21613. * An event triggered when the texture is disposed.
  21614. * @type {BABYLON.Observable}
  21615. */
  21616. this.onDisposeObservable = new BABYLON.Observable();
  21617. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21618. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21619. if (this._scene) {
  21620. this._scene.textures.push(this);
  21621. }
  21622. this._uid = null;
  21623. }
  21624. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21625. get: function () {
  21626. return this._hasAlpha;
  21627. },
  21628. set: function (value) {
  21629. if (this._hasAlpha === value) {
  21630. return;
  21631. }
  21632. this._hasAlpha = value;
  21633. if (this._scene) {
  21634. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21635. }
  21636. },
  21637. enumerable: true,
  21638. configurable: true
  21639. });
  21640. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  21641. get: function () {
  21642. return this._coordinatesMode;
  21643. },
  21644. set: function (value) {
  21645. if (this._coordinatesMode === value) {
  21646. return;
  21647. }
  21648. this._coordinatesMode = value;
  21649. if (this._scene) {
  21650. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21651. }
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Object.defineProperty(BaseTexture.prototype, "uid", {
  21657. get: function () {
  21658. if (!this._uid) {
  21659. this._uid = BABYLON.Tools.RandomId();
  21660. }
  21661. return this._uid;
  21662. },
  21663. enumerable: true,
  21664. configurable: true
  21665. });
  21666. BaseTexture.prototype.toString = function () {
  21667. return this.name;
  21668. };
  21669. BaseTexture.prototype.getClassName = function () {
  21670. return "BaseTexture";
  21671. };
  21672. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21673. set: function (callback) {
  21674. if (this._onDisposeObserver) {
  21675. this.onDisposeObservable.remove(this._onDisposeObserver);
  21676. }
  21677. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21678. },
  21679. enumerable: true,
  21680. configurable: true
  21681. });
  21682. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21683. get: function () {
  21684. return true;
  21685. },
  21686. enumerable: true,
  21687. configurable: true
  21688. });
  21689. BaseTexture.prototype.getScene = function () {
  21690. return this._scene;
  21691. };
  21692. BaseTexture.prototype.getTextureMatrix = function () {
  21693. return BABYLON.Matrix.IdentityReadOnly;
  21694. };
  21695. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21696. return BABYLON.Matrix.IdentityReadOnly;
  21697. };
  21698. BaseTexture.prototype.getInternalTexture = function () {
  21699. return this._texture;
  21700. };
  21701. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21702. return !this.isBlocking || this.isReady();
  21703. };
  21704. BaseTexture.prototype.isReady = function () {
  21705. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21706. this.delayLoad();
  21707. return false;
  21708. }
  21709. if (this._texture) {
  21710. return this._texture.isReady;
  21711. }
  21712. return false;
  21713. };
  21714. BaseTexture.prototype.getSize = function () {
  21715. if (this._texture && this._texture.width) {
  21716. return new BABYLON.Size(this._texture.width, this._texture.height);
  21717. }
  21718. if (this._texture && this._texture._size) {
  21719. return new BABYLON.Size(this._texture._size, this._texture._size);
  21720. }
  21721. return BABYLON.Size.Zero();
  21722. };
  21723. BaseTexture.prototype.getBaseSize = function () {
  21724. if (!this.isReady() || !this._texture)
  21725. return BABYLON.Size.Zero();
  21726. if (this._texture._size) {
  21727. return new BABYLON.Size(this._texture._size, this._texture._size);
  21728. }
  21729. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21730. };
  21731. BaseTexture.prototype.scale = function (ratio) {
  21732. };
  21733. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21734. get: function () {
  21735. return false;
  21736. },
  21737. enumerable: true,
  21738. configurable: true
  21739. });
  21740. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21741. if (!this._scene) {
  21742. return null;
  21743. }
  21744. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21745. for (var index = 0; index < texturesCache.length; index++) {
  21746. var texturesCacheEntry = texturesCache[index];
  21747. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21748. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21749. texturesCacheEntry.incrementReferences();
  21750. return texturesCacheEntry;
  21751. }
  21752. }
  21753. }
  21754. return null;
  21755. };
  21756. BaseTexture.prototype._rebuild = function () {
  21757. };
  21758. BaseTexture.prototype.delayLoad = function () {
  21759. };
  21760. BaseTexture.prototype.clone = function () {
  21761. return null;
  21762. };
  21763. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21764. get: function () {
  21765. if (!this._texture) {
  21766. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21767. }
  21768. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21769. },
  21770. enumerable: true,
  21771. configurable: true
  21772. });
  21773. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21774. get: function () {
  21775. if (!this._texture) {
  21776. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21777. }
  21778. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21779. },
  21780. enumerable: true,
  21781. configurable: true
  21782. });
  21783. BaseTexture.prototype.readPixels = function (faceIndex) {
  21784. if (faceIndex === void 0) { faceIndex = 0; }
  21785. if (!this._texture) {
  21786. return null;
  21787. }
  21788. var size = this.getSize();
  21789. var scene = this.getScene();
  21790. if (!scene) {
  21791. return null;
  21792. }
  21793. var engine = scene.getEngine();
  21794. if (this._texture.isCube) {
  21795. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21796. }
  21797. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21798. };
  21799. BaseTexture.prototype.releaseInternalTexture = function () {
  21800. if (this._texture) {
  21801. this._texture.dispose();
  21802. this._texture = null;
  21803. }
  21804. };
  21805. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21806. get: function () {
  21807. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21808. return null;
  21809. }
  21810. if (!this._texture._sphericalPolynomial) {
  21811. this._texture._sphericalPolynomial =
  21812. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21813. }
  21814. return this._texture._sphericalPolynomial;
  21815. },
  21816. set: function (value) {
  21817. if (this._texture) {
  21818. this._texture._sphericalPolynomial = value;
  21819. }
  21820. },
  21821. enumerable: true,
  21822. configurable: true
  21823. });
  21824. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21825. get: function () {
  21826. if (this._texture) {
  21827. return this._texture._lodTextureHigh;
  21828. }
  21829. return null;
  21830. },
  21831. enumerable: true,
  21832. configurable: true
  21833. });
  21834. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21835. get: function () {
  21836. if (this._texture) {
  21837. return this._texture._lodTextureMid;
  21838. }
  21839. return null;
  21840. },
  21841. enumerable: true,
  21842. configurable: true
  21843. });
  21844. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21845. get: function () {
  21846. if (this._texture) {
  21847. return this._texture._lodTextureLow;
  21848. }
  21849. return null;
  21850. },
  21851. enumerable: true,
  21852. configurable: true
  21853. });
  21854. BaseTexture.prototype.dispose = function () {
  21855. if (!this._scene) {
  21856. return;
  21857. }
  21858. // Animations
  21859. this._scene.stopAnimation(this);
  21860. // Remove from scene
  21861. this._scene._removePendingData(this);
  21862. var index = this._scene.textures.indexOf(this);
  21863. if (index >= 0) {
  21864. this._scene.textures.splice(index, 1);
  21865. }
  21866. if (this._texture === undefined) {
  21867. return;
  21868. }
  21869. // Release
  21870. this.releaseInternalTexture();
  21871. // Callback
  21872. this.onDisposeObservable.notifyObservers(this);
  21873. this.onDisposeObservable.clear();
  21874. };
  21875. BaseTexture.prototype.serialize = function () {
  21876. if (!this.name) {
  21877. return null;
  21878. }
  21879. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21880. // Animations
  21881. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21882. return serializationObject;
  21883. };
  21884. BaseTexture.WhenAllReady = function (textures, callback) {
  21885. var numRemaining = textures.length;
  21886. if (numRemaining === 0) {
  21887. callback();
  21888. return;
  21889. }
  21890. var _loop_1 = function () {
  21891. texture = textures[i];
  21892. if (texture.isReady()) {
  21893. if (--numRemaining === 0) {
  21894. callback();
  21895. }
  21896. }
  21897. else {
  21898. onLoadObservable = texture.onLoadObservable;
  21899. var onLoadCallback_1 = function () {
  21900. onLoadObservable.removeCallback(onLoadCallback_1);
  21901. if (--numRemaining === 0) {
  21902. callback();
  21903. }
  21904. };
  21905. onLoadObservable.add(onLoadCallback_1);
  21906. }
  21907. };
  21908. var texture, onLoadObservable;
  21909. for (var i = 0; i < textures.length; i++) {
  21910. _loop_1();
  21911. }
  21912. };
  21913. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21914. __decorate([
  21915. BABYLON.serialize()
  21916. ], BaseTexture.prototype, "name", void 0);
  21917. __decorate([
  21918. BABYLON.serialize("hasAlpha")
  21919. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21920. __decorate([
  21921. BABYLON.serialize()
  21922. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21923. __decorate([
  21924. BABYLON.serialize()
  21925. ], BaseTexture.prototype, "level", void 0);
  21926. __decorate([
  21927. BABYLON.serialize()
  21928. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21929. __decorate([
  21930. BABYLON.serialize("coordinatesMode")
  21931. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21932. __decorate([
  21933. BABYLON.serialize()
  21934. ], BaseTexture.prototype, "wrapU", void 0);
  21935. __decorate([
  21936. BABYLON.serialize()
  21937. ], BaseTexture.prototype, "wrapV", void 0);
  21938. __decorate([
  21939. BABYLON.serialize()
  21940. ], BaseTexture.prototype, "wrapR", void 0);
  21941. __decorate([
  21942. BABYLON.serialize()
  21943. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21944. __decorate([
  21945. BABYLON.serialize()
  21946. ], BaseTexture.prototype, "isCube", void 0);
  21947. __decorate([
  21948. BABYLON.serialize()
  21949. ], BaseTexture.prototype, "is3D", void 0);
  21950. __decorate([
  21951. BABYLON.serialize()
  21952. ], BaseTexture.prototype, "gammaSpace", void 0);
  21953. __decorate([
  21954. BABYLON.serialize()
  21955. ], BaseTexture.prototype, "invertZ", void 0);
  21956. __decorate([
  21957. BABYLON.serialize()
  21958. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21959. __decorate([
  21960. BABYLON.serialize()
  21961. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21962. __decorate([
  21963. BABYLON.serialize()
  21964. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21965. __decorate([
  21966. BABYLON.serialize()
  21967. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21968. return BaseTexture;
  21969. }());
  21970. BABYLON.BaseTexture = BaseTexture;
  21971. })(BABYLON || (BABYLON = {}));
  21972. //# sourceMappingURL=babylon.baseTexture.js.map
  21973. var BABYLON;
  21974. (function (BABYLON) {
  21975. var Texture = /** @class */ (function (_super) {
  21976. __extends(Texture, _super);
  21977. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21978. if (noMipmap === void 0) { noMipmap = false; }
  21979. if (invertY === void 0) { invertY = true; }
  21980. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21981. if (onLoad === void 0) { onLoad = null; }
  21982. if (onError === void 0) { onError = null; }
  21983. if (buffer === void 0) { buffer = null; }
  21984. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21985. var _this = _super.call(this, scene) || this;
  21986. _this.uOffset = 0;
  21987. _this.vOffset = 0;
  21988. _this.uScale = 1.0;
  21989. _this.vScale = 1.0;
  21990. _this.uAng = 0;
  21991. _this.vAng = 0;
  21992. _this.wAng = 0;
  21993. _this._isBlocking = true;
  21994. _this.name = url || "";
  21995. _this.url = url;
  21996. _this._noMipmap = noMipmap;
  21997. _this._invertY = invertY;
  21998. _this._samplingMode = samplingMode;
  21999. _this._buffer = buffer;
  22000. _this._deleteBuffer = deleteBuffer;
  22001. if (format) {
  22002. _this._format = format;
  22003. }
  22004. scene = _this.getScene();
  22005. if (!scene) {
  22006. return _this;
  22007. }
  22008. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  22009. var load = function () {
  22010. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  22011. _this.onLoadObservable.notifyObservers(_this);
  22012. }
  22013. if (onLoad) {
  22014. onLoad();
  22015. }
  22016. if (!_this.isBlocking && scene) {
  22017. scene.resetCachedMaterial();
  22018. }
  22019. };
  22020. if (!_this.url) {
  22021. _this._delayedOnLoad = load;
  22022. _this._delayedOnError = onError;
  22023. return _this;
  22024. }
  22025. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  22026. if (!_this._texture) {
  22027. if (!scene.useDelayedTextureLoading) {
  22028. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  22029. if (deleteBuffer) {
  22030. delete _this._buffer;
  22031. }
  22032. }
  22033. else {
  22034. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22035. _this._delayedOnLoad = load;
  22036. _this._delayedOnError = onError;
  22037. }
  22038. }
  22039. else {
  22040. if (_this._texture.isReady) {
  22041. BABYLON.Tools.SetImmediate(function () { return load(); });
  22042. }
  22043. else {
  22044. _this._texture.onLoadedObservable.add(load);
  22045. }
  22046. }
  22047. return _this;
  22048. }
  22049. Object.defineProperty(Texture.prototype, "noMipmap", {
  22050. get: function () {
  22051. return this._noMipmap;
  22052. },
  22053. enumerable: true,
  22054. configurable: true
  22055. });
  22056. Object.defineProperty(Texture.prototype, "isBlocking", {
  22057. get: function () {
  22058. return this._isBlocking;
  22059. },
  22060. set: function (value) {
  22061. this._isBlocking = value;
  22062. },
  22063. enumerable: true,
  22064. configurable: true
  22065. });
  22066. Object.defineProperty(Texture.prototype, "samplingMode", {
  22067. get: function () {
  22068. return this._samplingMode;
  22069. },
  22070. enumerable: true,
  22071. configurable: true
  22072. });
  22073. Texture.prototype.updateURL = function (url) {
  22074. this.url = url;
  22075. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22076. this.delayLoad();
  22077. };
  22078. Texture.prototype.delayLoad = function () {
  22079. var _this = this;
  22080. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22081. return;
  22082. }
  22083. var scene = this.getScene();
  22084. if (!scene) {
  22085. return;
  22086. }
  22087. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22088. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22089. if (!this._texture) {
  22090. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22091. if (this._deleteBuffer) {
  22092. delete this._buffer;
  22093. }
  22094. }
  22095. else {
  22096. if (this._texture.isReady) {
  22097. BABYLON.Tools.SetImmediate(function () {
  22098. if (!_this._delayedOnLoad) {
  22099. return;
  22100. }
  22101. _this._delayedOnLoad();
  22102. });
  22103. }
  22104. else {
  22105. if (this._delayedOnLoad) {
  22106. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22107. }
  22108. }
  22109. }
  22110. };
  22111. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22112. if (!this._texture) {
  22113. return;
  22114. }
  22115. var scene = this.getScene();
  22116. if (!scene) {
  22117. return;
  22118. }
  22119. this._samplingMode = samplingMode;
  22120. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22121. };
  22122. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22123. x *= this.uScale;
  22124. y *= this.vScale;
  22125. x -= 0.5 * this.uScale;
  22126. y -= 0.5 * this.vScale;
  22127. z -= 0.5;
  22128. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22129. t.x += 0.5 * this.uScale + this.uOffset;
  22130. t.y += 0.5 * this.vScale + this.vOffset;
  22131. t.z += 0.5;
  22132. };
  22133. Texture.prototype.getTextureMatrix = function () {
  22134. var _this = this;
  22135. if (this.uOffset === this._cachedUOffset &&
  22136. this.vOffset === this._cachedVOffset &&
  22137. this.uScale === this._cachedUScale &&
  22138. this.vScale === this._cachedVScale &&
  22139. this.uAng === this._cachedUAng &&
  22140. this.vAng === this._cachedVAng &&
  22141. this.wAng === this._cachedWAng) {
  22142. return this._cachedTextureMatrix;
  22143. }
  22144. this._cachedUOffset = this.uOffset;
  22145. this._cachedVOffset = this.vOffset;
  22146. this._cachedUScale = this.uScale;
  22147. this._cachedVScale = this.vScale;
  22148. this._cachedUAng = this.uAng;
  22149. this._cachedVAng = this.vAng;
  22150. this._cachedWAng = this.wAng;
  22151. if (!this._cachedTextureMatrix) {
  22152. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22153. this._rowGenerationMatrix = new BABYLON.Matrix();
  22154. this._t0 = BABYLON.Vector3.Zero();
  22155. this._t1 = BABYLON.Vector3.Zero();
  22156. this._t2 = BABYLON.Vector3.Zero();
  22157. }
  22158. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22159. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22160. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22161. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22162. this._t1.subtractInPlace(this._t0);
  22163. this._t2.subtractInPlace(this._t0);
  22164. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22165. this._cachedTextureMatrix.m[0] = this._t1.x;
  22166. this._cachedTextureMatrix.m[1] = this._t1.y;
  22167. this._cachedTextureMatrix.m[2] = this._t1.z;
  22168. this._cachedTextureMatrix.m[4] = this._t2.x;
  22169. this._cachedTextureMatrix.m[5] = this._t2.y;
  22170. this._cachedTextureMatrix.m[6] = this._t2.z;
  22171. this._cachedTextureMatrix.m[8] = this._t0.x;
  22172. this._cachedTextureMatrix.m[9] = this._t0.y;
  22173. this._cachedTextureMatrix.m[10] = this._t0.z;
  22174. var scene = this.getScene();
  22175. if (!scene) {
  22176. return this._cachedTextureMatrix;
  22177. }
  22178. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22179. return mat.hasTexture(_this);
  22180. });
  22181. return this._cachedTextureMatrix;
  22182. };
  22183. Texture.prototype.getReflectionTextureMatrix = function () {
  22184. var _this = this;
  22185. var scene = this.getScene();
  22186. if (!scene) {
  22187. return this._cachedTextureMatrix;
  22188. }
  22189. if (this.uOffset === this._cachedUOffset &&
  22190. this.vOffset === this._cachedVOffset &&
  22191. this.uScale === this._cachedUScale &&
  22192. this.vScale === this._cachedVScale &&
  22193. this.coordinatesMode === this._cachedCoordinatesMode) {
  22194. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22195. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22196. return this._cachedTextureMatrix;
  22197. }
  22198. }
  22199. else {
  22200. return this._cachedTextureMatrix;
  22201. }
  22202. }
  22203. if (!this._cachedTextureMatrix) {
  22204. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22205. }
  22206. if (!this._projectionModeMatrix) {
  22207. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22208. }
  22209. this._cachedUOffset = this.uOffset;
  22210. this._cachedVOffset = this.vOffset;
  22211. this._cachedUScale = this.uScale;
  22212. this._cachedVScale = this.vScale;
  22213. this._cachedCoordinatesMode = this.coordinatesMode;
  22214. switch (this.coordinatesMode) {
  22215. case Texture.PLANAR_MODE:
  22216. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22217. this._cachedTextureMatrix[0] = this.uScale;
  22218. this._cachedTextureMatrix[5] = this.vScale;
  22219. this._cachedTextureMatrix[12] = this.uOffset;
  22220. this._cachedTextureMatrix[13] = this.vOffset;
  22221. break;
  22222. case Texture.PROJECTION_MODE:
  22223. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22224. this._projectionModeMatrix.m[0] = 0.5;
  22225. this._projectionModeMatrix.m[5] = -0.5;
  22226. this._projectionModeMatrix.m[10] = 0.0;
  22227. this._projectionModeMatrix.m[12] = 0.5;
  22228. this._projectionModeMatrix.m[13] = 0.5;
  22229. this._projectionModeMatrix.m[14] = 1.0;
  22230. this._projectionModeMatrix.m[15] = 1.0;
  22231. var projectionMatrix = scene.getProjectionMatrix();
  22232. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22233. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22234. break;
  22235. default:
  22236. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22237. break;
  22238. }
  22239. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22240. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22241. });
  22242. return this._cachedTextureMatrix;
  22243. };
  22244. Texture.prototype.clone = function () {
  22245. var _this = this;
  22246. return BABYLON.SerializationHelper.Clone(function () {
  22247. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22248. }, this);
  22249. };
  22250. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22251. get: function () {
  22252. if (!this._onLoadObservable) {
  22253. this._onLoadObservable = new BABYLON.Observable();
  22254. }
  22255. return this._onLoadObservable;
  22256. },
  22257. enumerable: true,
  22258. configurable: true
  22259. });
  22260. Texture.prototype.serialize = function () {
  22261. var serializationObject = _super.prototype.serialize.call(this);
  22262. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22263. serializationObject.base64String = this._buffer;
  22264. serializationObject.name = serializationObject.name.replace("data:", "");
  22265. }
  22266. return serializationObject;
  22267. };
  22268. Texture.prototype.getClassName = function () {
  22269. return "Texture";
  22270. };
  22271. Texture.prototype.dispose = function () {
  22272. _super.prototype.dispose.call(this);
  22273. if (this.onLoadObservable) {
  22274. this.onLoadObservable.clear();
  22275. this._onLoadObservable = null;
  22276. }
  22277. this._delayedOnLoad = null;
  22278. this._delayedOnError = null;
  22279. };
  22280. // Statics
  22281. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22282. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22283. if (onLoad === void 0) { onLoad = null; }
  22284. if (onError === void 0) { onError = null; }
  22285. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22286. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22287. };
  22288. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22289. if (parsedTexture.customType) {
  22290. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22291. // Update Sampling Mode
  22292. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22293. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22294. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22295. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22296. }
  22297. }
  22298. return parsedCustomTexture;
  22299. }
  22300. if (parsedTexture.isCube) {
  22301. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22302. }
  22303. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22304. return null;
  22305. }
  22306. var texture = BABYLON.SerializationHelper.Parse(function () {
  22307. if (parsedTexture.mirrorPlane) {
  22308. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22309. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22310. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22311. return mirrorTexture;
  22312. }
  22313. else if (parsedTexture.isRenderTarget) {
  22314. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22315. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22316. return renderTargetTexture;
  22317. }
  22318. else {
  22319. var texture;
  22320. if (parsedTexture.base64String) {
  22321. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22322. }
  22323. else {
  22324. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22325. }
  22326. return texture;
  22327. }
  22328. }, parsedTexture, scene);
  22329. // Update Sampling Mode
  22330. if (parsedTexture.samplingMode) {
  22331. var sampling = parsedTexture.samplingMode;
  22332. if (texture._samplingMode !== sampling) {
  22333. texture.updateSamplingMode(sampling);
  22334. }
  22335. }
  22336. // Animations
  22337. if (parsedTexture.animations) {
  22338. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22339. var parsedAnimation = parsedTexture.animations[animationIndex];
  22340. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22341. }
  22342. }
  22343. return texture;
  22344. };
  22345. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22346. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22347. if (noMipmap === void 0) { noMipmap = false; }
  22348. if (invertY === void 0) { invertY = true; }
  22349. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22350. if (onLoad === void 0) { onLoad = null; }
  22351. if (onError === void 0) { onError = null; }
  22352. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22353. if (name.substr(0, 5) !== "data:") {
  22354. name = "data:" + name;
  22355. }
  22356. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22357. };
  22358. // Constants
  22359. Texture.NEAREST_SAMPLINGMODE = 1;
  22360. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22361. Texture.BILINEAR_SAMPLINGMODE = 2;
  22362. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22363. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22364. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22365. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22366. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22367. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22368. Texture.NEAREST_LINEAR = 7;
  22369. Texture.NEAREST_NEAREST = 8;
  22370. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22371. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22372. Texture.LINEAR_LINEAR = 11;
  22373. Texture.LINEAR_NEAREST = 12;
  22374. Texture.EXPLICIT_MODE = 0;
  22375. Texture.SPHERICAL_MODE = 1;
  22376. Texture.PLANAR_MODE = 2;
  22377. Texture.CUBIC_MODE = 3;
  22378. Texture.PROJECTION_MODE = 4;
  22379. Texture.SKYBOX_MODE = 5;
  22380. Texture.INVCUBIC_MODE = 6;
  22381. Texture.EQUIRECTANGULAR_MODE = 7;
  22382. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22383. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22384. Texture.CLAMP_ADDRESSMODE = 0;
  22385. Texture.WRAP_ADDRESSMODE = 1;
  22386. Texture.MIRROR_ADDRESSMODE = 2;
  22387. __decorate([
  22388. BABYLON.serialize()
  22389. ], Texture.prototype, "url", void 0);
  22390. __decorate([
  22391. BABYLON.serialize()
  22392. ], Texture.prototype, "uOffset", void 0);
  22393. __decorate([
  22394. BABYLON.serialize()
  22395. ], Texture.prototype, "vOffset", void 0);
  22396. __decorate([
  22397. BABYLON.serialize()
  22398. ], Texture.prototype, "uScale", void 0);
  22399. __decorate([
  22400. BABYLON.serialize()
  22401. ], Texture.prototype, "vScale", void 0);
  22402. __decorate([
  22403. BABYLON.serialize()
  22404. ], Texture.prototype, "uAng", void 0);
  22405. __decorate([
  22406. BABYLON.serialize()
  22407. ], Texture.prototype, "vAng", void 0);
  22408. __decorate([
  22409. BABYLON.serialize()
  22410. ], Texture.prototype, "wAng", void 0);
  22411. __decorate([
  22412. BABYLON.serialize()
  22413. ], Texture.prototype, "isBlocking", null);
  22414. return Texture;
  22415. }(BABYLON.BaseTexture));
  22416. BABYLON.Texture = Texture;
  22417. })(BABYLON || (BABYLON = {}));
  22418. //# sourceMappingURL=babylon.texture.js.map
  22419. var BABYLON;
  22420. (function (BABYLON) {
  22421. var _InstancesBatch = /** @class */ (function () {
  22422. function _InstancesBatch() {
  22423. this.mustReturn = false;
  22424. this.visibleInstances = new Array();
  22425. this.renderSelf = new Array();
  22426. }
  22427. return _InstancesBatch;
  22428. }());
  22429. BABYLON._InstancesBatch = _InstancesBatch;
  22430. var Mesh = /** @class */ (function (_super) {
  22431. __extends(Mesh, _super);
  22432. /**
  22433. * @constructor
  22434. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22435. * @param {Scene} scene The scene to add this mesh to.
  22436. * @param {Node} parent The parent of this mesh, if it has one
  22437. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22438. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22439. * When false, achieved by calling a clone(), also passing False.
  22440. * This will make creation of children, recursive.
  22441. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22442. */
  22443. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22444. if (scene === void 0) { scene = null; }
  22445. if (parent === void 0) { parent = null; }
  22446. if (source === void 0) { source = null; }
  22447. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22448. var _this = _super.call(this, name, scene) || this;
  22449. // Events
  22450. /**
  22451. * An event triggered before rendering the mesh
  22452. * @type {BABYLON.Observable}
  22453. */
  22454. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22455. /**
  22456. * An event triggered after rendering the mesh
  22457. * @type {BABYLON.Observable}
  22458. */
  22459. _this.onAfterRenderObservable = new BABYLON.Observable();
  22460. /**
  22461. * An event triggered before drawing the mesh
  22462. * @type {BABYLON.Observable}
  22463. */
  22464. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22465. // Members
  22466. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22467. _this.instances = new Array();
  22468. _this._LODLevels = new Array();
  22469. _this._visibleInstances = {};
  22470. _this._renderIdForInstances = new Array();
  22471. _this._batchCache = new _InstancesBatch();
  22472. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22473. // Use by builder only to know what orientation were the mesh build in.
  22474. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22475. _this.overrideMaterialSideOrientation = null;
  22476. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22477. // Will be used to save a source mesh reference, If any
  22478. _this._source = null;
  22479. scene = _this.getScene();
  22480. if (source) {
  22481. // Source mesh
  22482. _this._source = source;
  22483. // Geometry
  22484. if (source._geometry) {
  22485. source._geometry.applyToMesh(_this);
  22486. }
  22487. // Deep copy
  22488. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  22489. // Tags
  22490. if (BABYLON.Tags.HasTags(source)) {
  22491. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22492. }
  22493. _this.metadata = source.metadata;
  22494. // Parent
  22495. _this.parent = source.parent;
  22496. // Pivot
  22497. _this.setPivotMatrix(source.getPivotMatrix());
  22498. _this.id = name + "." + source.id;
  22499. // Material
  22500. _this.material = source.material;
  22501. var index;
  22502. if (!doNotCloneChildren) {
  22503. // Children
  22504. for (index = 0; index < scene.meshes.length; index++) {
  22505. var mesh = scene.meshes[index];
  22506. if (mesh.parent === source) {
  22507. // doNotCloneChildren is always going to be False
  22508. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22509. }
  22510. }
  22511. }
  22512. // Physics clone
  22513. var physicsEngine = _this.getScene().getPhysicsEngine();
  22514. if (clonePhysicsImpostor && physicsEngine) {
  22515. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22516. if (impostor) {
  22517. _this.physicsImpostor = impostor.clone(_this);
  22518. }
  22519. }
  22520. // Particles
  22521. for (index = 0; index < scene.particleSystems.length; index++) {
  22522. var system = scene.particleSystems[index];
  22523. if (system.emitter === source) {
  22524. system.clone(system.name, _this);
  22525. }
  22526. }
  22527. _this.computeWorldMatrix(true);
  22528. }
  22529. // Parent
  22530. if (parent !== null) {
  22531. _this.parent = parent;
  22532. }
  22533. return _this;
  22534. }
  22535. Object.defineProperty(Mesh, "FRONTSIDE", {
  22536. /**
  22537. * Mesh side orientation : usually the external or front surface
  22538. */
  22539. get: function () {
  22540. return Mesh._FRONTSIDE;
  22541. },
  22542. enumerable: true,
  22543. configurable: true
  22544. });
  22545. Object.defineProperty(Mesh, "BACKSIDE", {
  22546. /**
  22547. * Mesh side orientation : usually the internal or back surface
  22548. */
  22549. get: function () {
  22550. return Mesh._BACKSIDE;
  22551. },
  22552. enumerable: true,
  22553. configurable: true
  22554. });
  22555. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22556. /**
  22557. * Mesh side orientation : both internal and external or front and back surfaces
  22558. */
  22559. get: function () {
  22560. return Mesh._DOUBLESIDE;
  22561. },
  22562. enumerable: true,
  22563. configurable: true
  22564. });
  22565. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22566. /**
  22567. * Mesh side orientation : by default, `FRONTSIDE`
  22568. */
  22569. get: function () {
  22570. return Mesh._DEFAULTSIDE;
  22571. },
  22572. enumerable: true,
  22573. configurable: true
  22574. });
  22575. Object.defineProperty(Mesh, "NO_CAP", {
  22576. /**
  22577. * Mesh cap setting : no cap
  22578. */
  22579. get: function () {
  22580. return Mesh._NO_CAP;
  22581. },
  22582. enumerable: true,
  22583. configurable: true
  22584. });
  22585. Object.defineProperty(Mesh, "CAP_START", {
  22586. /**
  22587. * Mesh cap setting : one cap at the beginning of the mesh
  22588. */
  22589. get: function () {
  22590. return Mesh._CAP_START;
  22591. },
  22592. enumerable: true,
  22593. configurable: true
  22594. });
  22595. Object.defineProperty(Mesh, "CAP_END", {
  22596. /**
  22597. * Mesh cap setting : one cap at the end of the mesh
  22598. */
  22599. get: function () {
  22600. return Mesh._CAP_END;
  22601. },
  22602. enumerable: true,
  22603. configurable: true
  22604. });
  22605. Object.defineProperty(Mesh, "CAP_ALL", {
  22606. /**
  22607. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22608. */
  22609. get: function () {
  22610. return Mesh._CAP_ALL;
  22611. },
  22612. enumerable: true,
  22613. configurable: true
  22614. });
  22615. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22616. set: function (callback) {
  22617. if (this._onBeforeDrawObserver) {
  22618. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22619. }
  22620. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22621. },
  22622. enumerable: true,
  22623. configurable: true
  22624. });
  22625. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22626. get: function () {
  22627. return this._morphTargetManager;
  22628. },
  22629. set: function (value) {
  22630. if (this._morphTargetManager === value) {
  22631. return;
  22632. }
  22633. this._morphTargetManager = value;
  22634. this._syncGeometryWithMorphTargetManager();
  22635. },
  22636. enumerable: true,
  22637. configurable: true
  22638. });
  22639. Object.defineProperty(Mesh.prototype, "source", {
  22640. get: function () {
  22641. return this._source;
  22642. },
  22643. enumerable: true,
  22644. configurable: true
  22645. });
  22646. // Methods
  22647. /**
  22648. * Returns the string "Mesh".
  22649. */
  22650. Mesh.prototype.getClassName = function () {
  22651. return "Mesh";
  22652. };
  22653. /**
  22654. * Returns a string.
  22655. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22656. */
  22657. Mesh.prototype.toString = function (fullDetails) {
  22658. var ret = _super.prototype.toString.call(this, fullDetails);
  22659. ret += ", n vertices: " + this.getTotalVertices();
  22660. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22661. if (this.animations) {
  22662. for (var i = 0; i < this.animations.length; i++) {
  22663. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22664. }
  22665. }
  22666. if (fullDetails) {
  22667. if (this._geometry) {
  22668. var ib = this.getIndices();
  22669. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22670. if (vb && ib) {
  22671. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  22672. }
  22673. }
  22674. else {
  22675. ret += ", flat shading: UNKNOWN";
  22676. }
  22677. }
  22678. return ret;
  22679. };
  22680. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22681. /**
  22682. * True if the mesh has some Levels Of Details (LOD).
  22683. * Returns a boolean.
  22684. */
  22685. get: function () {
  22686. return this._LODLevels.length > 0;
  22687. },
  22688. enumerable: true,
  22689. configurable: true
  22690. });
  22691. Mesh.prototype._sortLODLevels = function () {
  22692. this._LODLevels.sort(function (a, b) {
  22693. if (a.distance < b.distance) {
  22694. return 1;
  22695. }
  22696. if (a.distance > b.distance) {
  22697. return -1;
  22698. }
  22699. return 0;
  22700. });
  22701. };
  22702. /**
  22703. * Add a mesh as LOD level triggered at the given distance.
  22704. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22705. * @param {number} distance The distance from the center of the object to show this level
  22706. * @param {Mesh} mesh The mesh to be added as LOD level
  22707. * @return {Mesh} This mesh (for chaining)
  22708. */
  22709. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22710. if (mesh && mesh._masterMesh) {
  22711. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22712. return this;
  22713. }
  22714. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22715. this._LODLevels.push(level);
  22716. if (mesh) {
  22717. mesh._masterMesh = this;
  22718. }
  22719. this._sortLODLevels();
  22720. return this;
  22721. };
  22722. /**
  22723. * Returns the LOD level mesh at the passed distance or null if not found.
  22724. * It is related to the method `addLODLevel(distance, mesh)`.
  22725. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22726. * Returns an object Mesh or `null`.
  22727. */
  22728. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22729. for (var index = 0; index < this._LODLevels.length; index++) {
  22730. var level = this._LODLevels[index];
  22731. if (level.distance === distance) {
  22732. return level.mesh;
  22733. }
  22734. }
  22735. return null;
  22736. };
  22737. /**
  22738. * Remove a mesh from the LOD array
  22739. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22740. * @param {Mesh} mesh The mesh to be removed.
  22741. * @return {Mesh} This mesh (for chaining)
  22742. */
  22743. Mesh.prototype.removeLODLevel = function (mesh) {
  22744. for (var index = 0; index < this._LODLevels.length; index++) {
  22745. if (this._LODLevels[index].mesh === mesh) {
  22746. this._LODLevels.splice(index, 1);
  22747. if (mesh) {
  22748. mesh._masterMesh = null;
  22749. }
  22750. }
  22751. }
  22752. this._sortLODLevels();
  22753. return this;
  22754. };
  22755. /**
  22756. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22757. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22758. */
  22759. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22760. if (!this._LODLevels || this._LODLevels.length === 0) {
  22761. return this;
  22762. }
  22763. var bSphere;
  22764. if (boundingSphere) {
  22765. bSphere = boundingSphere;
  22766. }
  22767. else {
  22768. var boundingInfo = this.getBoundingInfo();
  22769. if (!boundingInfo) {
  22770. return this;
  22771. }
  22772. bSphere = boundingInfo.boundingSphere;
  22773. }
  22774. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  22775. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22776. if (this.onLODLevelSelection) {
  22777. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22778. }
  22779. return this;
  22780. }
  22781. for (var index = 0; index < this._LODLevels.length; index++) {
  22782. var level = this._LODLevels[index];
  22783. if (level.distance < distanceToCamera) {
  22784. if (level.mesh) {
  22785. level.mesh._preActivate();
  22786. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22787. }
  22788. if (this.onLODLevelSelection) {
  22789. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22790. }
  22791. return level.mesh;
  22792. }
  22793. }
  22794. if (this.onLODLevelSelection) {
  22795. this.onLODLevelSelection(distanceToCamera, this, this);
  22796. }
  22797. return this;
  22798. };
  22799. Object.defineProperty(Mesh.prototype, "geometry", {
  22800. /**
  22801. * Returns the mesh internal Geometry object.
  22802. */
  22803. get: function () {
  22804. return this._geometry;
  22805. },
  22806. enumerable: true,
  22807. configurable: true
  22808. });
  22809. /**
  22810. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22811. */
  22812. Mesh.prototype.getTotalVertices = function () {
  22813. if (!this._geometry) {
  22814. return 0;
  22815. }
  22816. return this._geometry.getTotalVertices();
  22817. };
  22818. /**
  22819. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22820. * 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.
  22821. * You can force the copy with forceCopy === true
  22822. * Returns null if the mesh has no geometry or no vertex buffer.
  22823. * Possible `kind` values :
  22824. * - BABYLON.VertexBuffer.PositionKind
  22825. * - BABYLON.VertexBuffer.UVKind
  22826. * - BABYLON.VertexBuffer.UV2Kind
  22827. * - BABYLON.VertexBuffer.UV3Kind
  22828. * - BABYLON.VertexBuffer.UV4Kind
  22829. * - BABYLON.VertexBuffer.UV5Kind
  22830. * - BABYLON.VertexBuffer.UV6Kind
  22831. * - BABYLON.VertexBuffer.ColorKind
  22832. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22833. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22834. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22835. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22836. */
  22837. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22838. if (!this._geometry) {
  22839. return null;
  22840. }
  22841. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22842. };
  22843. /**
  22844. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22845. * Returns `null` if the mesh has no geometry.
  22846. * Possible `kind` values :
  22847. * - BABYLON.VertexBuffer.PositionKind
  22848. * - BABYLON.VertexBuffer.UVKind
  22849. * - BABYLON.VertexBuffer.UV2Kind
  22850. * - BABYLON.VertexBuffer.UV3Kind
  22851. * - BABYLON.VertexBuffer.UV4Kind
  22852. * - BABYLON.VertexBuffer.UV5Kind
  22853. * - BABYLON.VertexBuffer.UV6Kind
  22854. * - BABYLON.VertexBuffer.ColorKind
  22855. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22856. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22857. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22858. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22859. */
  22860. Mesh.prototype.getVertexBuffer = function (kind) {
  22861. if (!this._geometry) {
  22862. return null;
  22863. }
  22864. return this._geometry.getVertexBuffer(kind);
  22865. };
  22866. /**
  22867. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22868. * Possible `kind` values :
  22869. * - BABYLON.VertexBuffer.PositionKind
  22870. * - BABYLON.VertexBuffer.UVKind
  22871. * - BABYLON.VertexBuffer.UV2Kind
  22872. * - BABYLON.VertexBuffer.UV3Kind
  22873. * - BABYLON.VertexBuffer.UV4Kind
  22874. * - BABYLON.VertexBuffer.UV5Kind
  22875. * - BABYLON.VertexBuffer.UV6Kind
  22876. * - BABYLON.VertexBuffer.ColorKind
  22877. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22878. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22879. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22880. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22881. */
  22882. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22883. if (!this._geometry) {
  22884. if (this._delayInfo) {
  22885. return this._delayInfo.indexOf(kind) !== -1;
  22886. }
  22887. return false;
  22888. }
  22889. return this._geometry.isVerticesDataPresent(kind);
  22890. };
  22891. /**
  22892. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  22893. * Possible `kind` values :
  22894. * - BABYLON.VertexBuffer.PositionKind
  22895. * - BABYLON.VertexBuffer.UVKind
  22896. * - BABYLON.VertexBuffer.UV2Kind
  22897. * - BABYLON.VertexBuffer.UV3Kind
  22898. * - BABYLON.VertexBuffer.UV4Kind
  22899. * - BABYLON.VertexBuffer.UV5Kind
  22900. * - BABYLON.VertexBuffer.UV6Kind
  22901. * - BABYLON.VertexBuffer.ColorKind
  22902. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22903. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22904. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22905. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22906. */
  22907. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  22908. if (!this._geometry) {
  22909. if (this._delayInfo) {
  22910. return this._delayInfo.indexOf(kind) !== -1;
  22911. }
  22912. return false;
  22913. }
  22914. return this._geometry.isVertexBufferUpdatable(kind);
  22915. };
  22916. /**
  22917. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22918. * Possible `kind` values :
  22919. * - BABYLON.VertexBuffer.PositionKind
  22920. * - BABYLON.VertexBuffer.UVKind
  22921. * - BABYLON.VertexBuffer.UV2Kind
  22922. * - BABYLON.VertexBuffer.UV3Kind
  22923. * - BABYLON.VertexBuffer.UV4Kind
  22924. * - BABYLON.VertexBuffer.UV5Kind
  22925. * - BABYLON.VertexBuffer.UV6Kind
  22926. * - BABYLON.VertexBuffer.ColorKind
  22927. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22928. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22929. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22930. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22931. */
  22932. Mesh.prototype.getVerticesDataKinds = function () {
  22933. if (!this._geometry) {
  22934. var result = new Array();
  22935. if (this._delayInfo) {
  22936. this._delayInfo.forEach(function (kind, index, array) {
  22937. result.push(kind);
  22938. });
  22939. }
  22940. return result;
  22941. }
  22942. return this._geometry.getVerticesDataKinds();
  22943. };
  22944. /**
  22945. * Returns a positive integer : the total number of indices in this mesh geometry.
  22946. * Returns zero if the mesh has no geometry.
  22947. */
  22948. Mesh.prototype.getTotalIndices = function () {
  22949. if (!this._geometry) {
  22950. return 0;
  22951. }
  22952. return this._geometry.getTotalIndices();
  22953. };
  22954. /**
  22955. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22956. * 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.
  22957. * Returns an empty array if the mesh has no geometry.
  22958. */
  22959. Mesh.prototype.getIndices = function (copyWhenShared) {
  22960. if (!this._geometry) {
  22961. return [];
  22962. }
  22963. return this._geometry.getIndices(copyWhenShared);
  22964. };
  22965. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22966. get: function () {
  22967. return this._masterMesh !== null && this._masterMesh !== undefined;
  22968. },
  22969. enumerable: true,
  22970. configurable: true
  22971. });
  22972. /**
  22973. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22974. */
  22975. Mesh.prototype.isReady = function () {
  22976. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22977. return false;
  22978. }
  22979. return _super.prototype.isReady.call(this);
  22980. };
  22981. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22982. /**
  22983. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22984. * This property is pertinent only for updatable parametric shapes.
  22985. */
  22986. get: function () {
  22987. return this._areNormalsFrozen;
  22988. },
  22989. enumerable: true,
  22990. configurable: true
  22991. });
  22992. /**
  22993. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22994. * It has no effect at all on other shapes.
  22995. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22996. * Returns the Mesh.
  22997. */
  22998. Mesh.prototype.freezeNormals = function () {
  22999. this._areNormalsFrozen = true;
  23000. return this;
  23001. };
  23002. /**
  23003. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23004. * It has no effect at all on other shapes.
  23005. * It reactivates the mesh normals computation if it was previously frozen.
  23006. * Returns the Mesh.
  23007. */
  23008. Mesh.prototype.unfreezeNormals = function () {
  23009. this._areNormalsFrozen = false;
  23010. return this;
  23011. };
  23012. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23013. /**
  23014. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23015. */
  23016. set: function (count) {
  23017. this._overridenInstanceCount = count;
  23018. },
  23019. enumerable: true,
  23020. configurable: true
  23021. });
  23022. // Methods
  23023. Mesh.prototype._preActivate = function () {
  23024. var sceneRenderId = this.getScene().getRenderId();
  23025. if (this._preActivateId === sceneRenderId) {
  23026. return this;
  23027. }
  23028. this._preActivateId = sceneRenderId;
  23029. this._visibleInstances = null;
  23030. return this;
  23031. };
  23032. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23033. if (this._visibleInstances) {
  23034. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23035. }
  23036. return this;
  23037. };
  23038. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23039. if (!this._visibleInstances) {
  23040. this._visibleInstances = {};
  23041. this._visibleInstances.defaultRenderId = renderId;
  23042. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23043. }
  23044. if (!this._visibleInstances[renderId]) {
  23045. this._visibleInstances[renderId] = new Array();
  23046. }
  23047. this._visibleInstances[renderId].push(instance);
  23048. return this;
  23049. };
  23050. /**
  23051. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23052. * This means the mesh underlying bounding box and sphere are recomputed.
  23053. * Returns the Mesh.
  23054. */
  23055. Mesh.prototype.refreshBoundingInfo = function () {
  23056. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23057. return this;
  23058. }
  23059. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23060. if (data) {
  23061. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23062. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23063. }
  23064. if (this.subMeshes) {
  23065. for (var index = 0; index < this.subMeshes.length; index++) {
  23066. this.subMeshes[index].refreshBoundingInfo();
  23067. }
  23068. }
  23069. this._updateBoundingInfo();
  23070. return this;
  23071. };
  23072. Mesh.prototype._createGlobalSubMesh = function (force) {
  23073. var totalVertices = this.getTotalVertices();
  23074. if (!totalVertices || !this.getIndices()) {
  23075. return null;
  23076. }
  23077. // Check if we need to recreate the submeshes
  23078. if (this.subMeshes && this.subMeshes.length > 0) {
  23079. var ib = this.getIndices();
  23080. if (!ib) {
  23081. return null;
  23082. }
  23083. var totalIndices = ib.length;
  23084. var needToRecreate = false;
  23085. if (force) {
  23086. needToRecreate = true;
  23087. }
  23088. else {
  23089. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23090. var submesh = _a[_i];
  23091. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23092. needToRecreate = true;
  23093. break;
  23094. }
  23095. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23096. needToRecreate = true;
  23097. break;
  23098. }
  23099. }
  23100. }
  23101. if (!needToRecreate) {
  23102. return this.subMeshes[0];
  23103. }
  23104. }
  23105. this.releaseSubMeshes();
  23106. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23107. };
  23108. Mesh.prototype.subdivide = function (count) {
  23109. if (count < 1) {
  23110. return;
  23111. }
  23112. var totalIndices = this.getTotalIndices();
  23113. var subdivisionSize = (totalIndices / count) | 0;
  23114. var offset = 0;
  23115. // Ensure that subdivisionSize is a multiple of 3
  23116. while (subdivisionSize % 3 !== 0) {
  23117. subdivisionSize++;
  23118. }
  23119. this.releaseSubMeshes();
  23120. for (var index = 0; index < count; index++) {
  23121. if (offset >= totalIndices) {
  23122. break;
  23123. }
  23124. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23125. offset += subdivisionSize;
  23126. }
  23127. this.synchronizeInstances();
  23128. };
  23129. /**
  23130. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23131. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23132. * The `data` are either a numeric array either a Float32Array.
  23133. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23134. * 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).
  23135. * Note that a new underlying VertexBuffer object is created each call.
  23136. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23137. *
  23138. * Possible `kind` values :
  23139. * - BABYLON.VertexBuffer.PositionKind
  23140. * - BABYLON.VertexBuffer.UVKind
  23141. * - BABYLON.VertexBuffer.UV2Kind
  23142. * - BABYLON.VertexBuffer.UV3Kind
  23143. * - BABYLON.VertexBuffer.UV4Kind
  23144. * - BABYLON.VertexBuffer.UV5Kind
  23145. * - BABYLON.VertexBuffer.UV6Kind
  23146. * - BABYLON.VertexBuffer.ColorKind
  23147. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23148. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23149. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23150. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23151. *
  23152. * Returns the Mesh.
  23153. */
  23154. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23155. if (updatable === void 0) { updatable = false; }
  23156. if (!this._geometry) {
  23157. var vertexData = new BABYLON.VertexData();
  23158. vertexData.set(data, kind);
  23159. var scene = this.getScene();
  23160. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23161. }
  23162. else {
  23163. this._geometry.setVerticesData(kind, data, updatable, stride);
  23164. }
  23165. return this;
  23166. };
  23167. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23168. if (updatable === void 0) { updatable = true; }
  23169. var vb = this.getVertexBuffer(kind);
  23170. if (!vb || vb.isUpdatable() === updatable) {
  23171. return;
  23172. }
  23173. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23174. };
  23175. /**
  23176. * Sets the mesh VertexBuffer.
  23177. * Returns the Mesh.
  23178. */
  23179. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23180. if (!this._geometry) {
  23181. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23182. }
  23183. this._geometry.setVerticesBuffer(buffer);
  23184. return this;
  23185. };
  23186. /**
  23187. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23188. * If the mesh has no geometry, it is simply returned as it is.
  23189. * The `data` are either a numeric array either a Float32Array.
  23190. * No new underlying VertexBuffer object is created.
  23191. * 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.
  23192. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23193. *
  23194. * Possible `kind` values :
  23195. * - BABYLON.VertexBuffer.PositionKind
  23196. * - BABYLON.VertexBuffer.UVKind
  23197. * - BABYLON.VertexBuffer.UV2Kind
  23198. * - BABYLON.VertexBuffer.UV3Kind
  23199. * - BABYLON.VertexBuffer.UV4Kind
  23200. * - BABYLON.VertexBuffer.UV5Kind
  23201. * - BABYLON.VertexBuffer.UV6Kind
  23202. * - BABYLON.VertexBuffer.ColorKind
  23203. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23204. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23205. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23206. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23207. *
  23208. * Returns the Mesh.
  23209. */
  23210. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23211. if (!this._geometry) {
  23212. return this;
  23213. }
  23214. if (!makeItUnique) {
  23215. this._geometry.updateVerticesData(kind, data, updateExtends);
  23216. }
  23217. else {
  23218. this.makeGeometryUnique();
  23219. this.updateVerticesData(kind, data, updateExtends, false);
  23220. }
  23221. return this;
  23222. };
  23223. /**
  23224. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23225. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23226. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23227. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23228. * Returns the Mesh.
  23229. */
  23230. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23231. if (computeNormals === void 0) { computeNormals = true; }
  23232. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23233. if (!positions) {
  23234. return this;
  23235. }
  23236. positionFunction(positions);
  23237. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23238. if (computeNormals) {
  23239. var indices = this.getIndices();
  23240. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23241. if (!normals) {
  23242. return this;
  23243. }
  23244. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23245. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23246. }
  23247. return this;
  23248. };
  23249. /**
  23250. * Creates a un-shared specific occurence of the geometry for the mesh.
  23251. * Returns the Mesh.
  23252. */
  23253. Mesh.prototype.makeGeometryUnique = function () {
  23254. if (!this._geometry) {
  23255. return this;
  23256. }
  23257. var oldGeometry = this._geometry;
  23258. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23259. oldGeometry.releaseForMesh(this, true);
  23260. geometry.applyToMesh(this);
  23261. return this;
  23262. };
  23263. /**
  23264. * Sets the mesh indices.
  23265. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23266. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23267. * This method creates a new index buffer each call.
  23268. * Returns the Mesh.
  23269. */
  23270. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23271. if (totalVertices === void 0) { totalVertices = null; }
  23272. if (updatable === void 0) { updatable = false; }
  23273. if (!this._geometry) {
  23274. var vertexData = new BABYLON.VertexData();
  23275. vertexData.indices = indices;
  23276. var scene = this.getScene();
  23277. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23278. }
  23279. else {
  23280. this._geometry.setIndices(indices, totalVertices, updatable);
  23281. }
  23282. return this;
  23283. };
  23284. /**
  23285. * Update the current index buffer
  23286. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23287. * Returns the Mesh.
  23288. */
  23289. Mesh.prototype.updateIndices = function (indices, offset) {
  23290. if (!this._geometry) {
  23291. return this;
  23292. }
  23293. this._geometry.updateIndices(indices, offset);
  23294. return this;
  23295. };
  23296. /**
  23297. * Invert the geometry to move from a right handed system to a left handed one.
  23298. * Returns the Mesh.
  23299. */
  23300. Mesh.prototype.toLeftHanded = function () {
  23301. if (!this._geometry) {
  23302. return this;
  23303. }
  23304. this._geometry.toLeftHanded();
  23305. return this;
  23306. };
  23307. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23308. if (!this._geometry) {
  23309. return this;
  23310. }
  23311. var engine = this.getScene().getEngine();
  23312. // Wireframe
  23313. var indexToBind;
  23314. if (this._unIndexed) {
  23315. indexToBind = null;
  23316. }
  23317. else {
  23318. switch (fillMode) {
  23319. case BABYLON.Material.PointFillMode:
  23320. indexToBind = null;
  23321. break;
  23322. case BABYLON.Material.WireFrameFillMode:
  23323. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23324. break;
  23325. default:
  23326. case BABYLON.Material.TriangleFillMode:
  23327. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23328. break;
  23329. }
  23330. }
  23331. // VBOs
  23332. this._geometry._bind(effect, indexToBind);
  23333. return this;
  23334. };
  23335. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23336. if (alternate === void 0) { alternate = false; }
  23337. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23338. return this;
  23339. }
  23340. this.onBeforeDrawObservable.notifyObservers(this);
  23341. var scene = this.getScene();
  23342. var engine = scene.getEngine();
  23343. // Draw order
  23344. switch (fillMode) {
  23345. case BABYLON.Material.PointFillMode:
  23346. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23347. break;
  23348. case BABYLON.Material.WireFrameFillMode:
  23349. if (this._unIndexed) {
  23350. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23351. }
  23352. else {
  23353. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23354. }
  23355. break;
  23356. default:
  23357. if (this._unIndexed) {
  23358. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23359. }
  23360. else {
  23361. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23362. }
  23363. }
  23364. if (scene._isAlternateRenderingEnabled && !alternate) {
  23365. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23366. if (!effect || !scene.activeCamera) {
  23367. return this;
  23368. }
  23369. scene._switchToAlternateCameraConfiguration(true);
  23370. this._effectiveMaterial.bindView(effect);
  23371. this._effectiveMaterial.bindViewProjection(effect);
  23372. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23373. this._draw(subMesh, fillMode, instancesCount, true);
  23374. engine.setViewport(scene.activeCamera.viewport);
  23375. scene._switchToAlternateCameraConfiguration(false);
  23376. this._effectiveMaterial.bindView(effect);
  23377. this._effectiveMaterial.bindViewProjection(effect);
  23378. }
  23379. return this;
  23380. };
  23381. /**
  23382. * Registers for this mesh a javascript function called just before the rendering process.
  23383. * This function is passed the current mesh.
  23384. * Return the Mesh.
  23385. */
  23386. Mesh.prototype.registerBeforeRender = function (func) {
  23387. this.onBeforeRenderObservable.add(func);
  23388. return this;
  23389. };
  23390. /**
  23391. * Disposes a previously registered javascript function called before the rendering.
  23392. * This function is passed the current mesh.
  23393. * Returns the Mesh.
  23394. */
  23395. Mesh.prototype.unregisterBeforeRender = function (func) {
  23396. this.onBeforeRenderObservable.removeCallback(func);
  23397. return this;
  23398. };
  23399. /**
  23400. * Registers for this mesh a javascript function called just after the rendering is complete.
  23401. * This function is passed the current mesh.
  23402. * Returns the Mesh.
  23403. */
  23404. Mesh.prototype.registerAfterRender = function (func) {
  23405. this.onAfterRenderObservable.add(func);
  23406. return this;
  23407. };
  23408. /**
  23409. * Disposes a previously registered javascript function called after the rendering.
  23410. * This function is passed the current mesh.
  23411. * Return the Mesh.
  23412. */
  23413. Mesh.prototype.unregisterAfterRender = function (func) {
  23414. this.onAfterRenderObservable.removeCallback(func);
  23415. return this;
  23416. };
  23417. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23418. var scene = this.getScene();
  23419. this._batchCache.mustReturn = false;
  23420. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23421. this._batchCache.visibleInstances[subMeshId] = null;
  23422. if (this._visibleInstances) {
  23423. var currentRenderId = scene.getRenderId();
  23424. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23425. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23426. var selfRenderId = this._renderId;
  23427. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23428. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23429. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23430. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23431. }
  23432. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23433. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23434. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23435. this._batchCache.mustReturn = true;
  23436. return this._batchCache;
  23437. }
  23438. if (currentRenderId !== selfRenderId) {
  23439. this._batchCache.renderSelf[subMeshId] = false;
  23440. }
  23441. }
  23442. this._renderIdForInstances[subMeshId] = currentRenderId;
  23443. }
  23444. return this._batchCache;
  23445. };
  23446. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23447. var visibleInstances = batch.visibleInstances[subMesh._id];
  23448. if (!visibleInstances) {
  23449. return this;
  23450. }
  23451. var matricesCount = visibleInstances.length + 1;
  23452. var bufferSize = matricesCount * 16 * 4;
  23453. var currentInstancesBufferSize = this._instancesBufferSize;
  23454. var instancesBuffer = this._instancesBuffer;
  23455. while (this._instancesBufferSize < bufferSize) {
  23456. this._instancesBufferSize *= 2;
  23457. }
  23458. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23459. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23460. }
  23461. var offset = 0;
  23462. var instancesCount = 0;
  23463. var world = this.getWorldMatrix();
  23464. if (batch.renderSelf[subMesh._id]) {
  23465. world.copyToArray(this._instancesData, offset);
  23466. offset += 16;
  23467. instancesCount++;
  23468. }
  23469. if (visibleInstances) {
  23470. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23471. var instance = visibleInstances[instanceIndex];
  23472. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23473. offset += 16;
  23474. instancesCount++;
  23475. }
  23476. }
  23477. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23478. if (instancesBuffer) {
  23479. instancesBuffer.dispose();
  23480. }
  23481. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23482. this._instancesBuffer = instancesBuffer;
  23483. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23484. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23485. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23486. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23487. }
  23488. else {
  23489. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23490. }
  23491. this._bind(subMesh, effect, fillMode);
  23492. this._draw(subMesh, fillMode, instancesCount);
  23493. engine.unbindInstanceAttributes();
  23494. return this;
  23495. };
  23496. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23497. var scene = this.getScene();
  23498. var engine = scene.getEngine();
  23499. if (hardwareInstancedRendering) {
  23500. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23501. }
  23502. else {
  23503. if (batch.renderSelf[subMesh._id]) {
  23504. // Draw
  23505. if (onBeforeDraw) {
  23506. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23507. }
  23508. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23509. }
  23510. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23511. if (visibleInstancesForSubMesh) {
  23512. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23513. var instance = visibleInstancesForSubMesh[instanceIndex];
  23514. // World
  23515. var world = instance.getWorldMatrix();
  23516. if (onBeforeDraw) {
  23517. onBeforeDraw(true, world, effectiveMaterial);
  23518. }
  23519. // Draw
  23520. this._draw(subMesh, fillMode);
  23521. }
  23522. }
  23523. }
  23524. return this;
  23525. };
  23526. /**
  23527. * Triggers the draw call for the mesh.
  23528. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23529. * Returns the Mesh.
  23530. */
  23531. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23532. this.checkOcclusionQuery();
  23533. if (this._isOccluded) {
  23534. return this;
  23535. }
  23536. var scene = this.getScene();
  23537. // Managing instances
  23538. var batch = this._getInstancesRenderList(subMesh._id);
  23539. if (batch.mustReturn) {
  23540. return this;
  23541. }
  23542. // Checking geometry state
  23543. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23544. return this;
  23545. }
  23546. this.onBeforeRenderObservable.notifyObservers(this);
  23547. var engine = scene.getEngine();
  23548. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23549. // Material
  23550. var material = subMesh.getMaterial();
  23551. if (!material) {
  23552. return this;
  23553. }
  23554. this._effectiveMaterial = material;
  23555. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23556. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23557. return this;
  23558. }
  23559. }
  23560. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23561. return this;
  23562. }
  23563. // Alpha mode
  23564. if (enableAlphaMode) {
  23565. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23566. }
  23567. // Outline - step 1
  23568. var savedDepthWrite = engine.getDepthWrite();
  23569. if (this.renderOutline) {
  23570. engine.setDepthWrite(false);
  23571. scene.getOutlineRenderer().render(subMesh, batch);
  23572. engine.setDepthWrite(savedDepthWrite);
  23573. }
  23574. var effect;
  23575. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23576. effect = subMesh.effect;
  23577. }
  23578. else {
  23579. effect = this._effectiveMaterial.getEffect();
  23580. }
  23581. if (!effect) {
  23582. return this;
  23583. }
  23584. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23585. if (this._effectiveMaterial.forceDepthWrite) {
  23586. engine.setDepthWrite(true);
  23587. }
  23588. // Bind
  23589. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  23590. if (!hardwareInstancedRendering) {
  23591. this._bind(subMesh, effect, fillMode);
  23592. }
  23593. var world = this.getWorldMatrix();
  23594. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23595. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  23596. }
  23597. else {
  23598. this._effectiveMaterial.bind(world, this);
  23599. }
  23600. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  23601. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  23602. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23603. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  23604. }
  23605. // Draw
  23606. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23607. // Unbind
  23608. this._effectiveMaterial.unbind();
  23609. // Outline - step 2
  23610. if (this.renderOutline && savedDepthWrite) {
  23611. engine.setDepthWrite(true);
  23612. engine.setColorWrite(false);
  23613. scene.getOutlineRenderer().render(subMesh, batch);
  23614. engine.setColorWrite(true);
  23615. }
  23616. // Overlay
  23617. if (this.renderOverlay) {
  23618. var currentMode = engine.getAlphaMode();
  23619. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23620. scene.getOutlineRenderer().render(subMesh, batch, true);
  23621. engine.setAlphaMode(currentMode);
  23622. }
  23623. this.onAfterRenderObservable.notifyObservers(this);
  23624. return this;
  23625. };
  23626. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23627. if (isInstance) {
  23628. effectiveMaterial.bindOnlyWorldMatrix(world);
  23629. }
  23630. return this;
  23631. };
  23632. /**
  23633. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23634. */
  23635. Mesh.prototype.getEmittedParticleSystems = function () {
  23636. var results = new Array();
  23637. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23638. var particleSystem = this.getScene().particleSystems[index];
  23639. if (particleSystem.emitter === this) {
  23640. results.push(particleSystem);
  23641. }
  23642. }
  23643. return results;
  23644. };
  23645. /**
  23646. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23647. */
  23648. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23649. var results = new Array();
  23650. var descendants = this.getDescendants();
  23651. descendants.push(this);
  23652. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23653. var particleSystem = this.getScene().particleSystems[index];
  23654. var emitter = particleSystem.emitter;
  23655. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23656. results.push(particleSystem);
  23657. }
  23658. }
  23659. return results;
  23660. };
  23661. Mesh.prototype._checkDelayState = function () {
  23662. var scene = this.getScene();
  23663. if (this._geometry) {
  23664. this._geometry.load(scene);
  23665. }
  23666. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23667. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23668. this._queueLoad(this, scene);
  23669. }
  23670. return this;
  23671. };
  23672. Mesh.prototype._queueLoad = function (mesh, scene) {
  23673. var _this = this;
  23674. scene._addPendingData(mesh);
  23675. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23676. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23677. if (data instanceof ArrayBuffer) {
  23678. _this._delayLoadingFunction(data, _this);
  23679. }
  23680. else {
  23681. _this._delayLoadingFunction(JSON.parse(data), _this);
  23682. }
  23683. _this.instances.forEach(function (instance) {
  23684. instance._syncSubMeshes();
  23685. });
  23686. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23687. scene._removePendingData(_this);
  23688. }, function () { }, scene.database, getBinaryData);
  23689. return this;
  23690. };
  23691. /**
  23692. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23693. */
  23694. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23695. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23696. return false;
  23697. }
  23698. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23699. return false;
  23700. }
  23701. this._checkDelayState();
  23702. return true;
  23703. };
  23704. /**
  23705. * Sets the mesh material by the material or multiMaterial `id` property.
  23706. * The material `id` is a string identifying the material or the multiMaterial.
  23707. * This method returns the Mesh.
  23708. */
  23709. Mesh.prototype.setMaterialByID = function (id) {
  23710. var materials = this.getScene().materials;
  23711. var index;
  23712. for (index = materials.length - 1; index > -1; index--) {
  23713. if (materials[index].id === id) {
  23714. this.material = materials[index];
  23715. return this;
  23716. }
  23717. }
  23718. // Multi
  23719. var multiMaterials = this.getScene().multiMaterials;
  23720. for (index = multiMaterials.length - 1; index > -1; index--) {
  23721. if (multiMaterials[index].id === id) {
  23722. this.material = multiMaterials[index];
  23723. return this;
  23724. }
  23725. }
  23726. return this;
  23727. };
  23728. /**
  23729. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23730. */
  23731. Mesh.prototype.getAnimatables = function () {
  23732. var results = new Array();
  23733. if (this.material) {
  23734. results.push(this.material);
  23735. }
  23736. if (this.skeleton) {
  23737. results.push(this.skeleton);
  23738. }
  23739. return results;
  23740. };
  23741. /**
  23742. * Modifies the mesh geometry according to the passed transformation matrix.
  23743. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23744. * The mesh normals are modified accordingly the same transformation.
  23745. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23746. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23747. * Returns the Mesh.
  23748. */
  23749. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23750. // Position
  23751. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23752. return this;
  23753. }
  23754. var submeshes = this.subMeshes.splice(0);
  23755. this._resetPointsArrayCache();
  23756. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23757. var temp = new Array();
  23758. var index;
  23759. for (index = 0; index < data.length; index += 3) {
  23760. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23761. }
  23762. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23763. // Normals
  23764. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23765. return this;
  23766. }
  23767. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23768. temp = [];
  23769. for (index = 0; index < data.length; index += 3) {
  23770. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23771. }
  23772. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23773. // flip faces?
  23774. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23775. this.flipFaces();
  23776. }
  23777. // Restore submeshes
  23778. this.releaseSubMeshes();
  23779. this.subMeshes = submeshes;
  23780. return this;
  23781. };
  23782. /**
  23783. * Modifies the mesh geometry according to its own current World Matrix.
  23784. * The mesh World Matrix is then reset.
  23785. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23786. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23787. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23788. * Returns the Mesh.
  23789. */
  23790. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23791. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23792. this.scaling.copyFromFloats(1, 1, 1);
  23793. this.position.copyFromFloats(0, 0, 0);
  23794. this.rotation.copyFromFloats(0, 0, 0);
  23795. //only if quaternion is already set
  23796. if (this.rotationQuaternion) {
  23797. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23798. }
  23799. this._worldMatrix = BABYLON.Matrix.Identity();
  23800. return this;
  23801. };
  23802. Object.defineProperty(Mesh.prototype, "_positions", {
  23803. // Cache
  23804. get: function () {
  23805. if (this._geometry) {
  23806. return this._geometry._positions;
  23807. }
  23808. return null;
  23809. },
  23810. enumerable: true,
  23811. configurable: true
  23812. });
  23813. Mesh.prototype._resetPointsArrayCache = function () {
  23814. if (this._geometry) {
  23815. this._geometry._resetPointsArrayCache();
  23816. }
  23817. return this;
  23818. };
  23819. Mesh.prototype._generatePointsArray = function () {
  23820. if (this._geometry) {
  23821. return this._geometry._generatePointsArray();
  23822. }
  23823. return false;
  23824. };
  23825. /**
  23826. * Returns a new Mesh object generated from the current mesh properties.
  23827. * This method must not get confused with createInstance().
  23828. * The parameter `name` is a string, the name given to the new mesh.
  23829. * The optional parameter `newParent` can be any Node object (default `null`).
  23830. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23831. * 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.
  23832. */
  23833. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23834. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23835. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23836. };
  23837. /**
  23838. * Disposes the mesh.
  23839. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23840. */
  23841. Mesh.prototype.dispose = function (doNotRecurse) {
  23842. var _this = this;
  23843. this.morphTargetManager = null;
  23844. if (this._geometry) {
  23845. this._geometry.releaseForMesh(this, true);
  23846. }
  23847. // Sources
  23848. var meshes = this.getScene().meshes;
  23849. meshes.forEach(function (mesh) {
  23850. if (mesh._source && mesh._source === _this) {
  23851. mesh._source = null;
  23852. }
  23853. });
  23854. this._source = null;
  23855. // Instances
  23856. if (this._instancesBuffer) {
  23857. this._instancesBuffer.dispose();
  23858. this._instancesBuffer = null;
  23859. }
  23860. while (this.instances.length) {
  23861. this.instances[0].dispose();
  23862. }
  23863. // Highlight layers.
  23864. var highlightLayers = this.getScene().highlightLayers;
  23865. for (var i = 0; i < highlightLayers.length; i++) {
  23866. var highlightLayer = highlightLayers[i];
  23867. if (highlightLayer) {
  23868. highlightLayer.removeMesh(this);
  23869. highlightLayer.removeExcludedMesh(this);
  23870. }
  23871. }
  23872. _super.prototype.dispose.call(this, doNotRecurse);
  23873. };
  23874. /**
  23875. * Modifies the mesh geometry according to a displacement map.
  23876. * 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.
  23877. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23878. * This method returns nothing.
  23879. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23880. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23881. * 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.
  23882. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23883. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23884. *
  23885. * Returns the Mesh.
  23886. */
  23887. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23888. var _this = this;
  23889. var scene = this.getScene();
  23890. var onload = function (img) {
  23891. // Getting height map data
  23892. var canvas = document.createElement("canvas");
  23893. var context = canvas.getContext("2d");
  23894. var heightMapWidth = img.width;
  23895. var heightMapHeight = img.height;
  23896. canvas.width = heightMapWidth;
  23897. canvas.height = heightMapHeight;
  23898. context.drawImage(img, 0, 0);
  23899. // Create VertexData from map data
  23900. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23901. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23902. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23903. //execute success callback, if set
  23904. if (onSuccess) {
  23905. onSuccess(_this);
  23906. }
  23907. };
  23908. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23909. return this;
  23910. };
  23911. /**
  23912. * Modifies the mesh geometry according to a displacementMap buffer.
  23913. * 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.
  23914. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23915. * This method returns nothing.
  23916. * 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.
  23917. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23918. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23919. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23920. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23921. *
  23922. * Returns the Mesh.
  23923. */
  23924. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23925. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23926. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23927. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23928. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23929. return this;
  23930. }
  23931. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23932. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23933. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23934. var position = BABYLON.Vector3.Zero();
  23935. var normal = BABYLON.Vector3.Zero();
  23936. var uv = BABYLON.Vector2.Zero();
  23937. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23938. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23939. for (var index = 0; index < positions.length; index += 3) {
  23940. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23941. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23942. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23943. // Compute height
  23944. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23945. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23946. var pos = (u + v * heightMapWidth) * 4;
  23947. var r = buffer[pos] / 255.0;
  23948. var g = buffer[pos + 1] / 255.0;
  23949. var b = buffer[pos + 2] / 255.0;
  23950. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23951. normal.normalize();
  23952. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23953. position = position.add(normal);
  23954. position.toArray(positions, index);
  23955. }
  23956. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23957. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23958. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23959. return this;
  23960. };
  23961. /**
  23962. * Modify the mesh to get a flat shading rendering.
  23963. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23964. * This method returns the Mesh.
  23965. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23966. */
  23967. Mesh.prototype.convertToFlatShadedMesh = function () {
  23968. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23969. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23970. var kinds = this.getVerticesDataKinds();
  23971. var vbs = {};
  23972. var data = {};
  23973. var newdata = {};
  23974. var updatableNormals = false;
  23975. var kindIndex;
  23976. var kind;
  23977. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23978. kind = kinds[kindIndex];
  23979. var vertexBuffer = this.getVertexBuffer(kind);
  23980. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23981. updatableNormals = vertexBuffer.isUpdatable();
  23982. kinds.splice(kindIndex, 1);
  23983. kindIndex--;
  23984. continue;
  23985. }
  23986. vbs[kind] = vertexBuffer;
  23987. data[kind] = vbs[kind].getData();
  23988. newdata[kind] = [];
  23989. }
  23990. // Save previous submeshes
  23991. var previousSubmeshes = this.subMeshes.slice(0);
  23992. var indices = this.getIndices();
  23993. var totalIndices = this.getTotalIndices();
  23994. // Generating unique vertices per face
  23995. var index;
  23996. for (index = 0; index < totalIndices; index++) {
  23997. var vertexIndex = indices[index];
  23998. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23999. kind = kinds[kindIndex];
  24000. var stride = vbs[kind].getStrideSize();
  24001. for (var offset = 0; offset < stride; offset++) {
  24002. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24003. }
  24004. }
  24005. }
  24006. // Updating faces & normal
  24007. var normals = [];
  24008. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24009. for (index = 0; index < totalIndices; index += 3) {
  24010. indices[index] = index;
  24011. indices[index + 1] = index + 1;
  24012. indices[index + 2] = index + 2;
  24013. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24014. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24015. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24016. var p1p2 = p1.subtract(p2);
  24017. var p3p2 = p3.subtract(p2);
  24018. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24019. // Store same normals for every vertex
  24020. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24021. normals.push(normal.x);
  24022. normals.push(normal.y);
  24023. normals.push(normal.z);
  24024. }
  24025. }
  24026. this.setIndices(indices);
  24027. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24028. // Updating vertex buffers
  24029. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24030. kind = kinds[kindIndex];
  24031. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24032. }
  24033. // Updating submeshes
  24034. this.releaseSubMeshes();
  24035. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24036. var previousOne = previousSubmeshes[submeshIndex];
  24037. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24038. }
  24039. this.synchronizeInstances();
  24040. return this;
  24041. };
  24042. /**
  24043. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24044. * In other words, more vertices, no more indices and a single bigger VBO.
  24045. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24046. * Returns the Mesh.
  24047. */
  24048. Mesh.prototype.convertToUnIndexedMesh = function () {
  24049. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24050. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24051. var kinds = this.getVerticesDataKinds();
  24052. var vbs = {};
  24053. var data = {};
  24054. var newdata = {};
  24055. var kindIndex;
  24056. var kind;
  24057. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24058. kind = kinds[kindIndex];
  24059. var vertexBuffer = this.getVertexBuffer(kind);
  24060. vbs[kind] = vertexBuffer;
  24061. data[kind] = vbs[kind].getData();
  24062. newdata[kind] = [];
  24063. }
  24064. // Save previous submeshes
  24065. var previousSubmeshes = this.subMeshes.slice(0);
  24066. var indices = this.getIndices();
  24067. var totalIndices = this.getTotalIndices();
  24068. // Generating unique vertices per face
  24069. var index;
  24070. for (index = 0; index < totalIndices; index++) {
  24071. var vertexIndex = indices[index];
  24072. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24073. kind = kinds[kindIndex];
  24074. var stride = vbs[kind].getStrideSize();
  24075. for (var offset = 0; offset < stride; offset++) {
  24076. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24077. }
  24078. }
  24079. }
  24080. // Updating indices
  24081. for (index = 0; index < totalIndices; index += 3) {
  24082. indices[index] = index;
  24083. indices[index + 1] = index + 1;
  24084. indices[index + 2] = index + 2;
  24085. }
  24086. this.setIndices(indices);
  24087. // Updating vertex buffers
  24088. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24089. kind = kinds[kindIndex];
  24090. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24091. }
  24092. // Updating submeshes
  24093. this.releaseSubMeshes();
  24094. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24095. var previousOne = previousSubmeshes[submeshIndex];
  24096. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24097. }
  24098. this._unIndexed = true;
  24099. this.synchronizeInstances();
  24100. return this;
  24101. };
  24102. /**
  24103. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24104. * This method returns the Mesh.
  24105. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24106. */
  24107. Mesh.prototype.flipFaces = function (flipNormals) {
  24108. if (flipNormals === void 0) { flipNormals = false; }
  24109. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24110. var i;
  24111. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24112. for (i = 0; i < vertex_data.normals.length; i++) {
  24113. vertex_data.normals[i] *= -1;
  24114. }
  24115. }
  24116. if (vertex_data.indices) {
  24117. var temp;
  24118. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24119. // reassign indices
  24120. temp = vertex_data.indices[i + 1];
  24121. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24122. vertex_data.indices[i + 2] = temp;
  24123. }
  24124. }
  24125. vertex_data.applyToMesh(this);
  24126. return this;
  24127. };
  24128. // Instances
  24129. /**
  24130. * Creates a new InstancedMesh object from the mesh model.
  24131. * An instance shares the same properties and the same material than its model.
  24132. * Only these properties of each instance can then be set individually :
  24133. * - position
  24134. * - rotation
  24135. * - rotationQuaternion
  24136. * - setPivotMatrix
  24137. * - scaling
  24138. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24139. * Warning : this method is not supported for Line mesh and LineSystem
  24140. */
  24141. Mesh.prototype.createInstance = function (name) {
  24142. return new BABYLON.InstancedMesh(name, this);
  24143. };
  24144. /**
  24145. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24146. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24147. * This method returns the Mesh.
  24148. */
  24149. Mesh.prototype.synchronizeInstances = function () {
  24150. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24151. var instance = this.instances[instanceIndex];
  24152. instance._syncSubMeshes();
  24153. }
  24154. return this;
  24155. };
  24156. /**
  24157. * Simplify the mesh according to the given array of settings.
  24158. * Function will return immediately and will simplify async. It returns the Mesh.
  24159. * @param settings a collection of simplification settings.
  24160. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24161. * @param type the type of simplification to run.
  24162. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24163. */
  24164. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24165. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24166. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24167. this.getScene().simplificationQueue.addTask({
  24168. settings: settings,
  24169. parallelProcessing: parallelProcessing,
  24170. mesh: this,
  24171. simplificationType: simplificationType,
  24172. successCallback: successCallback
  24173. });
  24174. return this;
  24175. };
  24176. /**
  24177. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24178. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24179. * This should be used together with the simplification to avoid disappearing triangles.
  24180. * Returns the Mesh.
  24181. * @param successCallback an optional success callback to be called after the optimization finished.
  24182. */
  24183. Mesh.prototype.optimizeIndices = function (successCallback) {
  24184. var _this = this;
  24185. var indices = this.getIndices();
  24186. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24187. if (!positions || !indices) {
  24188. return this;
  24189. }
  24190. var vectorPositions = new Array();
  24191. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24192. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24193. }
  24194. var dupes = new Array();
  24195. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24196. var realPos = vectorPositions.length - 1 - iteration;
  24197. var testedPosition = vectorPositions[realPos];
  24198. for (var j = 0; j < realPos; ++j) {
  24199. var againstPosition = vectorPositions[j];
  24200. if (testedPosition.equals(againstPosition)) {
  24201. dupes[realPos] = j;
  24202. break;
  24203. }
  24204. }
  24205. }, function () {
  24206. for (var i = 0; i < indices.length; ++i) {
  24207. indices[i] = dupes[indices[i]] || indices[i];
  24208. }
  24209. //indices are now reordered
  24210. var originalSubMeshes = _this.subMeshes.slice(0);
  24211. _this.setIndices(indices);
  24212. _this.subMeshes = originalSubMeshes;
  24213. if (successCallback) {
  24214. successCallback(_this);
  24215. }
  24216. });
  24217. return this;
  24218. };
  24219. Mesh.prototype.serialize = function (serializationObject) {
  24220. serializationObject.name = this.name;
  24221. serializationObject.id = this.id;
  24222. serializationObject.type = this.getClassName();
  24223. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24224. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24225. }
  24226. serializationObject.position = this.position.asArray();
  24227. if (this.rotationQuaternion) {
  24228. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24229. }
  24230. else if (this.rotation) {
  24231. serializationObject.rotation = this.rotation.asArray();
  24232. }
  24233. serializationObject.scaling = this.scaling.asArray();
  24234. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24235. serializationObject.isEnabled = this.isEnabled();
  24236. serializationObject.isVisible = this.isVisible;
  24237. serializationObject.infiniteDistance = this.infiniteDistance;
  24238. serializationObject.pickable = this.isPickable;
  24239. serializationObject.receiveShadows = this.receiveShadows;
  24240. serializationObject.billboardMode = this.billboardMode;
  24241. serializationObject.visibility = this.visibility;
  24242. serializationObject.checkCollisions = this.checkCollisions;
  24243. serializationObject.isBlocker = this.isBlocker;
  24244. // Parent
  24245. if (this.parent) {
  24246. serializationObject.parentId = this.parent.id;
  24247. }
  24248. // Geometry
  24249. var geometry = this._geometry;
  24250. if (geometry) {
  24251. var geometryId = geometry.id;
  24252. serializationObject.geometryId = geometryId;
  24253. // SubMeshes
  24254. serializationObject.subMeshes = [];
  24255. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24256. var subMesh = this.subMeshes[subIndex];
  24257. serializationObject.subMeshes.push({
  24258. materialIndex: subMesh.materialIndex,
  24259. verticesStart: subMesh.verticesStart,
  24260. verticesCount: subMesh.verticesCount,
  24261. indexStart: subMesh.indexStart,
  24262. indexCount: subMesh.indexCount
  24263. });
  24264. }
  24265. }
  24266. // Material
  24267. if (this.material) {
  24268. serializationObject.materialId = this.material.id;
  24269. }
  24270. else {
  24271. this.material = null;
  24272. }
  24273. // Morph targets
  24274. if (this.morphTargetManager) {
  24275. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24276. }
  24277. // Skeleton
  24278. if (this.skeleton) {
  24279. serializationObject.skeletonId = this.skeleton.id;
  24280. }
  24281. // Physics
  24282. //TODO implement correct serialization for physics impostors.
  24283. var impostor = this.getPhysicsImpostor();
  24284. if (impostor) {
  24285. serializationObject.physicsMass = impostor.getParam("mass");
  24286. serializationObject.physicsFriction = impostor.getParam("friction");
  24287. serializationObject.physicsRestitution = impostor.getParam("mass");
  24288. serializationObject.physicsImpostor = impostor.type;
  24289. }
  24290. // Metadata
  24291. if (this.metadata) {
  24292. serializationObject.metadata = this.metadata;
  24293. }
  24294. // Instances
  24295. serializationObject.instances = [];
  24296. for (var index = 0; index < this.instances.length; index++) {
  24297. var instance = this.instances[index];
  24298. var serializationInstance = {
  24299. name: instance.name,
  24300. position: instance.position.asArray(),
  24301. scaling: instance.scaling.asArray()
  24302. };
  24303. if (instance.rotationQuaternion) {
  24304. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24305. }
  24306. else if (instance.rotation) {
  24307. serializationInstance.rotation = instance.rotation.asArray();
  24308. }
  24309. serializationObject.instances.push(serializationInstance);
  24310. // Animations
  24311. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24312. serializationInstance.ranges = instance.serializeAnimationRanges();
  24313. }
  24314. //
  24315. // Animations
  24316. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24317. serializationObject.ranges = this.serializeAnimationRanges();
  24318. // Layer mask
  24319. serializationObject.layerMask = this.layerMask;
  24320. // Alpha
  24321. serializationObject.alphaIndex = this.alphaIndex;
  24322. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24323. // Overlay
  24324. serializationObject.overlayAlpha = this.overlayAlpha;
  24325. serializationObject.overlayColor = this.overlayColor.asArray();
  24326. serializationObject.renderOverlay = this.renderOverlay;
  24327. // Fog
  24328. serializationObject.applyFog = this.applyFog;
  24329. // Action Manager
  24330. if (this.actionManager) {
  24331. serializationObject.actions = this.actionManager.serialize(this.name);
  24332. }
  24333. };
  24334. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24335. if (!this.geometry) {
  24336. return;
  24337. }
  24338. this._markSubMeshesAsAttributesDirty();
  24339. var morphTargetManager = this._morphTargetManager;
  24340. if (morphTargetManager && morphTargetManager.vertexCount) {
  24341. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24342. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24343. this.morphTargetManager = null;
  24344. return;
  24345. }
  24346. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24347. var morphTarget = morphTargetManager.getActiveTarget(index);
  24348. var positions = morphTarget.getPositions();
  24349. if (!positions) {
  24350. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24351. return;
  24352. }
  24353. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24354. var normals = morphTarget.getNormals();
  24355. if (normals) {
  24356. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24357. }
  24358. var tangents = morphTarget.getTangents();
  24359. if (tangents) {
  24360. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24361. }
  24362. }
  24363. }
  24364. else {
  24365. var index = 0;
  24366. // Positions
  24367. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24368. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24369. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24370. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24371. }
  24372. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24373. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24374. }
  24375. index++;
  24376. }
  24377. }
  24378. };
  24379. // Statics
  24380. /**
  24381. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24382. * The parameter `parsedMesh` is the mesh to be copied.
  24383. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24384. */
  24385. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24386. var mesh;
  24387. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24388. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24389. }
  24390. else {
  24391. mesh = new Mesh(parsedMesh.name, scene);
  24392. }
  24393. mesh.id = parsedMesh.id;
  24394. if (BABYLON.Tags) {
  24395. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24396. }
  24397. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24398. if (parsedMesh.metadata !== undefined) {
  24399. mesh.metadata = parsedMesh.metadata;
  24400. }
  24401. if (parsedMesh.rotationQuaternion) {
  24402. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24403. }
  24404. else if (parsedMesh.rotation) {
  24405. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24406. }
  24407. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24408. if (parsedMesh.localMatrix) {
  24409. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24410. }
  24411. else if (parsedMesh.pivotMatrix) {
  24412. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24413. }
  24414. mesh.setEnabled(parsedMesh.isEnabled);
  24415. mesh.isVisible = parsedMesh.isVisible;
  24416. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24417. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24418. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24419. if (parsedMesh.applyFog !== undefined) {
  24420. mesh.applyFog = parsedMesh.applyFog;
  24421. }
  24422. if (parsedMesh.pickable !== undefined) {
  24423. mesh.isPickable = parsedMesh.pickable;
  24424. }
  24425. if (parsedMesh.alphaIndex !== undefined) {
  24426. mesh.alphaIndex = parsedMesh.alphaIndex;
  24427. }
  24428. mesh.receiveShadows = parsedMesh.receiveShadows;
  24429. mesh.billboardMode = parsedMesh.billboardMode;
  24430. if (parsedMesh.visibility !== undefined) {
  24431. mesh.visibility = parsedMesh.visibility;
  24432. }
  24433. mesh.checkCollisions = parsedMesh.checkCollisions;
  24434. if (parsedMesh.isBlocker !== undefined) {
  24435. mesh.isBlocker = parsedMesh.isBlocker;
  24436. }
  24437. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24438. // freezeWorldMatrix
  24439. if (parsedMesh.freezeWorldMatrix) {
  24440. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24441. }
  24442. // Parent
  24443. if (parsedMesh.parentId) {
  24444. mesh._waitingParentId = parsedMesh.parentId;
  24445. }
  24446. // Actions
  24447. if (parsedMesh.actions !== undefined) {
  24448. mesh._waitingActions = parsedMesh.actions;
  24449. }
  24450. // Overlay
  24451. if (parsedMesh.overlayAlpha !== undefined) {
  24452. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24453. }
  24454. if (parsedMesh.overlayColor !== undefined) {
  24455. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24456. }
  24457. if (parsedMesh.renderOverlay !== undefined) {
  24458. mesh.renderOverlay = parsedMesh.renderOverlay;
  24459. }
  24460. // Geometry
  24461. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24462. if (parsedMesh.delayLoadingFile) {
  24463. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24464. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24465. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24466. if (parsedMesh._binaryInfo) {
  24467. mesh._binaryInfo = parsedMesh._binaryInfo;
  24468. }
  24469. mesh._delayInfo = [];
  24470. if (parsedMesh.hasUVs) {
  24471. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24472. }
  24473. if (parsedMesh.hasUVs2) {
  24474. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24475. }
  24476. if (parsedMesh.hasUVs3) {
  24477. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24478. }
  24479. if (parsedMesh.hasUVs4) {
  24480. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24481. }
  24482. if (parsedMesh.hasUVs5) {
  24483. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24484. }
  24485. if (parsedMesh.hasUVs6) {
  24486. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24487. }
  24488. if (parsedMesh.hasColors) {
  24489. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24490. }
  24491. if (parsedMesh.hasMatricesIndices) {
  24492. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24493. }
  24494. if (parsedMesh.hasMatricesWeights) {
  24495. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24496. }
  24497. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24498. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24499. mesh._checkDelayState();
  24500. }
  24501. }
  24502. else {
  24503. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24504. }
  24505. // Material
  24506. if (parsedMesh.materialId) {
  24507. mesh.setMaterialByID(parsedMesh.materialId);
  24508. }
  24509. else {
  24510. mesh.material = null;
  24511. }
  24512. // Morph targets
  24513. if (parsedMesh.morphTargetManagerId > -1) {
  24514. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24515. }
  24516. // Skeleton
  24517. if (parsedMesh.skeletonId > -1) {
  24518. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24519. if (parsedMesh.numBoneInfluencers) {
  24520. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24521. }
  24522. }
  24523. // Animations
  24524. if (parsedMesh.animations) {
  24525. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24526. var parsedAnimation = parsedMesh.animations[animationIndex];
  24527. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24528. }
  24529. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24530. }
  24531. if (parsedMesh.autoAnimate) {
  24532. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24533. }
  24534. // Layer Mask
  24535. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24536. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24537. }
  24538. else {
  24539. mesh.layerMask = 0x0FFFFFFF;
  24540. }
  24541. // Physics
  24542. if (parsedMesh.physicsImpostor) {
  24543. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24544. mass: parsedMesh.physicsMass,
  24545. friction: parsedMesh.physicsFriction,
  24546. restitution: parsedMesh.physicsRestitution
  24547. }, scene);
  24548. }
  24549. // Instances
  24550. if (parsedMesh.instances) {
  24551. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24552. var parsedInstance = parsedMesh.instances[index];
  24553. var instance = mesh.createInstance(parsedInstance.name);
  24554. if (BABYLON.Tags) {
  24555. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24556. }
  24557. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24558. if (parsedInstance.parentId) {
  24559. instance._waitingParentId = parsedInstance.parentId;
  24560. }
  24561. if (parsedInstance.rotationQuaternion) {
  24562. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24563. }
  24564. else if (parsedInstance.rotation) {
  24565. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24566. }
  24567. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24568. instance.checkCollisions = mesh.checkCollisions;
  24569. if (parsedMesh.animations) {
  24570. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24571. parsedAnimation = parsedMesh.animations[animationIndex];
  24572. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24573. }
  24574. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24575. }
  24576. }
  24577. }
  24578. return mesh;
  24579. };
  24580. /**
  24581. * Creates a ribbon mesh.
  24582. * Please consider using the same method from the MeshBuilder class instead.
  24583. * 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.
  24584. *
  24585. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24586. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24587. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24588. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24589. * 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.
  24590. * 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.
  24591. * 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
  24592. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24593. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24594. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24595. */
  24596. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24597. if (closeArray === void 0) { closeArray = false; }
  24598. if (updatable === void 0) { updatable = false; }
  24599. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24600. pathArray: pathArray,
  24601. closeArray: closeArray,
  24602. closePath: closePath,
  24603. offset: offset,
  24604. updatable: updatable,
  24605. sideOrientation: sideOrientation,
  24606. instance: instance
  24607. }, scene);
  24608. };
  24609. /**
  24610. * Creates a plane polygonal mesh. By default, this is a disc.
  24611. * Please consider using the same method from the MeshBuilder class instead.
  24612. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24613. * 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.
  24614. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24615. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24616. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24617. */
  24618. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24619. if (scene === void 0) { scene = null; }
  24620. var options = {
  24621. radius: radius,
  24622. tessellation: tessellation,
  24623. sideOrientation: sideOrientation,
  24624. updatable: updatable
  24625. };
  24626. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24627. };
  24628. /**
  24629. * Creates a box mesh.
  24630. * Please consider using the same method from the MeshBuilder class instead.
  24631. * The parameter `size` sets the size (float) of each box side (default 1).
  24632. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24633. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24634. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24635. */
  24636. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24637. if (scene === void 0) { scene = null; }
  24638. var options = {
  24639. size: size,
  24640. sideOrientation: sideOrientation,
  24641. updatable: updatable
  24642. };
  24643. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24644. };
  24645. /**
  24646. * Creates a sphere mesh.
  24647. * Please consider using the same method from the MeshBuilder class instead.
  24648. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24649. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24650. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24651. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24652. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24653. */
  24654. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24655. var options = {
  24656. segments: segments,
  24657. diameterX: diameter,
  24658. diameterY: diameter,
  24659. diameterZ: diameter,
  24660. sideOrientation: sideOrientation,
  24661. updatable: updatable
  24662. };
  24663. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24664. };
  24665. /**
  24666. * Creates a cylinder or a cone mesh.
  24667. * Please consider using the same method from the MeshBuilder class instead.
  24668. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24669. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24670. * 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.
  24671. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24672. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24673. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24674. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24675. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24676. */
  24677. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24678. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24679. if (scene !== undefined) {
  24680. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24681. updatable = scene;
  24682. }
  24683. scene = subdivisions;
  24684. subdivisions = 1;
  24685. }
  24686. var options = {
  24687. height: height,
  24688. diameterTop: diameterTop,
  24689. diameterBottom: diameterBottom,
  24690. tessellation: tessellation,
  24691. subdivisions: subdivisions,
  24692. sideOrientation: sideOrientation,
  24693. updatable: updatable
  24694. };
  24695. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24696. };
  24697. // Torus (Code from SharpDX.org)
  24698. /**
  24699. * Creates a torus mesh.
  24700. * Please consider using the same method from the MeshBuilder class instead.
  24701. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24702. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24703. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24704. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24705. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24706. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24707. */
  24708. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24709. var options = {
  24710. diameter: diameter,
  24711. thickness: thickness,
  24712. tessellation: tessellation,
  24713. sideOrientation: sideOrientation,
  24714. updatable: updatable
  24715. };
  24716. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24717. };
  24718. /**
  24719. * Creates a torus knot mesh.
  24720. * Please consider using the same method from the MeshBuilder class instead.
  24721. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24722. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24723. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24724. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24725. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24726. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24727. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24728. */
  24729. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24730. var options = {
  24731. radius: radius,
  24732. tube: tube,
  24733. radialSegments: radialSegments,
  24734. tubularSegments: tubularSegments,
  24735. p: p,
  24736. q: q,
  24737. sideOrientation: sideOrientation,
  24738. updatable: updatable
  24739. };
  24740. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24741. };
  24742. /**
  24743. * Creates a line mesh.
  24744. * Please consider using the same method from the MeshBuilder class instead.
  24745. * 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.
  24746. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24747. * The parameter `points` is an array successive Vector3.
  24748. * 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
  24749. * When updating an instance, remember that only point positions can change, not the number of points.
  24750. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24751. */
  24752. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24753. if (scene === void 0) { scene = null; }
  24754. if (updatable === void 0) { updatable = false; }
  24755. if (instance === void 0) { instance = null; }
  24756. var options = {
  24757. points: points,
  24758. updatable: updatable,
  24759. instance: instance
  24760. };
  24761. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24762. };
  24763. /**
  24764. * Creates a dashed line mesh.
  24765. * Please consider using the same method from the MeshBuilder class instead.
  24766. * 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.
  24767. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24768. * The parameter `points` is an array successive Vector3.
  24769. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24770. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24771. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24772. * 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
  24773. * When updating an instance, remember that only point positions can change, not the number of points.
  24774. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24775. */
  24776. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24777. if (scene === void 0) { scene = null; }
  24778. var options = {
  24779. points: points,
  24780. dashSize: dashSize,
  24781. gapSize: gapSize,
  24782. dashNb: dashNb,
  24783. updatable: updatable,
  24784. instance: instance
  24785. };
  24786. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24787. };
  24788. /**
  24789. * Creates a polygon mesh.
  24790. * Please consider using the same method from the MeshBuilder class instead.
  24791. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24792. * 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.
  24793. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24794. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24795. * Remember you can only change the shape positions, not their number when updating a polygon.
  24796. */
  24797. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24798. var options = {
  24799. shape: shape,
  24800. holes: holes,
  24801. updatable: updatable,
  24802. sideOrientation: sideOrientation
  24803. };
  24804. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24805. };
  24806. /**
  24807. * Creates an extruded polygon mesh, with depth in the Y direction.
  24808. * Please consider using the same method from the MeshBuilder class instead.
  24809. */
  24810. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24811. var options = {
  24812. shape: shape,
  24813. holes: holes,
  24814. depth: depth,
  24815. updatable: updatable,
  24816. sideOrientation: sideOrientation
  24817. };
  24818. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24819. };
  24820. /**
  24821. * Creates an extruded shape mesh.
  24822. * 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.
  24823. * Please consider using the same method from the MeshBuilder class instead.
  24824. *
  24825. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24826. * 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
  24827. * extruded along the Z axis.
  24828. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24829. * 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.
  24830. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24831. * 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
  24832. * 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
  24833. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24834. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24835. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24836. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24837. */
  24838. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24839. if (scene === void 0) { scene = null; }
  24840. var options = {
  24841. shape: shape,
  24842. path: path,
  24843. scale: scale,
  24844. rotation: rotation,
  24845. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24846. sideOrientation: sideOrientation,
  24847. instance: instance,
  24848. updatable: updatable
  24849. };
  24850. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24851. };
  24852. /**
  24853. * Creates an custom extruded shape mesh.
  24854. * 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.
  24855. * Please consider using the same method from the MeshBuilder class instead.
  24856. *
  24857. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24858. * 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
  24859. * extruded along the Z axis.
  24860. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24861. * 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
  24862. * and the distance of this point from the begining of the path :
  24863. * ```javascript
  24864. * var rotationFunction = function(i, distance) {
  24865. * // do things
  24866. * return rotationValue; }
  24867. * ```
  24868. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24869. * 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
  24870. * and the distance of this point from the begining of the path :
  24871. * ```javascript
  24872. * var scaleFunction = function(i, distance) {
  24873. * // do things
  24874. * return scaleValue;}
  24875. * ```
  24876. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24877. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24878. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24879. * 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
  24880. * 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
  24881. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24882. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24883. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24885. */
  24886. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24887. var options = {
  24888. shape: shape,
  24889. path: path,
  24890. scaleFunction: scaleFunction,
  24891. rotationFunction: rotationFunction,
  24892. ribbonCloseArray: ribbonCloseArray,
  24893. ribbonClosePath: ribbonClosePath,
  24894. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24895. sideOrientation: sideOrientation,
  24896. instance: instance,
  24897. updatable: updatable
  24898. };
  24899. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24900. };
  24901. /**
  24902. * Creates lathe mesh.
  24903. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24904. * Please consider using the same method from the MeshBuilder class instead.
  24905. * 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
  24906. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24907. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24908. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24909. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24910. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24911. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24912. */
  24913. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24914. var options = {
  24915. shape: shape,
  24916. radius: radius,
  24917. tessellation: tessellation,
  24918. sideOrientation: sideOrientation,
  24919. updatable: updatable
  24920. };
  24921. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24922. };
  24923. /**
  24924. * Creates a plane mesh.
  24925. * Please consider using the same method from the MeshBuilder class instead.
  24926. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24927. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24928. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24929. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24930. */
  24931. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24932. var options = {
  24933. size: size,
  24934. width: size,
  24935. height: size,
  24936. sideOrientation: sideOrientation,
  24937. updatable: updatable
  24938. };
  24939. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24940. };
  24941. /**
  24942. * Creates a ground mesh.
  24943. * Please consider using the same method from the MeshBuilder class instead.
  24944. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24945. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24947. */
  24948. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24949. var options = {
  24950. width: width,
  24951. height: height,
  24952. subdivisions: subdivisions,
  24953. updatable: updatable
  24954. };
  24955. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24956. };
  24957. /**
  24958. * Creates a tiled ground mesh.
  24959. * Please consider using the same method from the MeshBuilder class instead.
  24960. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24961. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24962. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24963. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24964. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24965. * numbers of subdivisions on the ground width and height of each tile.
  24966. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24967. */
  24968. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24969. var options = {
  24970. xmin: xmin,
  24971. zmin: zmin,
  24972. xmax: xmax,
  24973. zmax: zmax,
  24974. subdivisions: subdivisions,
  24975. precision: precision,
  24976. updatable: updatable
  24977. };
  24978. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24979. };
  24980. /**
  24981. * Creates a ground mesh from a height map.
  24982. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24983. * Please consider using the same method from the MeshBuilder class instead.
  24984. * The parameter `url` sets the URL of the height map image resource.
  24985. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24986. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24987. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24988. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24989. * 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).
  24990. * This function is passed the newly built mesh :
  24991. * ```javascript
  24992. * function(mesh) { // do things
  24993. * return; }
  24994. * ```
  24995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24996. */
  24997. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24998. var options = {
  24999. width: width,
  25000. height: height,
  25001. subdivisions: subdivisions,
  25002. minHeight: minHeight,
  25003. maxHeight: maxHeight,
  25004. updatable: updatable,
  25005. onReady: onReady
  25006. };
  25007. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25008. };
  25009. /**
  25010. * Creates a tube mesh.
  25011. * 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.
  25012. * Please consider using the same method from the MeshBuilder class instead.
  25013. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25014. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25015. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25016. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25017. * 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.
  25018. * It must return a radius value (positive float) :
  25019. * ```javascript
  25020. * var radiusFunction = function(i, distance) {
  25021. * // do things
  25022. * return radius; }
  25023. * ```
  25024. * 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
  25025. * 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
  25026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25027. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25029. */
  25030. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25031. var options = {
  25032. path: path,
  25033. radius: radius,
  25034. tessellation: tessellation,
  25035. radiusFunction: radiusFunction,
  25036. arc: 1,
  25037. cap: cap,
  25038. updatable: updatable,
  25039. sideOrientation: sideOrientation,
  25040. instance: instance
  25041. };
  25042. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25043. };
  25044. /**
  25045. * Creates a polyhedron mesh.
  25046. * Please consider using the same method from the MeshBuilder class instead.
  25047. * 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
  25048. * to choose the wanted type.
  25049. * The parameter `size` (positive float, default 1) sets the polygon size.
  25050. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25051. * 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`.
  25052. * 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
  25053. * 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)`).
  25054. * 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
  25055. * 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.
  25056. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25057. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25058. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25059. */
  25060. Mesh.CreatePolyhedron = function (name, options, scene) {
  25061. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25062. };
  25063. /**
  25064. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25065. * Please consider using the same method from the MeshBuilder class instead.
  25066. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25067. * 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`).
  25068. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25069. * 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.
  25070. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25071. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25072. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25073. */
  25074. Mesh.CreateIcoSphere = function (name, options, scene) {
  25075. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25076. };
  25077. /**
  25078. * Creates a decal mesh.
  25079. * Please consider using the same method from the MeshBuilder class instead.
  25080. * 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.
  25081. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25082. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25083. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25084. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25085. */
  25086. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25087. var options = {
  25088. position: position,
  25089. normal: normal,
  25090. size: size,
  25091. angle: angle
  25092. };
  25093. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25094. };
  25095. // Skeletons
  25096. /**
  25097. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25098. */
  25099. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25100. if (!this._sourcePositions) {
  25101. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25102. if (!source) {
  25103. return this._sourcePositions;
  25104. }
  25105. this._sourcePositions = new Float32Array(source);
  25106. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25107. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25108. }
  25109. }
  25110. return this._sourcePositions;
  25111. };
  25112. /**
  25113. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25114. */
  25115. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25116. if (!this._sourceNormals) {
  25117. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25118. if (!source) {
  25119. return this._sourceNormals;
  25120. }
  25121. this._sourceNormals = new Float32Array(source);
  25122. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25123. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25124. }
  25125. }
  25126. return this._sourceNormals;
  25127. };
  25128. /**
  25129. * Updates the vertex buffer by applying transformation from the bones.
  25130. * Returns the Mesh.
  25131. *
  25132. * @param {skeleton} skeleton to apply
  25133. */
  25134. Mesh.prototype.applySkeleton = function (skeleton) {
  25135. if (!this.geometry) {
  25136. return this;
  25137. }
  25138. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25139. return this;
  25140. }
  25141. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25142. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25143. return this;
  25144. }
  25145. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25146. return this;
  25147. }
  25148. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25149. return this;
  25150. }
  25151. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25152. return this;
  25153. }
  25154. if (!this._sourcePositions) {
  25155. var submeshes = this.subMeshes.slice();
  25156. this.setPositionsForCPUSkinning();
  25157. this.subMeshes = submeshes;
  25158. }
  25159. if (!this._sourceNormals) {
  25160. this.setNormalsForCPUSkinning();
  25161. }
  25162. // positionsData checks for not being Float32Array will only pass at most once
  25163. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25164. if (!positionsData) {
  25165. return this;
  25166. }
  25167. if (!(positionsData instanceof Float32Array)) {
  25168. positionsData = new Float32Array(positionsData);
  25169. }
  25170. // normalsData checks for not being Float32Array will only pass at most once
  25171. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25172. if (!normalsData) {
  25173. return this;
  25174. }
  25175. if (!(normalsData instanceof Float32Array)) {
  25176. normalsData = new Float32Array(normalsData);
  25177. }
  25178. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25179. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25180. if (!matricesWeightsData || !matricesIndicesData) {
  25181. return this;
  25182. }
  25183. var needExtras = this.numBoneInfluencers > 4;
  25184. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25185. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25186. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  25187. return this;
  25188. }
  25189. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25190. var tempVector3 = BABYLON.Vector3.Zero();
  25191. var finalMatrix = new BABYLON.Matrix();
  25192. var tempMatrix = new BABYLON.Matrix();
  25193. var matWeightIdx = 0;
  25194. var inf;
  25195. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25196. var weight;
  25197. for (inf = 0; inf < 4; inf++) {
  25198. weight = matricesWeightsData[matWeightIdx + inf];
  25199. if (weight > 0) {
  25200. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25201. finalMatrix.addToSelf(tempMatrix);
  25202. }
  25203. else
  25204. break;
  25205. }
  25206. if (needExtras) {
  25207. for (inf = 0; inf < 4; inf++) {
  25208. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25209. if (weight > 0) {
  25210. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25211. finalMatrix.addToSelf(tempMatrix);
  25212. }
  25213. else
  25214. break;
  25215. }
  25216. }
  25217. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25218. tempVector3.toArray(positionsData, index);
  25219. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25220. tempVector3.toArray(normalsData, index);
  25221. finalMatrix.reset();
  25222. }
  25223. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25224. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25225. return this;
  25226. };
  25227. // Tools
  25228. /**
  25229. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25230. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25231. */
  25232. Mesh.MinMax = function (meshes) {
  25233. var minVector = null;
  25234. var maxVector = null;
  25235. meshes.forEach(function (mesh, index, array) {
  25236. var boundingInfo = mesh.getBoundingInfo();
  25237. if (!boundingInfo) {
  25238. return;
  25239. }
  25240. var boundingBox = boundingInfo.boundingBox;
  25241. if (!minVector || !maxVector) {
  25242. minVector = boundingBox.minimumWorld;
  25243. maxVector = boundingBox.maximumWorld;
  25244. }
  25245. else {
  25246. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25247. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25248. }
  25249. });
  25250. if (!minVector || !maxVector) {
  25251. return {
  25252. min: BABYLON.Vector3.Zero(),
  25253. max: BABYLON.Vector3.Zero()
  25254. };
  25255. }
  25256. return {
  25257. min: minVector,
  25258. max: maxVector
  25259. };
  25260. };
  25261. /**
  25262. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25263. */
  25264. Mesh.Center = function (meshesOrMinMaxVector) {
  25265. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25266. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25267. };
  25268. /**
  25269. * Merge the array of meshes into a single mesh for performance reasons.
  25270. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25271. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25272. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25273. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25274. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25275. */
  25276. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25277. if (disposeSource === void 0) { disposeSource = true; }
  25278. var index;
  25279. if (!allow32BitsIndices) {
  25280. var totalVertices = 0;
  25281. // Counting vertices
  25282. for (index = 0; index < meshes.length; index++) {
  25283. if (meshes[index]) {
  25284. totalVertices += meshes[index].getTotalVertices();
  25285. if (totalVertices > 65536) {
  25286. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25287. return null;
  25288. }
  25289. }
  25290. }
  25291. }
  25292. // Merge
  25293. var vertexData = null;
  25294. var otherVertexData;
  25295. var indiceArray = new Array();
  25296. var source = null;
  25297. for (index = 0; index < meshes.length; index++) {
  25298. if (meshes[index]) {
  25299. meshes[index].computeWorldMatrix(true);
  25300. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25301. otherVertexData.transform(meshes[index].getWorldMatrix());
  25302. if (vertexData) {
  25303. vertexData.merge(otherVertexData);
  25304. }
  25305. else {
  25306. vertexData = otherVertexData;
  25307. source = meshes[index];
  25308. }
  25309. if (subdivideWithSubMeshes) {
  25310. indiceArray.push(meshes[index].getTotalIndices());
  25311. }
  25312. }
  25313. }
  25314. source = source;
  25315. if (!meshSubclass) {
  25316. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25317. }
  25318. vertexData.applyToMesh(meshSubclass);
  25319. // Setting properties
  25320. meshSubclass.material = source.material;
  25321. meshSubclass.checkCollisions = source.checkCollisions;
  25322. // Cleaning
  25323. if (disposeSource) {
  25324. for (index = 0; index < meshes.length; index++) {
  25325. if (meshes[index]) {
  25326. meshes[index].dispose();
  25327. }
  25328. }
  25329. }
  25330. // Subdivide
  25331. if (subdivideWithSubMeshes) {
  25332. //-- Suppresions du submesh global
  25333. meshSubclass.releaseSubMeshes();
  25334. index = 0;
  25335. var offset = 0;
  25336. //-- aplique la subdivision en fonction du tableau d'indices
  25337. while (index < indiceArray.length) {
  25338. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25339. offset += indiceArray[index];
  25340. index++;
  25341. }
  25342. }
  25343. return meshSubclass;
  25344. };
  25345. // Consts
  25346. Mesh._FRONTSIDE = 0;
  25347. Mesh._BACKSIDE = 1;
  25348. Mesh._DOUBLESIDE = 2;
  25349. Mesh._DEFAULTSIDE = 0;
  25350. Mesh._NO_CAP = 0;
  25351. Mesh._CAP_START = 1;
  25352. Mesh._CAP_END = 2;
  25353. Mesh._CAP_ALL = 3;
  25354. return Mesh;
  25355. }(BABYLON.AbstractMesh));
  25356. BABYLON.Mesh = Mesh;
  25357. })(BABYLON || (BABYLON = {}));
  25358. //# sourceMappingURL=babylon.mesh.js.map
  25359. var BABYLON;
  25360. (function (BABYLON) {
  25361. var BaseSubMesh = /** @class */ (function () {
  25362. function BaseSubMesh() {
  25363. }
  25364. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25365. get: function () {
  25366. return this._materialEffect;
  25367. },
  25368. enumerable: true,
  25369. configurable: true
  25370. });
  25371. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25372. if (defines === void 0) { defines = null; }
  25373. if (this._materialEffect === effect) {
  25374. if (!effect) {
  25375. this._materialDefines = null;
  25376. }
  25377. return;
  25378. }
  25379. this._materialDefines = defines;
  25380. this._materialEffect = effect;
  25381. };
  25382. return BaseSubMesh;
  25383. }());
  25384. BABYLON.BaseSubMesh = BaseSubMesh;
  25385. var SubMesh = /** @class */ (function (_super) {
  25386. __extends(SubMesh, _super);
  25387. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25388. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25389. var _this = _super.call(this) || this;
  25390. _this.materialIndex = materialIndex;
  25391. _this.verticesStart = verticesStart;
  25392. _this.verticesCount = verticesCount;
  25393. _this.indexStart = indexStart;
  25394. _this.indexCount = indexCount;
  25395. _this._renderId = 0;
  25396. _this._mesh = mesh;
  25397. _this._renderingMesh = renderingMesh || mesh;
  25398. mesh.subMeshes.push(_this);
  25399. _this._trianglePlanes = [];
  25400. _this._id = mesh.subMeshes.length - 1;
  25401. if (createBoundingBox) {
  25402. _this.refreshBoundingInfo();
  25403. mesh.computeWorldMatrix(true);
  25404. }
  25405. return _this;
  25406. }
  25407. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25408. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25409. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25410. };
  25411. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25412. get: function () {
  25413. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25414. },
  25415. enumerable: true,
  25416. configurable: true
  25417. });
  25418. /**
  25419. * Returns the submesh BoudingInfo object.
  25420. */
  25421. SubMesh.prototype.getBoundingInfo = function () {
  25422. if (this.IsGlobal) {
  25423. return this._mesh.getBoundingInfo();
  25424. }
  25425. return this._boundingInfo;
  25426. };
  25427. /**
  25428. * Sets the submesh BoundingInfo.
  25429. * Return the SubMesh.
  25430. */
  25431. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25432. this._boundingInfo = boundingInfo;
  25433. return this;
  25434. };
  25435. /**
  25436. * Returns the mesh of the current submesh.
  25437. */
  25438. SubMesh.prototype.getMesh = function () {
  25439. return this._mesh;
  25440. };
  25441. /**
  25442. * Returns the rendering mesh of the submesh.
  25443. */
  25444. SubMesh.prototype.getRenderingMesh = function () {
  25445. return this._renderingMesh;
  25446. };
  25447. /**
  25448. * Returns the submesh material.
  25449. */
  25450. SubMesh.prototype.getMaterial = function () {
  25451. var rootMaterial = this._renderingMesh.material;
  25452. if (rootMaterial && rootMaterial.getSubMaterial) {
  25453. var multiMaterial = rootMaterial;
  25454. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25455. if (this._currentMaterial !== effectiveMaterial) {
  25456. this._currentMaterial = effectiveMaterial;
  25457. this._materialDefines = null;
  25458. }
  25459. return effectiveMaterial;
  25460. }
  25461. if (!rootMaterial) {
  25462. return this._mesh.getScene().defaultMaterial;
  25463. }
  25464. return rootMaterial;
  25465. };
  25466. // Methods
  25467. /**
  25468. * Sets a new updated BoundingInfo object to the submesh.
  25469. * Returns the SubMesh.
  25470. */
  25471. SubMesh.prototype.refreshBoundingInfo = function () {
  25472. this._lastColliderWorldVertices = null;
  25473. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25474. return this;
  25475. }
  25476. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25477. if (!data) {
  25478. this._boundingInfo = this._mesh._boundingInfo;
  25479. return this;
  25480. }
  25481. var indices = this._renderingMesh.getIndices();
  25482. var extend;
  25483. //is this the only submesh?
  25484. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25485. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25486. if (!boundingInfo) {
  25487. return this;
  25488. }
  25489. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25490. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25491. }
  25492. else {
  25493. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25494. }
  25495. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25496. return this;
  25497. };
  25498. SubMesh.prototype._checkCollision = function (collider) {
  25499. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25500. if (!boundingInfo) {
  25501. return false;
  25502. }
  25503. return boundingInfo._checkCollision(collider);
  25504. };
  25505. /**
  25506. * Updates the submesh BoundingInfo.
  25507. * Returns the Submesh.
  25508. */
  25509. SubMesh.prototype.updateBoundingInfo = function (world) {
  25510. var boundingInfo = this.getBoundingInfo();
  25511. if (!boundingInfo) {
  25512. this.refreshBoundingInfo();
  25513. boundingInfo = this.getBoundingInfo();
  25514. }
  25515. boundingInfo.update(world);
  25516. return this;
  25517. };
  25518. /**
  25519. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25520. * Boolean returned.
  25521. */
  25522. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25523. var boundingInfo = this.getBoundingInfo();
  25524. if (!boundingInfo) {
  25525. return false;
  25526. }
  25527. return boundingInfo.isInFrustum(frustumPlanes);
  25528. };
  25529. /**
  25530. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25531. * Boolean returned.
  25532. */
  25533. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25534. var boundingInfo = this.getBoundingInfo();
  25535. if (!boundingInfo) {
  25536. return false;
  25537. }
  25538. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25539. };
  25540. /**
  25541. * Renders the submesh.
  25542. * Returns it.
  25543. */
  25544. SubMesh.prototype.render = function (enableAlphaMode) {
  25545. this._renderingMesh.render(this, enableAlphaMode);
  25546. return this;
  25547. };
  25548. /**
  25549. * Returns a new Index Buffer.
  25550. * Type returned : WebGLBuffer.
  25551. */
  25552. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25553. if (!this._linesIndexBuffer) {
  25554. var linesIndices = [];
  25555. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25556. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25557. }
  25558. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25559. this.linesIndexCount = linesIndices.length;
  25560. }
  25561. return this._linesIndexBuffer;
  25562. };
  25563. /**
  25564. * True is the passed Ray intersects the submesh bounding box.
  25565. * Boolean returned.
  25566. */
  25567. SubMesh.prototype.canIntersects = function (ray) {
  25568. var boundingInfo = this.getBoundingInfo();
  25569. if (!boundingInfo) {
  25570. return false;
  25571. }
  25572. return ray.intersectsBox(boundingInfo.boundingBox);
  25573. };
  25574. /**
  25575. * Returns an object IntersectionInfo.
  25576. */
  25577. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25578. var intersectInfo = null;
  25579. // LineMesh first as it's also a Mesh...
  25580. if (this._mesh instanceof BABYLON.LinesMesh) {
  25581. var lineMesh = this._mesh;
  25582. // Line test
  25583. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25584. var p0 = positions[indices[index]];
  25585. var p1 = positions[indices[index + 1]];
  25586. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25587. if (length < 0) {
  25588. continue;
  25589. }
  25590. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25591. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25592. if (fastCheck) {
  25593. break;
  25594. }
  25595. }
  25596. }
  25597. }
  25598. else {
  25599. // Triangles test
  25600. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25601. var p0 = positions[indices[index]];
  25602. var p1 = positions[indices[index + 1]];
  25603. var p2 = positions[indices[index + 2]];
  25604. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25605. if (currentIntersectInfo) {
  25606. if (currentIntersectInfo.distance < 0) {
  25607. continue;
  25608. }
  25609. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25610. intersectInfo = currentIntersectInfo;
  25611. intersectInfo.faceId = index / 3;
  25612. if (fastCheck) {
  25613. break;
  25614. }
  25615. }
  25616. }
  25617. }
  25618. }
  25619. return intersectInfo;
  25620. };
  25621. SubMesh.prototype._rebuild = function () {
  25622. if (this._linesIndexBuffer) {
  25623. this._linesIndexBuffer = null;
  25624. }
  25625. };
  25626. // Clone
  25627. /**
  25628. * Creates a new Submesh from the passed Mesh.
  25629. */
  25630. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25631. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25632. if (!this.IsGlobal) {
  25633. var boundingInfo = this.getBoundingInfo();
  25634. if (!boundingInfo) {
  25635. return result;
  25636. }
  25637. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  25638. }
  25639. return result;
  25640. };
  25641. // Dispose
  25642. /**
  25643. * Disposes the Submesh.
  25644. * Returns nothing.
  25645. */
  25646. SubMesh.prototype.dispose = function () {
  25647. if (this._linesIndexBuffer) {
  25648. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25649. this._linesIndexBuffer = null;
  25650. }
  25651. // Remove from mesh
  25652. var index = this._mesh.subMeshes.indexOf(this);
  25653. this._mesh.subMeshes.splice(index, 1);
  25654. };
  25655. // Statics
  25656. /**
  25657. * Creates a new Submesh from the passed parameters :
  25658. * - materialIndex (integer) : the index of the main mesh material.
  25659. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25660. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25661. * - mesh (Mesh) : the main mesh to create the submesh from.
  25662. * - renderingMesh (optional Mesh) : rendering mesh.
  25663. */
  25664. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25665. var minVertexIndex = Number.MAX_VALUE;
  25666. var maxVertexIndex = -Number.MAX_VALUE;
  25667. renderingMesh = (renderingMesh || mesh);
  25668. var indices = renderingMesh.getIndices();
  25669. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25670. var vertexIndex = indices[index];
  25671. if (vertexIndex < minVertexIndex)
  25672. minVertexIndex = vertexIndex;
  25673. if (vertexIndex > maxVertexIndex)
  25674. maxVertexIndex = vertexIndex;
  25675. }
  25676. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25677. };
  25678. return SubMesh;
  25679. }(BaseSubMesh));
  25680. BABYLON.SubMesh = SubMesh;
  25681. })(BABYLON || (BABYLON = {}));
  25682. //# sourceMappingURL=babylon.subMesh.js.map
  25683. var BABYLON;
  25684. (function (BABYLON) {
  25685. var EffectFallbacks = /** @class */ (function () {
  25686. function EffectFallbacks() {
  25687. this._defines = {};
  25688. this._currentRank = 32;
  25689. this._maxRank = -1;
  25690. }
  25691. EffectFallbacks.prototype.unBindMesh = function () {
  25692. this._mesh = null;
  25693. };
  25694. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25695. if (!this._defines[rank]) {
  25696. if (rank < this._currentRank) {
  25697. this._currentRank = rank;
  25698. }
  25699. if (rank > this._maxRank) {
  25700. this._maxRank = rank;
  25701. }
  25702. this._defines[rank] = new Array();
  25703. }
  25704. this._defines[rank].push(define);
  25705. };
  25706. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25707. this._meshRank = rank;
  25708. this._mesh = mesh;
  25709. if (rank < this._currentRank) {
  25710. this._currentRank = rank;
  25711. }
  25712. if (rank > this._maxRank) {
  25713. this._maxRank = rank;
  25714. }
  25715. };
  25716. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25717. get: function () {
  25718. return this._currentRank <= this._maxRank;
  25719. },
  25720. enumerable: true,
  25721. configurable: true
  25722. });
  25723. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25724. // First we try to switch to CPU skinning
  25725. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25726. this._mesh.computeBonesUsingShaders = false;
  25727. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25728. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25729. var scene = this._mesh.getScene();
  25730. for (var index = 0; index < scene.meshes.length; index++) {
  25731. var otherMesh = scene.meshes[index];
  25732. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25733. otherMesh.computeBonesUsingShaders = false;
  25734. }
  25735. }
  25736. }
  25737. else {
  25738. var currentFallbacks = this._defines[this._currentRank];
  25739. if (currentFallbacks) {
  25740. for (var index = 0; index < currentFallbacks.length; index++) {
  25741. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25742. }
  25743. }
  25744. this._currentRank++;
  25745. }
  25746. return currentDefines;
  25747. };
  25748. return EffectFallbacks;
  25749. }());
  25750. BABYLON.EffectFallbacks = EffectFallbacks;
  25751. var EffectCreationOptions = /** @class */ (function () {
  25752. function EffectCreationOptions() {
  25753. }
  25754. return EffectCreationOptions;
  25755. }());
  25756. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25757. var Effect = /** @class */ (function () {
  25758. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25759. if (samplers === void 0) { samplers = null; }
  25760. if (defines === void 0) { defines = null; }
  25761. if (fallbacks === void 0) { fallbacks = null; }
  25762. if (onCompiled === void 0) { onCompiled = null; }
  25763. if (onError === void 0) { onError = null; }
  25764. var _this = this;
  25765. this.uniqueId = 0;
  25766. this.onCompileObservable = new BABYLON.Observable();
  25767. this.onErrorObservable = new BABYLON.Observable();
  25768. this.onBindObservable = new BABYLON.Observable();
  25769. this._uniformBuffersNames = {};
  25770. this._isReady = false;
  25771. this._compilationError = "";
  25772. this.name = baseName;
  25773. if (attributesNamesOrOptions.attributes) {
  25774. var options = attributesNamesOrOptions;
  25775. this._engine = uniformsNamesOrEngine;
  25776. this._attributesNames = options.attributes;
  25777. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25778. this._samplers = options.samplers;
  25779. this.defines = options.defines;
  25780. this.onError = options.onError;
  25781. this.onCompiled = options.onCompiled;
  25782. this._fallbacks = options.fallbacks;
  25783. this._indexParameters = options.indexParameters;
  25784. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  25785. if (options.uniformBuffersNames) {
  25786. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25787. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25788. }
  25789. }
  25790. }
  25791. else {
  25792. this._engine = engine;
  25793. this.defines = defines;
  25794. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25795. this._samplers = samplers;
  25796. this._attributesNames = attributesNamesOrOptions;
  25797. this.onError = onError;
  25798. this.onCompiled = onCompiled;
  25799. this._indexParameters = indexParameters;
  25800. this._fallbacks = fallbacks;
  25801. }
  25802. this.uniqueId = Effect._uniqueIdSeed++;
  25803. var vertexSource;
  25804. var fragmentSource;
  25805. if (baseName.vertexElement) {
  25806. vertexSource = document.getElementById(baseName.vertexElement);
  25807. if (!vertexSource) {
  25808. vertexSource = baseName.vertexElement;
  25809. }
  25810. }
  25811. else {
  25812. vertexSource = baseName.vertex || baseName;
  25813. }
  25814. if (baseName.fragmentElement) {
  25815. fragmentSource = document.getElementById(baseName.fragmentElement);
  25816. if (!fragmentSource) {
  25817. fragmentSource = baseName.fragmentElement;
  25818. }
  25819. }
  25820. else {
  25821. fragmentSource = baseName.fragment || baseName;
  25822. }
  25823. this._loadVertexShader(vertexSource, function (vertexCode) {
  25824. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25825. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25826. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25827. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25828. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25829. if (baseName) {
  25830. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25831. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25832. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25833. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25834. }
  25835. else {
  25836. _this._vertexSourceCode = migratedVertexCode;
  25837. _this._fragmentSourceCode = migratedFragmentCode;
  25838. }
  25839. _this._prepareEffect();
  25840. });
  25841. });
  25842. });
  25843. });
  25844. });
  25845. });
  25846. }
  25847. Object.defineProperty(Effect.prototype, "key", {
  25848. get: function () {
  25849. return this._key;
  25850. },
  25851. enumerable: true,
  25852. configurable: true
  25853. });
  25854. // Properties
  25855. Effect.prototype.isReady = function () {
  25856. return this._isReady;
  25857. };
  25858. Effect.prototype.getEngine = function () {
  25859. return this._engine;
  25860. };
  25861. Effect.prototype.getProgram = function () {
  25862. return this._program;
  25863. };
  25864. Effect.prototype.getAttributesNames = function () {
  25865. return this._attributesNames;
  25866. };
  25867. Effect.prototype.getAttributeLocation = function (index) {
  25868. return this._attributes[index];
  25869. };
  25870. Effect.prototype.getAttributeLocationByName = function (name) {
  25871. var index = this._attributesNames.indexOf(name);
  25872. return this._attributes[index];
  25873. };
  25874. Effect.prototype.getAttributesCount = function () {
  25875. return this._attributes.length;
  25876. };
  25877. Effect.prototype.getUniformIndex = function (uniformName) {
  25878. return this._uniformsNames.indexOf(uniformName);
  25879. };
  25880. Effect.prototype.getUniform = function (uniformName) {
  25881. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25882. };
  25883. Effect.prototype.getSamplers = function () {
  25884. return this._samplers;
  25885. };
  25886. Effect.prototype.getCompilationError = function () {
  25887. return this._compilationError;
  25888. };
  25889. // Methods
  25890. Effect.prototype.executeWhenCompiled = function (func) {
  25891. if (this.isReady()) {
  25892. func(this);
  25893. return;
  25894. }
  25895. this.onCompileObservable.add(function (effect) {
  25896. func(effect);
  25897. });
  25898. };
  25899. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25900. if (BABYLON.Tools.IsWindowObjectExist()) {
  25901. // DOM element ?
  25902. if (vertex instanceof HTMLElement) {
  25903. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25904. callback(vertexCode);
  25905. return;
  25906. }
  25907. }
  25908. // Base64 encoded ?
  25909. if (vertex.substr(0, 7) === "base64:") {
  25910. var vertexBinary = window.atob(vertex.substr(7));
  25911. callback(vertexBinary);
  25912. return;
  25913. }
  25914. // Is in local store ?
  25915. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25916. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25917. return;
  25918. }
  25919. var vertexShaderUrl;
  25920. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25921. vertexShaderUrl = vertex;
  25922. }
  25923. else {
  25924. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25925. }
  25926. // Vertex shader
  25927. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25928. };
  25929. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25930. if (BABYLON.Tools.IsWindowObjectExist()) {
  25931. // DOM element ?
  25932. if (fragment instanceof HTMLElement) {
  25933. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25934. callback(fragmentCode);
  25935. return;
  25936. }
  25937. }
  25938. // Base64 encoded ?
  25939. if (fragment.substr(0, 7) === "base64:") {
  25940. var fragmentBinary = window.atob(fragment.substr(7));
  25941. callback(fragmentBinary);
  25942. return;
  25943. }
  25944. // Is in local store ?
  25945. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25946. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25947. return;
  25948. }
  25949. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25950. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25951. return;
  25952. }
  25953. var fragmentShaderUrl;
  25954. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25955. fragmentShaderUrl = fragment;
  25956. }
  25957. else {
  25958. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25959. }
  25960. // Fragment shader
  25961. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25962. };
  25963. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  25964. // Rebuild shaders source code
  25965. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  25966. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  25967. vertexCode = prefix + vertexCode;
  25968. fragmentCode = prefix + fragmentCode;
  25969. // Number lines of shaders source code
  25970. var i = 2;
  25971. var regex = /\n/gm;
  25972. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25973. i = 2;
  25974. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25975. // Dump shaders name and formatted source code
  25976. if (this.name.vertexElement) {
  25977. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  25978. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  25979. }
  25980. else if (this.name.vertex) {
  25981. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  25982. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  25983. }
  25984. else {
  25985. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  25986. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  25987. }
  25988. };
  25989. ;
  25990. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25991. var preparedSourceCode = this._processPrecision(sourceCode);
  25992. if (this._engine.webGLVersion == 1) {
  25993. callback(preparedSourceCode);
  25994. return;
  25995. }
  25996. // Already converted
  25997. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25998. callback(preparedSourceCode.replace("#version 300 es", ""));
  25999. return;
  26000. }
  26001. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  26002. // Remove extensions
  26003. // #extension GL_OES_standard_derivatives : enable
  26004. // #extension GL_EXT_shader_texture_lod : enable
  26005. // #extension GL_EXT_frag_depth : enable
  26006. // #extension GL_EXT_draw_buffers : require
  26007. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  26008. var result = preparedSourceCode.replace(regex, "");
  26009. // Migrate to GLSL v300
  26010. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  26011. result = result.replace(/attribute[ \t]/g, "in ");
  26012. result = result.replace(/[ \t]attribute/g, " in");
  26013. if (isFragment) {
  26014. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  26015. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  26016. result = result.replace(/texture2D\s*\(/g, "texture(");
  26017. result = result.replace(/textureCube\s*\(/g, "texture(");
  26018. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26019. result = result.replace(/gl_FragColor/g, "glFragColor");
  26020. result = result.replace(/gl_FragData/g, "glFragData");
  26021. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  26022. }
  26023. callback(result);
  26024. };
  26025. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26026. var _this = this;
  26027. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26028. var match = regex.exec(sourceCode);
  26029. var returnValue = new String(sourceCode);
  26030. while (match != null) {
  26031. var includeFile = match[1];
  26032. // Uniform declaration
  26033. if (includeFile.indexOf("__decl__") !== -1) {
  26034. includeFile = includeFile.replace(/__decl__/, "");
  26035. if (this._engine.supportsUniformBuffers) {
  26036. includeFile = includeFile.replace(/Vertex/, "Ubo");
  26037. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26038. }
  26039. includeFile = includeFile + "Declaration";
  26040. }
  26041. if (Effect.IncludesShadersStore[includeFile]) {
  26042. // Substitution
  26043. var includeContent = Effect.IncludesShadersStore[includeFile];
  26044. if (match[2]) {
  26045. var splits = match[3].split(",");
  26046. for (var index = 0; index < splits.length; index += 2) {
  26047. var source = new RegExp(splits[index], "g");
  26048. var dest = splits[index + 1];
  26049. includeContent = includeContent.replace(source, dest);
  26050. }
  26051. }
  26052. if (match[4]) {
  26053. var indexString = match[5];
  26054. if (indexString.indexOf("..") !== -1) {
  26055. var indexSplits = indexString.split("..");
  26056. var minIndex = parseInt(indexSplits[0]);
  26057. var maxIndex = parseInt(indexSplits[1]);
  26058. var sourceIncludeContent = includeContent.slice(0);
  26059. includeContent = "";
  26060. if (isNaN(maxIndex)) {
  26061. maxIndex = this._indexParameters[indexSplits[1]];
  26062. }
  26063. for (var i = minIndex; i < maxIndex; i++) {
  26064. if (!this._engine.supportsUniformBuffers) {
  26065. // Ubo replacement
  26066. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26067. return p1 + "{X}";
  26068. });
  26069. }
  26070. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26071. }
  26072. }
  26073. else {
  26074. if (!this._engine.supportsUniformBuffers) {
  26075. // Ubo replacement
  26076. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26077. return p1 + "{X}";
  26078. });
  26079. }
  26080. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26081. }
  26082. }
  26083. // Replace
  26084. returnValue = returnValue.replace(match[0], includeContent);
  26085. }
  26086. else {
  26087. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26088. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26089. Effect.IncludesShadersStore[includeFile] = fileContent;
  26090. _this._processIncludes(returnValue, callback);
  26091. });
  26092. return;
  26093. }
  26094. match = regex.exec(sourceCode);
  26095. }
  26096. callback(returnValue);
  26097. };
  26098. Effect.prototype._processPrecision = function (source) {
  26099. if (source.indexOf("precision highp float") === -1) {
  26100. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26101. source = "precision mediump float;\n" + source;
  26102. }
  26103. else {
  26104. source = "precision highp float;\n" + source;
  26105. }
  26106. }
  26107. else {
  26108. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26109. source = source.replace("precision highp float", "precision mediump float");
  26110. }
  26111. }
  26112. return source;
  26113. };
  26114. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26115. var _this = this;
  26116. this._isReady = false;
  26117. this._vertexSourceCodeOverride = vertexSourceCode;
  26118. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26119. this.onError = function (effect, error) {
  26120. if (onError) {
  26121. onError(error);
  26122. }
  26123. };
  26124. this.onCompiled = function () {
  26125. var scenes = _this.getEngine().scenes;
  26126. for (var i = 0; i < scenes.length; i++) {
  26127. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26128. }
  26129. if (onCompiled) {
  26130. onCompiled(_this._program);
  26131. }
  26132. };
  26133. this._fallbacks = null;
  26134. this._prepareEffect();
  26135. };
  26136. Effect.prototype._prepareEffect = function () {
  26137. var attributesNames = this._attributesNames;
  26138. var defines = this.defines;
  26139. var fallbacks = this._fallbacks;
  26140. this._valueCache = {};
  26141. var previousProgram = this._program;
  26142. try {
  26143. var engine = this._engine;
  26144. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26145. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26146. }
  26147. else {
  26148. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26149. }
  26150. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26151. if (engine.webGLVersion > 1) {
  26152. for (var name in this._uniformBuffersNames) {
  26153. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26154. }
  26155. }
  26156. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26157. this._attributes = engine.getAttributes(this._program, attributesNames);
  26158. var index;
  26159. for (index = 0; index < this._samplers.length; index++) {
  26160. var sampler = this.getUniform(this._samplers[index]);
  26161. if (sampler == null) {
  26162. this._samplers.splice(index, 1);
  26163. index--;
  26164. }
  26165. }
  26166. engine.bindSamplers(this);
  26167. this._compilationError = "";
  26168. this._isReady = true;
  26169. if (this.onCompiled) {
  26170. this.onCompiled(this);
  26171. }
  26172. this.onCompileObservable.notifyObservers(this);
  26173. this.onCompileObservable.clear();
  26174. // Unbind mesh reference in fallbacks
  26175. if (this._fallbacks) {
  26176. this._fallbacks.unBindMesh();
  26177. }
  26178. if (previousProgram) {
  26179. this.getEngine()._deleteProgram(previousProgram);
  26180. }
  26181. }
  26182. catch (e) {
  26183. this._compilationError = e.message;
  26184. // Let's go through fallbacks then
  26185. BABYLON.Tools.Error("Unable to compile effect:");
  26186. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26187. return " " + uniform;
  26188. }));
  26189. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26190. return " " + attribute;
  26191. }));
  26192. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26193. BABYLON.Tools.Error("Error: " + this._compilationError);
  26194. if (previousProgram) {
  26195. this._program = previousProgram;
  26196. this._isReady = true;
  26197. if (this.onError) {
  26198. this.onError(this, this._compilationError);
  26199. }
  26200. this.onErrorObservable.notifyObservers(this);
  26201. }
  26202. if (fallbacks && fallbacks.isMoreFallbacks) {
  26203. BABYLON.Tools.Error("Trying next fallback.");
  26204. this.defines = fallbacks.reduce(this.defines);
  26205. this._prepareEffect();
  26206. }
  26207. else {
  26208. if (this.onError) {
  26209. this.onError(this, this._compilationError);
  26210. }
  26211. this.onErrorObservable.notifyObservers(this);
  26212. this.onErrorObservable.clear();
  26213. // Unbind mesh reference in fallbacks
  26214. if (this._fallbacks) {
  26215. this._fallbacks.unBindMesh();
  26216. }
  26217. }
  26218. }
  26219. };
  26220. Object.defineProperty(Effect.prototype, "isSupported", {
  26221. get: function () {
  26222. return this._compilationError === "";
  26223. },
  26224. enumerable: true,
  26225. configurable: true
  26226. });
  26227. Effect.prototype._bindTexture = function (channel, texture) {
  26228. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26229. };
  26230. Effect.prototype.setTexture = function (channel, texture) {
  26231. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26232. };
  26233. Effect.prototype.setTextureArray = function (channel, textures) {
  26234. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26235. var initialPos = this._samplers.indexOf(channel);
  26236. for (var index = 1; index < textures.length; index++) {
  26237. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26238. }
  26239. }
  26240. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26241. };
  26242. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26243. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26244. };
  26245. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26246. var cache = this._valueCache[uniformName];
  26247. var flag = matrix.updateFlag;
  26248. if (cache !== undefined && cache === flag) {
  26249. return false;
  26250. }
  26251. this._valueCache[uniformName] = flag;
  26252. return true;
  26253. };
  26254. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26255. var cache = this._valueCache[uniformName];
  26256. if (!cache) {
  26257. cache = [x, y];
  26258. this._valueCache[uniformName] = cache;
  26259. return true;
  26260. }
  26261. var changed = false;
  26262. if (cache[0] !== x) {
  26263. cache[0] = x;
  26264. changed = true;
  26265. }
  26266. if (cache[1] !== y) {
  26267. cache[1] = y;
  26268. changed = true;
  26269. }
  26270. return changed;
  26271. };
  26272. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26273. var cache = this._valueCache[uniformName];
  26274. if (!cache) {
  26275. cache = [x, y, z];
  26276. this._valueCache[uniformName] = cache;
  26277. return true;
  26278. }
  26279. var changed = false;
  26280. if (cache[0] !== x) {
  26281. cache[0] = x;
  26282. changed = true;
  26283. }
  26284. if (cache[1] !== y) {
  26285. cache[1] = y;
  26286. changed = true;
  26287. }
  26288. if (cache[2] !== z) {
  26289. cache[2] = z;
  26290. changed = true;
  26291. }
  26292. return changed;
  26293. };
  26294. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26295. var cache = this._valueCache[uniformName];
  26296. if (!cache) {
  26297. cache = [x, y, z, w];
  26298. this._valueCache[uniformName] = cache;
  26299. return true;
  26300. }
  26301. var changed = false;
  26302. if (cache[0] !== x) {
  26303. cache[0] = x;
  26304. changed = true;
  26305. }
  26306. if (cache[1] !== y) {
  26307. cache[1] = y;
  26308. changed = true;
  26309. }
  26310. if (cache[2] !== z) {
  26311. cache[2] = z;
  26312. changed = true;
  26313. }
  26314. if (cache[3] !== w) {
  26315. cache[3] = w;
  26316. changed = true;
  26317. }
  26318. return changed;
  26319. };
  26320. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26321. var bufferName = this._uniformBuffersNames[name];
  26322. if (Effect._baseCache[bufferName] === buffer) {
  26323. return;
  26324. }
  26325. Effect._baseCache[bufferName] = buffer;
  26326. this._engine.bindUniformBufferBase(buffer, bufferName);
  26327. };
  26328. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26329. this._engine.bindUniformBlock(this._program, blockName, index);
  26330. };
  26331. Effect.prototype.setIntArray = function (uniformName, array) {
  26332. this._valueCache[uniformName] = null;
  26333. this._engine.setIntArray(this.getUniform(uniformName), array);
  26334. return this;
  26335. };
  26336. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26337. this._valueCache[uniformName] = null;
  26338. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26339. return this;
  26340. };
  26341. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26342. this._valueCache[uniformName] = null;
  26343. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26344. return this;
  26345. };
  26346. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26347. this._valueCache[uniformName] = null;
  26348. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26349. return this;
  26350. };
  26351. Effect.prototype.setFloatArray = function (uniformName, array) {
  26352. this._valueCache[uniformName] = null;
  26353. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26354. return this;
  26355. };
  26356. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26357. this._valueCache[uniformName] = null;
  26358. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26359. return this;
  26360. };
  26361. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26362. this._valueCache[uniformName] = null;
  26363. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26364. return this;
  26365. };
  26366. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26367. this._valueCache[uniformName] = null;
  26368. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26369. return this;
  26370. };
  26371. Effect.prototype.setArray = function (uniformName, array) {
  26372. this._valueCache[uniformName] = null;
  26373. this._engine.setArray(this.getUniform(uniformName), array);
  26374. return this;
  26375. };
  26376. Effect.prototype.setArray2 = function (uniformName, array) {
  26377. this._valueCache[uniformName] = null;
  26378. this._engine.setArray2(this.getUniform(uniformName), array);
  26379. return this;
  26380. };
  26381. Effect.prototype.setArray3 = function (uniformName, array) {
  26382. this._valueCache[uniformName] = null;
  26383. this._engine.setArray3(this.getUniform(uniformName), array);
  26384. return this;
  26385. };
  26386. Effect.prototype.setArray4 = function (uniformName, array) {
  26387. this._valueCache[uniformName] = null;
  26388. this._engine.setArray4(this.getUniform(uniformName), array);
  26389. return this;
  26390. };
  26391. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26392. if (!matrices) {
  26393. return this;
  26394. }
  26395. this._valueCache[uniformName] = null;
  26396. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26397. return this;
  26398. };
  26399. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26400. if (this._cacheMatrix(uniformName, matrix)) {
  26401. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26402. }
  26403. return this;
  26404. };
  26405. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26406. this._valueCache[uniformName] = null;
  26407. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26408. return this;
  26409. };
  26410. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26411. this._valueCache[uniformName] = null;
  26412. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26413. return this;
  26414. };
  26415. Effect.prototype.setFloat = function (uniformName, value) {
  26416. var cache = this._valueCache[uniformName];
  26417. if (cache !== undefined && cache === value)
  26418. return this;
  26419. this._valueCache[uniformName] = value;
  26420. this._engine.setFloat(this.getUniform(uniformName), value);
  26421. return this;
  26422. };
  26423. Effect.prototype.setBool = function (uniformName, bool) {
  26424. var cache = this._valueCache[uniformName];
  26425. if (cache !== undefined && cache === bool)
  26426. return this;
  26427. this._valueCache[uniformName] = bool;
  26428. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26429. return this;
  26430. };
  26431. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26432. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26433. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26434. }
  26435. return this;
  26436. };
  26437. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26438. if (this._cacheFloat2(uniformName, x, y)) {
  26439. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26440. }
  26441. return this;
  26442. };
  26443. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26444. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26445. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26446. }
  26447. return this;
  26448. };
  26449. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26450. if (this._cacheFloat3(uniformName, x, y, z)) {
  26451. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26452. }
  26453. return this;
  26454. };
  26455. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26456. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26457. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26458. }
  26459. return this;
  26460. };
  26461. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26462. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26463. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26464. }
  26465. return this;
  26466. };
  26467. Effect.prototype.setColor3 = function (uniformName, color3) {
  26468. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26469. this._engine.setColor3(this.getUniform(uniformName), color3);
  26470. }
  26471. return this;
  26472. };
  26473. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26474. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26475. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26476. }
  26477. return this;
  26478. };
  26479. Effect.ResetCache = function () {
  26480. Effect._baseCache = {};
  26481. };
  26482. Effect._uniqueIdSeed = 0;
  26483. Effect._baseCache = {};
  26484. // Statics
  26485. Effect.ShadersStore = {};
  26486. Effect.IncludesShadersStore = {};
  26487. return Effect;
  26488. }());
  26489. BABYLON.Effect = Effect;
  26490. })(BABYLON || (BABYLON = {}));
  26491. //# sourceMappingURL=babylon.effect.js.map
  26492. var BABYLON;
  26493. (function (BABYLON) {
  26494. var MaterialHelper = /** @class */ (function () {
  26495. function MaterialHelper() {
  26496. }
  26497. MaterialHelper.BindEyePosition = function (effect, scene) {
  26498. if (scene._forcedViewPosition) {
  26499. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26500. return;
  26501. }
  26502. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26503. };
  26504. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26505. defines._needUVs = true;
  26506. defines[key] = true;
  26507. if (texture.getTextureMatrix().isIdentity(true)) {
  26508. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26509. if (texture.coordinatesIndex === 0) {
  26510. defines["MAINUV1"] = true;
  26511. }
  26512. else {
  26513. defines["MAINUV2"] = true;
  26514. }
  26515. }
  26516. else {
  26517. defines[key + "DIRECTUV"] = 0;
  26518. }
  26519. };
  26520. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26521. var matrix = texture.getTextureMatrix();
  26522. if (!matrix.isIdentity(true)) {
  26523. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26524. }
  26525. };
  26526. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26527. if (defines._areMiscDirty) {
  26528. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26529. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26530. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26531. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26532. }
  26533. };
  26534. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26535. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26536. var changed = false;
  26537. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26538. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26539. changed = true;
  26540. }
  26541. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26542. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26543. changed = true;
  26544. }
  26545. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26546. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26547. changed = true;
  26548. }
  26549. if (defines["INSTANCES"] !== useInstances) {
  26550. defines["INSTANCES"] = useInstances;
  26551. changed = true;
  26552. }
  26553. if (changed) {
  26554. defines.markAsUnprocessed();
  26555. }
  26556. };
  26557. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  26558. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26559. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  26560. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26561. return false;
  26562. }
  26563. defines._normals = defines._needNormals;
  26564. defines._uvs = defines._needUVs;
  26565. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26566. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26567. defines["TANGENT"] = true;
  26568. }
  26569. if (defines._needUVs) {
  26570. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26571. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26572. }
  26573. else {
  26574. defines["UV1"] = false;
  26575. defines["UV2"] = false;
  26576. }
  26577. if (useVertexColor) {
  26578. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26579. defines["VERTEXCOLOR"] = hasVertexColors;
  26580. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  26581. }
  26582. if (useBones) {
  26583. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26584. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26585. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26586. }
  26587. else {
  26588. defines["NUM_BONE_INFLUENCERS"] = 0;
  26589. defines["BonesPerMesh"] = 0;
  26590. }
  26591. }
  26592. if (useMorphTargets) {
  26593. var manager = mesh.morphTargetManager;
  26594. if (manager) {
  26595. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  26596. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  26597. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  26598. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  26599. }
  26600. else {
  26601. defines["MORPHTARGETS_TANGENT"] = false;
  26602. defines["MORPHTARGETS_NORMAL"] = false;
  26603. defines["MORPHTARGETS"] = false;
  26604. defines["NUM_MORPH_INFLUENCERS"] = 0;
  26605. }
  26606. }
  26607. return true;
  26608. };
  26609. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  26610. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26611. if (disableLighting === void 0) { disableLighting = false; }
  26612. if (!defines._areLightsDirty) {
  26613. return defines._needNormals;
  26614. }
  26615. var lightIndex = 0;
  26616. var needNormals = false;
  26617. var needRebuild = false;
  26618. var lightmapMode = false;
  26619. var shadowEnabled = false;
  26620. var specularEnabled = false;
  26621. if (scene.lightsEnabled && !disableLighting) {
  26622. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26623. var light = _a[_i];
  26624. needNormals = true;
  26625. if (defines["LIGHT" + lightIndex] === undefined) {
  26626. needRebuild = true;
  26627. }
  26628. defines["LIGHT" + lightIndex] = true;
  26629. defines["SPOTLIGHT" + lightIndex] = false;
  26630. defines["HEMILIGHT" + lightIndex] = false;
  26631. defines["POINTLIGHT" + lightIndex] = false;
  26632. defines["DIRLIGHT" + lightIndex] = false;
  26633. var type;
  26634. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  26635. type = "SPOTLIGHT" + lightIndex;
  26636. }
  26637. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  26638. type = "HEMILIGHT" + lightIndex;
  26639. }
  26640. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  26641. type = "POINTLIGHT" + lightIndex;
  26642. }
  26643. else {
  26644. type = "DIRLIGHT" + lightIndex;
  26645. }
  26646. defines[type] = true;
  26647. // Specular
  26648. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  26649. specularEnabled = true;
  26650. }
  26651. // Shadows
  26652. defines["SHADOW" + lightIndex] = false;
  26653. defines["SHADOWPCF" + lightIndex] = false;
  26654. defines["SHADOWESM" + lightIndex] = false;
  26655. defines["SHADOWCUBE" + lightIndex] = false;
  26656. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  26657. var shadowGenerator = light.getShadowGenerator();
  26658. if (shadowGenerator) {
  26659. shadowEnabled = true;
  26660. shadowGenerator.prepareDefines(defines, lightIndex);
  26661. }
  26662. }
  26663. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26664. lightmapMode = true;
  26665. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26666. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  26667. }
  26668. else {
  26669. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  26670. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  26671. }
  26672. lightIndex++;
  26673. if (lightIndex === maxSimultaneousLights)
  26674. break;
  26675. }
  26676. }
  26677. defines["SPECULARTERM"] = specularEnabled;
  26678. defines["SHADOWS"] = shadowEnabled;
  26679. // Resetting all other lights if any
  26680. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26681. if (defines["LIGHT" + index] !== undefined) {
  26682. defines["LIGHT" + index] = false;
  26683. defines["HEMILIGHT" + lightIndex] = false;
  26684. defines["POINTLIGHT" + lightIndex] = false;
  26685. defines["DIRLIGHT" + lightIndex] = false;
  26686. defines["SPOTLIGHT" + lightIndex] = false;
  26687. defines["SHADOW" + lightIndex] = false;
  26688. }
  26689. }
  26690. var caps = scene.getEngine().getCaps();
  26691. if (defines["SHADOWFLOAT"] === undefined) {
  26692. needRebuild = true;
  26693. }
  26694. defines["SHADOWFLOAT"] = shadowEnabled &&
  26695. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26696. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26697. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26698. if (needRebuild) {
  26699. defines.rebuild();
  26700. }
  26701. return needNormals;
  26702. };
  26703. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26704. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26705. var uniformsList;
  26706. var uniformBuffersList = null;
  26707. if (uniformsListOrOptions.uniformsNames) {
  26708. var options = uniformsListOrOptions;
  26709. uniformsList = options.uniformsNames;
  26710. uniformBuffersList = options.uniformBuffersNames;
  26711. samplersList = options.samplers;
  26712. defines = options.defines;
  26713. maxSimultaneousLights = options.maxSimultaneousLights;
  26714. }
  26715. else {
  26716. uniformsList = uniformsListOrOptions;
  26717. if (!samplersList) {
  26718. samplersList = [];
  26719. }
  26720. }
  26721. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26722. if (!defines["LIGHT" + lightIndex]) {
  26723. break;
  26724. }
  26725. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26726. if (uniformBuffersList) {
  26727. uniformBuffersList.push("Light" + lightIndex);
  26728. }
  26729. samplersList.push("shadowSampler" + lightIndex);
  26730. }
  26731. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26732. uniformsList.push("morphTargetInfluences");
  26733. }
  26734. };
  26735. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  26736. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26737. if (rank === void 0) { rank = 0; }
  26738. var lightFallbackRank = 0;
  26739. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26740. if (!defines["LIGHT" + lightIndex]) {
  26741. break;
  26742. }
  26743. if (lightIndex > 0) {
  26744. lightFallbackRank = rank + lightIndex;
  26745. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  26746. }
  26747. if (!defines["SHADOWS"]) {
  26748. if (defines["SHADOW" + lightIndex]) {
  26749. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  26750. }
  26751. if (defines["SHADOWPCF" + lightIndex]) {
  26752. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  26753. }
  26754. if (defines["SHADOWESM" + lightIndex]) {
  26755. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  26756. }
  26757. }
  26758. }
  26759. return lightFallbackRank++;
  26760. };
  26761. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26762. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26763. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  26764. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26765. var manager = mesh.morphTargetManager;
  26766. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  26767. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  26768. for (var index = 0; index < influencers; index++) {
  26769. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26770. if (normal) {
  26771. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26772. }
  26773. if (tangent) {
  26774. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26775. }
  26776. if (attribs.length > maxAttributesCount) {
  26777. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26778. }
  26779. }
  26780. }
  26781. };
  26782. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26783. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26784. fallbacks.addCPUSkinningFallback(0, mesh);
  26785. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26786. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26787. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26788. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26789. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26790. }
  26791. }
  26792. };
  26793. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26794. if (defines["INSTANCES"]) {
  26795. attribs.push("world0");
  26796. attribs.push("world1");
  26797. attribs.push("world2");
  26798. attribs.push("world3");
  26799. }
  26800. };
  26801. // Bindings
  26802. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26803. if (light.shadowEnabled && mesh.receiveShadows) {
  26804. var shadowGenerator = light.getShadowGenerator();
  26805. if (shadowGenerator) {
  26806. shadowGenerator.bindShadowLight(lightIndex, effect);
  26807. }
  26808. }
  26809. };
  26810. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26811. light.transferToEffect(effect, lightIndex + "");
  26812. };
  26813. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26814. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26815. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26816. var lightIndex = 0;
  26817. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26818. var light = _a[_i];
  26819. var scaledIntensity = light.getScaledIntensity();
  26820. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26821. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26822. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26823. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26824. if (defines["SPECULARTERM"]) {
  26825. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26826. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26827. }
  26828. // Shadows
  26829. if (scene.shadowsEnabled) {
  26830. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26831. }
  26832. light._uniformBuffer.update();
  26833. lightIndex++;
  26834. if (lightIndex === maxSimultaneousLights)
  26835. break;
  26836. }
  26837. };
  26838. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26839. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26840. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26841. effect.setColor3("vFogColor", scene.fogColor);
  26842. }
  26843. };
  26844. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26845. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26846. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26847. if (matrices && effect) {
  26848. effect.setMatrices("mBones", matrices);
  26849. }
  26850. }
  26851. };
  26852. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26853. var manager = abstractMesh.morphTargetManager;
  26854. if (!abstractMesh || !manager) {
  26855. return;
  26856. }
  26857. effect.setFloatArray("morphTargetInfluences", manager.influences);
  26858. };
  26859. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26860. if (defines["LOGARITHMICDEPTH"]) {
  26861. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26862. }
  26863. };
  26864. MaterialHelper.BindClipPlane = function (effect, scene) {
  26865. if (scene.clipPlane) {
  26866. var clipPlane = scene.clipPlane;
  26867. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26868. }
  26869. };
  26870. return MaterialHelper;
  26871. }());
  26872. BABYLON.MaterialHelper = MaterialHelper;
  26873. })(BABYLON || (BABYLON = {}));
  26874. //# sourceMappingURL=babylon.materialHelper.js.map
  26875. var BABYLON;
  26876. (function (BABYLON) {
  26877. var MaterialDefines = /** @class */ (function () {
  26878. function MaterialDefines() {
  26879. this._isDirty = true;
  26880. this._areLightsDirty = true;
  26881. this._areAttributesDirty = true;
  26882. this._areTexturesDirty = true;
  26883. this._areFresnelDirty = true;
  26884. this._areMiscDirty = true;
  26885. this._areImageProcessingDirty = true;
  26886. this._normals = false;
  26887. this._uvs = false;
  26888. this._needNormals = false;
  26889. this._needUVs = false;
  26890. }
  26891. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26892. get: function () {
  26893. return this._isDirty;
  26894. },
  26895. enumerable: true,
  26896. configurable: true
  26897. });
  26898. MaterialDefines.prototype.markAsProcessed = function () {
  26899. this._isDirty = false;
  26900. this._areAttributesDirty = false;
  26901. this._areTexturesDirty = false;
  26902. this._areFresnelDirty = false;
  26903. this._areLightsDirty = false;
  26904. this._areMiscDirty = false;
  26905. this._areImageProcessingDirty = false;
  26906. };
  26907. MaterialDefines.prototype.markAsUnprocessed = function () {
  26908. this._isDirty = true;
  26909. };
  26910. MaterialDefines.prototype.markAllAsDirty = function () {
  26911. this._areTexturesDirty = true;
  26912. this._areAttributesDirty = true;
  26913. this._areLightsDirty = true;
  26914. this._areFresnelDirty = true;
  26915. this._areMiscDirty = true;
  26916. this._areImageProcessingDirty = true;
  26917. this._isDirty = true;
  26918. };
  26919. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  26920. this._areImageProcessingDirty = true;
  26921. this._isDirty = true;
  26922. };
  26923. MaterialDefines.prototype.markAsLightDirty = function () {
  26924. this._areLightsDirty = true;
  26925. this._isDirty = true;
  26926. };
  26927. MaterialDefines.prototype.markAsAttributesDirty = function () {
  26928. this._areAttributesDirty = true;
  26929. this._isDirty = true;
  26930. };
  26931. MaterialDefines.prototype.markAsTexturesDirty = function () {
  26932. this._areTexturesDirty = true;
  26933. this._isDirty = true;
  26934. };
  26935. MaterialDefines.prototype.markAsFresnelDirty = function () {
  26936. this._areFresnelDirty = true;
  26937. this._isDirty = true;
  26938. };
  26939. MaterialDefines.prototype.markAsMiscDirty = function () {
  26940. this._areMiscDirty = true;
  26941. this._isDirty = true;
  26942. };
  26943. MaterialDefines.prototype.rebuild = function () {
  26944. if (this._keys) {
  26945. delete this._keys;
  26946. }
  26947. this._keys = [];
  26948. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  26949. var key = _a[_i];
  26950. if (key[0] === "_") {
  26951. continue;
  26952. }
  26953. this._keys.push(key);
  26954. }
  26955. };
  26956. MaterialDefines.prototype.isEqual = function (other) {
  26957. if (this._keys.length !== other._keys.length) {
  26958. return false;
  26959. }
  26960. for (var index = 0; index < this._keys.length; index++) {
  26961. var prop = this._keys[index];
  26962. if (this[prop] !== other[prop]) {
  26963. return false;
  26964. }
  26965. }
  26966. return true;
  26967. };
  26968. MaterialDefines.prototype.cloneTo = function (other) {
  26969. if (this._keys.length !== other._keys.length) {
  26970. other._keys = this._keys.slice(0);
  26971. }
  26972. for (var index = 0; index < this._keys.length; index++) {
  26973. var prop = this._keys[index];
  26974. other[prop] = this[prop];
  26975. }
  26976. };
  26977. MaterialDefines.prototype.reset = function () {
  26978. for (var index = 0; index < this._keys.length; index++) {
  26979. var prop = this._keys[index];
  26980. if (typeof (this[prop]) === "number") {
  26981. this[prop] = 0;
  26982. }
  26983. else {
  26984. this[prop] = false;
  26985. }
  26986. }
  26987. };
  26988. MaterialDefines.prototype.toString = function () {
  26989. var result = "";
  26990. for (var index = 0; index < this._keys.length; index++) {
  26991. var prop = this._keys[index];
  26992. var value = this[prop];
  26993. if (typeof (value) === "number") {
  26994. result += "#define " + prop + " " + this[prop] + "\n";
  26995. }
  26996. else if (value) {
  26997. result += "#define " + prop + "\n";
  26998. }
  26999. }
  27000. return result;
  27001. };
  27002. return MaterialDefines;
  27003. }());
  27004. BABYLON.MaterialDefines = MaterialDefines;
  27005. var Material = /** @class */ (function () {
  27006. function Material(name, scene, doNotAdd) {
  27007. this.checkReadyOnEveryCall = false;
  27008. this.checkReadyOnlyOnce = false;
  27009. this.state = "";
  27010. this.alpha = 1.0;
  27011. this._backFaceCulling = true;
  27012. this.doNotSerialize = false;
  27013. this.storeEffectOnSubMeshes = false;
  27014. /**
  27015. * An event triggered when the material is disposed.
  27016. * @type {BABYLON.Observable}
  27017. */
  27018. this.onDisposeObservable = new BABYLON.Observable();
  27019. /**
  27020. * An event triggered when the material is bound.
  27021. * @type {BABYLON.Observable}
  27022. */
  27023. this.onBindObservable = new BABYLON.Observable();
  27024. /**
  27025. * An event triggered when the material is unbound.
  27026. * @type {BABYLON.Observable}
  27027. */
  27028. this.onUnBindObservable = new BABYLON.Observable();
  27029. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27030. this._needDepthPrePass = false;
  27031. this.disableDepthWrite = false;
  27032. this.forceDepthWrite = false;
  27033. this.separateCullingPass = false;
  27034. this._fogEnabled = true;
  27035. this.pointSize = 1.0;
  27036. this.zOffset = 0;
  27037. this._wasPreviouslyReady = false;
  27038. this._fillMode = Material.TriangleFillMode;
  27039. this.name = name;
  27040. this.id = name || BABYLON.Tools.RandomId();
  27041. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27042. if (this._scene.useRightHandedSystem) {
  27043. this.sideOrientation = Material.ClockWiseSideOrientation;
  27044. }
  27045. else {
  27046. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27047. }
  27048. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27049. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27050. if (!doNotAdd) {
  27051. this._scene.materials.push(this);
  27052. }
  27053. }
  27054. Object.defineProperty(Material, "TriangleFillMode", {
  27055. get: function () {
  27056. return Material._TriangleFillMode;
  27057. },
  27058. enumerable: true,
  27059. configurable: true
  27060. });
  27061. Object.defineProperty(Material, "WireFrameFillMode", {
  27062. get: function () {
  27063. return Material._WireFrameFillMode;
  27064. },
  27065. enumerable: true,
  27066. configurable: true
  27067. });
  27068. Object.defineProperty(Material, "PointFillMode", {
  27069. get: function () {
  27070. return Material._PointFillMode;
  27071. },
  27072. enumerable: true,
  27073. configurable: true
  27074. });
  27075. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27076. get: function () {
  27077. return Material._ClockWiseSideOrientation;
  27078. },
  27079. enumerable: true,
  27080. configurable: true
  27081. });
  27082. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27083. get: function () {
  27084. return Material._CounterClockWiseSideOrientation;
  27085. },
  27086. enumerable: true,
  27087. configurable: true
  27088. });
  27089. Object.defineProperty(Material, "TextureDirtyFlag", {
  27090. get: function () {
  27091. return Material._TextureDirtyFlag;
  27092. },
  27093. enumerable: true,
  27094. configurable: true
  27095. });
  27096. Object.defineProperty(Material, "LightDirtyFlag", {
  27097. get: function () {
  27098. return Material._LightDirtyFlag;
  27099. },
  27100. enumerable: true,
  27101. configurable: true
  27102. });
  27103. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27104. get: function () {
  27105. return Material._FresnelDirtyFlag;
  27106. },
  27107. enumerable: true,
  27108. configurable: true
  27109. });
  27110. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27111. get: function () {
  27112. return Material._AttributesDirtyFlag;
  27113. },
  27114. enumerable: true,
  27115. configurable: true
  27116. });
  27117. Object.defineProperty(Material, "MiscDirtyFlag", {
  27118. get: function () {
  27119. return Material._MiscDirtyFlag;
  27120. },
  27121. enumerable: true,
  27122. configurable: true
  27123. });
  27124. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27125. get: function () {
  27126. return this._backFaceCulling;
  27127. },
  27128. set: function (value) {
  27129. if (this._backFaceCulling === value) {
  27130. return;
  27131. }
  27132. this._backFaceCulling = value;
  27133. this.markAsDirty(Material.TextureDirtyFlag);
  27134. },
  27135. enumerable: true,
  27136. configurable: true
  27137. });
  27138. Object.defineProperty(Material.prototype, "onDispose", {
  27139. set: function (callback) {
  27140. if (this._onDisposeObserver) {
  27141. this.onDisposeObservable.remove(this._onDisposeObserver);
  27142. }
  27143. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27144. },
  27145. enumerable: true,
  27146. configurable: true
  27147. });
  27148. Object.defineProperty(Material.prototype, "onBind", {
  27149. set: function (callback) {
  27150. if (this._onBindObserver) {
  27151. this.onBindObservable.remove(this._onBindObserver);
  27152. }
  27153. this._onBindObserver = this.onBindObservable.add(callback);
  27154. },
  27155. enumerable: true,
  27156. configurable: true
  27157. });
  27158. Object.defineProperty(Material.prototype, "alphaMode", {
  27159. get: function () {
  27160. return this._alphaMode;
  27161. },
  27162. set: function (value) {
  27163. if (this._alphaMode === value) {
  27164. return;
  27165. }
  27166. this._alphaMode = value;
  27167. this.markAsDirty(Material.TextureDirtyFlag);
  27168. },
  27169. enumerable: true,
  27170. configurable: true
  27171. });
  27172. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27173. get: function () {
  27174. return this._needDepthPrePass;
  27175. },
  27176. set: function (value) {
  27177. if (this._needDepthPrePass === value) {
  27178. return;
  27179. }
  27180. this._needDepthPrePass = value;
  27181. if (this._needDepthPrePass) {
  27182. this.checkReadyOnEveryCall = true;
  27183. }
  27184. },
  27185. enumerable: true,
  27186. configurable: true
  27187. });
  27188. Object.defineProperty(Material.prototype, "fogEnabled", {
  27189. get: function () {
  27190. return this._fogEnabled;
  27191. },
  27192. set: function (value) {
  27193. if (this._fogEnabled === value) {
  27194. return;
  27195. }
  27196. this._fogEnabled = value;
  27197. this.markAsDirty(Material.MiscDirtyFlag);
  27198. },
  27199. enumerable: true,
  27200. configurable: true
  27201. });
  27202. Object.defineProperty(Material.prototype, "wireframe", {
  27203. get: function () {
  27204. return this._fillMode === Material.WireFrameFillMode;
  27205. },
  27206. set: function (value) {
  27207. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27208. },
  27209. enumerable: true,
  27210. configurable: true
  27211. });
  27212. Object.defineProperty(Material.prototype, "pointsCloud", {
  27213. get: function () {
  27214. return this._fillMode === Material.PointFillMode;
  27215. },
  27216. set: function (value) {
  27217. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27218. },
  27219. enumerable: true,
  27220. configurable: true
  27221. });
  27222. Object.defineProperty(Material.prototype, "fillMode", {
  27223. get: function () {
  27224. return this._fillMode;
  27225. },
  27226. set: function (value) {
  27227. if (this._fillMode === value) {
  27228. return;
  27229. }
  27230. this._fillMode = value;
  27231. this.markAsDirty(Material.MiscDirtyFlag);
  27232. },
  27233. enumerable: true,
  27234. configurable: true
  27235. });
  27236. /**
  27237. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27238. * subclasses should override adding information pertainent to themselves
  27239. */
  27240. Material.prototype.toString = function (fullDetails) {
  27241. var ret = "Name: " + this.name;
  27242. if (fullDetails) {
  27243. }
  27244. return ret;
  27245. };
  27246. /**
  27247. * Child classes can use it to update shaders
  27248. */
  27249. Material.prototype.getClassName = function () {
  27250. return "Material";
  27251. };
  27252. Object.defineProperty(Material.prototype, "isFrozen", {
  27253. get: function () {
  27254. return this.checkReadyOnlyOnce;
  27255. },
  27256. enumerable: true,
  27257. configurable: true
  27258. });
  27259. Material.prototype.freeze = function () {
  27260. this.checkReadyOnlyOnce = true;
  27261. };
  27262. Material.prototype.unfreeze = function () {
  27263. this.checkReadyOnlyOnce = false;
  27264. };
  27265. Material.prototype.isReady = function (mesh, useInstances) {
  27266. return true;
  27267. };
  27268. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27269. return false;
  27270. };
  27271. Material.prototype.getEffect = function () {
  27272. return this._effect;
  27273. };
  27274. Material.prototype.getScene = function () {
  27275. return this._scene;
  27276. };
  27277. Material.prototype.needAlphaBlending = function () {
  27278. return (this.alpha < 1.0);
  27279. };
  27280. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27281. return (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27282. };
  27283. Material.prototype.needAlphaTesting = function () {
  27284. return false;
  27285. };
  27286. Material.prototype.getAlphaTestTexture = function () {
  27287. return null;
  27288. };
  27289. Material.prototype.markDirty = function () {
  27290. this._wasPreviouslyReady = false;
  27291. };
  27292. Material.prototype._preBind = function (effect, overrideOrientation) {
  27293. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27294. var engine = this._scene.getEngine();
  27295. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27296. var reverse = orientation === Material.ClockWiseSideOrientation;
  27297. engine.enableEffect(effect ? effect : this._effect);
  27298. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27299. return reverse;
  27300. };
  27301. Material.prototype.bind = function (world, mesh) {
  27302. };
  27303. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27304. };
  27305. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27306. };
  27307. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27308. sceneUbo.bindToEffect(effect, "Scene");
  27309. };
  27310. Material.prototype.bindView = function (effect) {
  27311. if (!this._useUBO) {
  27312. effect.setMatrix("view", this.getScene().getViewMatrix());
  27313. }
  27314. else {
  27315. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27316. }
  27317. };
  27318. Material.prototype.bindViewProjection = function (effect) {
  27319. if (!this._useUBO) {
  27320. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27321. }
  27322. else {
  27323. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27324. }
  27325. };
  27326. Material.prototype._afterBind = function (mesh) {
  27327. this._scene._cachedMaterial = this;
  27328. if (mesh) {
  27329. this._scene._cachedVisibility = mesh.visibility;
  27330. }
  27331. else {
  27332. this._scene._cachedVisibility = 1;
  27333. }
  27334. if (mesh) {
  27335. this.onBindObservable.notifyObservers(mesh);
  27336. }
  27337. if (this.disableDepthWrite) {
  27338. var engine = this._scene.getEngine();
  27339. this._cachedDepthWriteState = engine.getDepthWrite();
  27340. engine.setDepthWrite(false);
  27341. }
  27342. };
  27343. Material.prototype.unbind = function () {
  27344. this.onUnBindObservable.notifyObservers(this);
  27345. if (this.disableDepthWrite) {
  27346. var engine = this._scene.getEngine();
  27347. engine.setDepthWrite(this._cachedDepthWriteState);
  27348. }
  27349. };
  27350. Material.prototype.getActiveTextures = function () {
  27351. return [];
  27352. };
  27353. Material.prototype.hasTexture = function (texture) {
  27354. return false;
  27355. };
  27356. Material.prototype.clone = function (name) {
  27357. return null;
  27358. };
  27359. Material.prototype.getBindedMeshes = function () {
  27360. var result = new Array();
  27361. for (var index = 0; index < this._scene.meshes.length; index++) {
  27362. var mesh = this._scene.meshes[index];
  27363. if (mesh.material === this) {
  27364. result.push(mesh);
  27365. }
  27366. }
  27367. return result;
  27368. };
  27369. /**
  27370. * Force shader compilation including textures ready check
  27371. */
  27372. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27373. var _this = this;
  27374. var subMesh = new BABYLON.BaseSubMesh();
  27375. var scene = this.getScene();
  27376. var engine = scene.getEngine();
  27377. var checkReady = function () {
  27378. if (!_this._scene || !_this._scene.getEngine()) {
  27379. return;
  27380. }
  27381. if (subMesh._materialDefines) {
  27382. subMesh._materialDefines._renderId = -1;
  27383. }
  27384. var alphaTestState = engine.getAlphaTesting();
  27385. var clipPlaneState = scene.clipPlane;
  27386. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  27387. if (options && options.clipPlane) {
  27388. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27389. }
  27390. if (_this.storeEffectOnSubMeshes) {
  27391. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27392. if (onCompiled) {
  27393. onCompiled(_this);
  27394. }
  27395. }
  27396. else {
  27397. setTimeout(checkReady, 16);
  27398. }
  27399. }
  27400. else {
  27401. if (_this.isReady(mesh)) {
  27402. if (onCompiled) {
  27403. onCompiled(_this);
  27404. }
  27405. }
  27406. else {
  27407. setTimeout(checkReady, 16);
  27408. }
  27409. }
  27410. engine.setAlphaTesting(alphaTestState);
  27411. if (options && options.clipPlane) {
  27412. scene.clipPlane = clipPlaneState;
  27413. }
  27414. };
  27415. checkReady();
  27416. };
  27417. Material.prototype.markAsDirty = function (flag) {
  27418. if (flag & Material.TextureDirtyFlag) {
  27419. this._markAllSubMeshesAsTexturesDirty();
  27420. }
  27421. if (flag & Material.LightDirtyFlag) {
  27422. this._markAllSubMeshesAsLightsDirty();
  27423. }
  27424. if (flag & Material.FresnelDirtyFlag) {
  27425. this._markAllSubMeshesAsFresnelDirty();
  27426. }
  27427. if (flag & Material.AttributesDirtyFlag) {
  27428. this._markAllSubMeshesAsAttributesDirty();
  27429. }
  27430. if (flag & Material.MiscDirtyFlag) {
  27431. this._markAllSubMeshesAsMiscDirty();
  27432. }
  27433. this.getScene().resetCachedMaterial();
  27434. };
  27435. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27436. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27437. var mesh = _a[_i];
  27438. if (!mesh.subMeshes) {
  27439. continue;
  27440. }
  27441. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27442. var subMesh = _c[_b];
  27443. if (subMesh.getMaterial() !== this) {
  27444. continue;
  27445. }
  27446. if (!subMesh._materialDefines) {
  27447. continue;
  27448. }
  27449. func(subMesh._materialDefines);
  27450. }
  27451. }
  27452. };
  27453. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27454. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27455. };
  27456. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27457. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27458. };
  27459. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27460. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27461. };
  27462. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27463. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27464. };
  27465. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27466. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27467. };
  27468. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27469. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27470. };
  27471. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27472. // Animations
  27473. this.getScene().stopAnimation(this);
  27474. // Remove from scene
  27475. var index = this._scene.materials.indexOf(this);
  27476. if (index >= 0) {
  27477. this._scene.materials.splice(index, 1);
  27478. }
  27479. // Remove from meshes
  27480. for (index = 0; index < this._scene.meshes.length; index++) {
  27481. var mesh = this._scene.meshes[index];
  27482. if (mesh.material === this) {
  27483. mesh.material = null;
  27484. if (mesh.geometry) {
  27485. var geometry = (mesh.geometry);
  27486. if (this.storeEffectOnSubMeshes) {
  27487. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27488. var subMesh = _a[_i];
  27489. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27490. if (forceDisposeEffect && subMesh._materialEffect) {
  27491. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27492. }
  27493. }
  27494. }
  27495. else {
  27496. geometry._releaseVertexArrayObject(this._effect);
  27497. }
  27498. }
  27499. }
  27500. }
  27501. this._uniformBuffer.dispose();
  27502. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27503. if (forceDisposeEffect && this._effect) {
  27504. if (!this.storeEffectOnSubMeshes) {
  27505. this._scene.getEngine()._releaseEffect(this._effect);
  27506. }
  27507. this._effect = null;
  27508. }
  27509. // Callback
  27510. this.onDisposeObservable.notifyObservers(this);
  27511. this.onDisposeObservable.clear();
  27512. this.onBindObservable.clear();
  27513. this.onUnBindObservable.clear();
  27514. };
  27515. Material.prototype.serialize = function () {
  27516. return BABYLON.SerializationHelper.Serialize(this);
  27517. };
  27518. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27519. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27520. multiMaterial.id = parsedMultiMaterial.id;
  27521. if (BABYLON.Tags) {
  27522. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27523. }
  27524. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27525. var subMatId = parsedMultiMaterial.materials[matIndex];
  27526. if (subMatId) {
  27527. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27528. }
  27529. else {
  27530. multiMaterial.subMaterials.push(null);
  27531. }
  27532. }
  27533. return multiMaterial;
  27534. };
  27535. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27536. if (!parsedMaterial.customType) {
  27537. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27538. }
  27539. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27540. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27541. if (!BABYLON.LegacyPBRMaterial) {
  27542. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27543. return;
  27544. }
  27545. }
  27546. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27547. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27548. ;
  27549. };
  27550. Material._TriangleFillMode = 0;
  27551. Material._WireFrameFillMode = 1;
  27552. Material._PointFillMode = 2;
  27553. Material._ClockWiseSideOrientation = 0;
  27554. Material._CounterClockWiseSideOrientation = 1;
  27555. Material._TextureDirtyFlag = 1;
  27556. Material._LightDirtyFlag = 2;
  27557. Material._FresnelDirtyFlag = 4;
  27558. Material._AttributesDirtyFlag = 8;
  27559. Material._MiscDirtyFlag = 16;
  27560. __decorate([
  27561. BABYLON.serialize()
  27562. ], Material.prototype, "id", void 0);
  27563. __decorate([
  27564. BABYLON.serialize()
  27565. ], Material.prototype, "name", void 0);
  27566. __decorate([
  27567. BABYLON.serialize()
  27568. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27569. __decorate([
  27570. BABYLON.serialize()
  27571. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27572. __decorate([
  27573. BABYLON.serialize()
  27574. ], Material.prototype, "state", void 0);
  27575. __decorate([
  27576. BABYLON.serialize()
  27577. ], Material.prototype, "alpha", void 0);
  27578. __decorate([
  27579. BABYLON.serialize("backFaceCulling")
  27580. ], Material.prototype, "_backFaceCulling", void 0);
  27581. __decorate([
  27582. BABYLON.serialize()
  27583. ], Material.prototype, "sideOrientation", void 0);
  27584. __decorate([
  27585. BABYLON.serialize("alphaMode")
  27586. ], Material.prototype, "_alphaMode", void 0);
  27587. __decorate([
  27588. BABYLON.serialize()
  27589. ], Material.prototype, "_needDepthPrePass", void 0);
  27590. __decorate([
  27591. BABYLON.serialize()
  27592. ], Material.prototype, "disableDepthWrite", void 0);
  27593. __decorate([
  27594. BABYLON.serialize()
  27595. ], Material.prototype, "forceDepthWrite", void 0);
  27596. __decorate([
  27597. BABYLON.serialize()
  27598. ], Material.prototype, "separateCullingPass", void 0);
  27599. __decorate([
  27600. BABYLON.serialize("fogEnabled")
  27601. ], Material.prototype, "_fogEnabled", void 0);
  27602. __decorate([
  27603. BABYLON.serialize()
  27604. ], Material.prototype, "pointSize", void 0);
  27605. __decorate([
  27606. BABYLON.serialize()
  27607. ], Material.prototype, "zOffset", void 0);
  27608. __decorate([
  27609. BABYLON.serialize()
  27610. ], Material.prototype, "wireframe", null);
  27611. __decorate([
  27612. BABYLON.serialize()
  27613. ], Material.prototype, "pointsCloud", null);
  27614. __decorate([
  27615. BABYLON.serialize()
  27616. ], Material.prototype, "fillMode", null);
  27617. return Material;
  27618. }());
  27619. BABYLON.Material = Material;
  27620. })(BABYLON || (BABYLON = {}));
  27621. //# sourceMappingURL=babylon.material.js.map
  27622. var BABYLON;
  27623. (function (BABYLON) {
  27624. var UniformBuffer = /** @class */ (function () {
  27625. /**
  27626. * Uniform buffer objects.
  27627. *
  27628. * Handles blocks of uniform on the GPU.
  27629. *
  27630. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  27631. *
  27632. * For more information, please refer to :
  27633. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  27634. */
  27635. function UniformBuffer(engine, data, dynamic) {
  27636. this._engine = engine;
  27637. this._noUBO = !engine.supportsUniformBuffers;
  27638. this._dynamic = dynamic;
  27639. this._data = data || [];
  27640. this._uniformLocations = {};
  27641. this._uniformSizes = {};
  27642. this._uniformLocationPointer = 0;
  27643. this._needSync = false;
  27644. if (this._noUBO) {
  27645. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  27646. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  27647. this.updateFloat = this._updateFloatForEffect;
  27648. this.updateFloat2 = this._updateFloat2ForEffect;
  27649. this.updateFloat3 = this._updateFloat3ForEffect;
  27650. this.updateFloat4 = this._updateFloat4ForEffect;
  27651. this.updateMatrix = this._updateMatrixForEffect;
  27652. this.updateVector3 = this._updateVector3ForEffect;
  27653. this.updateVector4 = this._updateVector4ForEffect;
  27654. this.updateColor3 = this._updateColor3ForEffect;
  27655. this.updateColor4 = this._updateColor4ForEffect;
  27656. }
  27657. else {
  27658. this._engine._uniformBuffers.push(this);
  27659. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  27660. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  27661. this.updateFloat = this._updateFloatForUniform;
  27662. this.updateFloat2 = this._updateFloat2ForUniform;
  27663. this.updateFloat3 = this._updateFloat3ForUniform;
  27664. this.updateFloat4 = this._updateFloat4ForUniform;
  27665. this.updateMatrix = this._updateMatrixForUniform;
  27666. this.updateVector3 = this._updateVector3ForUniform;
  27667. this.updateVector4 = this._updateVector4ForUniform;
  27668. this.updateColor3 = this._updateColor3ForUniform;
  27669. this.updateColor4 = this._updateColor4ForUniform;
  27670. }
  27671. }
  27672. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  27673. // Properties
  27674. /**
  27675. * Indicates if the buffer is using the WebGL2 UBO implementation,
  27676. * or just falling back on setUniformXXX calls.
  27677. */
  27678. get: function () {
  27679. return !this._noUBO;
  27680. },
  27681. enumerable: true,
  27682. configurable: true
  27683. });
  27684. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  27685. /**
  27686. * Indicates if the WebGL underlying uniform buffer is in sync
  27687. * with the javascript cache data.
  27688. */
  27689. get: function () {
  27690. return !this._needSync;
  27691. },
  27692. enumerable: true,
  27693. configurable: true
  27694. });
  27695. /**
  27696. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27697. * Also, a dynamic UniformBuffer will disable cache verification and always
  27698. * update the underlying WebGL uniform buffer to the GPU.
  27699. */
  27700. UniformBuffer.prototype.isDynamic = function () {
  27701. return this._dynamic !== undefined;
  27702. };
  27703. /**
  27704. * The data cache on JS side.
  27705. */
  27706. UniformBuffer.prototype.getData = function () {
  27707. return this._bufferData;
  27708. };
  27709. /**
  27710. * The underlying WebGL Uniform buffer.
  27711. */
  27712. UniformBuffer.prototype.getBuffer = function () {
  27713. return this._buffer;
  27714. };
  27715. /**
  27716. * std140 layout specifies how to align data within an UBO structure.
  27717. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27718. * for specs.
  27719. */
  27720. UniformBuffer.prototype._fillAlignment = function (size) {
  27721. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27722. // and 4x4 matrices
  27723. // TODO : change if other types are used
  27724. var alignment;
  27725. if (size <= 2) {
  27726. alignment = size;
  27727. }
  27728. else {
  27729. alignment = 4;
  27730. }
  27731. if ((this._uniformLocationPointer % alignment) !== 0) {
  27732. var oldPointer = this._uniformLocationPointer;
  27733. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27734. var diff = this._uniformLocationPointer - oldPointer;
  27735. for (var i = 0; i < diff; i++) {
  27736. this._data.push(0);
  27737. }
  27738. }
  27739. };
  27740. /**
  27741. * Adds an uniform in the buffer.
  27742. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27743. * for the layout to be correct !
  27744. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27745. * @param {number|number[]} size Data size, or data directly.
  27746. */
  27747. UniformBuffer.prototype.addUniform = function (name, size) {
  27748. if (this._noUBO) {
  27749. return;
  27750. }
  27751. if (this._uniformLocations[name] !== undefined) {
  27752. // Already existing uniform
  27753. return;
  27754. }
  27755. // This function must be called in the order of the shader layout !
  27756. // size can be the size of the uniform, or data directly
  27757. var data;
  27758. if (size instanceof Array) {
  27759. data = size;
  27760. size = data.length;
  27761. }
  27762. else {
  27763. size = size;
  27764. data = [];
  27765. // Fill with zeros
  27766. for (var i = 0; i < size; i++) {
  27767. data.push(0);
  27768. }
  27769. }
  27770. this._fillAlignment(size);
  27771. this._uniformSizes[name] = size;
  27772. this._uniformLocations[name] = this._uniformLocationPointer;
  27773. this._uniformLocationPointer += size;
  27774. for (var i = 0; i < size; i++) {
  27775. this._data.push(data[i]);
  27776. }
  27777. this._needSync = true;
  27778. };
  27779. /**
  27780. * Wrapper for addUniform.
  27781. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27782. * @param {Matrix} mat A 4x4 matrix.
  27783. */
  27784. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27785. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27786. };
  27787. /**
  27788. * Wrapper for addUniform.
  27789. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27790. * @param {number} x
  27791. * @param {number} y
  27792. */
  27793. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27794. var temp = [x, y];
  27795. this.addUniform(name, temp);
  27796. };
  27797. /**
  27798. * Wrapper for addUniform.
  27799. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27800. * @param {number} x
  27801. * @param {number} y
  27802. * @param {number} z
  27803. */
  27804. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27805. var temp = [x, y, z];
  27806. this.addUniform(name, temp);
  27807. };
  27808. /**
  27809. * Wrapper for addUniform.
  27810. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27811. * @param {Color3} color
  27812. */
  27813. UniformBuffer.prototype.addColor3 = function (name, color) {
  27814. var temp = new Array();
  27815. color.toArray(temp);
  27816. this.addUniform(name, temp);
  27817. };
  27818. /**
  27819. * Wrapper for addUniform.
  27820. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27821. * @param {Color3} color
  27822. * @param {number} alpha
  27823. */
  27824. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27825. var temp = new Array();
  27826. color.toArray(temp);
  27827. temp.push(alpha);
  27828. this.addUniform(name, temp);
  27829. };
  27830. /**
  27831. * Wrapper for addUniform.
  27832. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27833. * @param {Vector3} vector
  27834. */
  27835. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27836. var temp = new Array();
  27837. vector.toArray(temp);
  27838. this.addUniform(name, temp);
  27839. };
  27840. /**
  27841. * Wrapper for addUniform.
  27842. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27843. */
  27844. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27845. this.addUniform(name, 12);
  27846. };
  27847. /**
  27848. * Wrapper for addUniform.
  27849. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27850. */
  27851. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27852. this.addUniform(name, 8);
  27853. };
  27854. /**
  27855. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27856. */
  27857. UniformBuffer.prototype.create = function () {
  27858. if (this._noUBO) {
  27859. return;
  27860. }
  27861. if (this._buffer) {
  27862. return; // nothing to do
  27863. }
  27864. // See spec, alignment must be filled as a vec4
  27865. this._fillAlignment(4);
  27866. this._bufferData = new Float32Array(this._data);
  27867. this._rebuild();
  27868. this._needSync = true;
  27869. };
  27870. UniformBuffer.prototype._rebuild = function () {
  27871. if (this._noUBO) {
  27872. return;
  27873. }
  27874. if (this._dynamic) {
  27875. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27876. }
  27877. else {
  27878. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27879. }
  27880. };
  27881. /**
  27882. * Updates the WebGL Uniform Buffer on the GPU.
  27883. * If the `dynamic` flag is set to true, no cache comparison is done.
  27884. * Otherwise, the buffer will be updated only if the cache differs.
  27885. */
  27886. UniformBuffer.prototype.update = function () {
  27887. if (!this._buffer) {
  27888. this.create();
  27889. return;
  27890. }
  27891. if (!this._dynamic && !this._needSync) {
  27892. return;
  27893. }
  27894. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27895. this._needSync = false;
  27896. };
  27897. /**
  27898. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  27899. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27900. * @param {number[]|Float32Array} data Flattened data
  27901. * @param {number} size Size of the data.
  27902. */
  27903. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  27904. var location = this._uniformLocations[uniformName];
  27905. if (location === undefined) {
  27906. if (this._buffer) {
  27907. // Cannot add an uniform if the buffer is already created
  27908. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  27909. return;
  27910. }
  27911. this.addUniform(uniformName, size);
  27912. location = this._uniformLocations[uniformName];
  27913. }
  27914. if (!this._buffer) {
  27915. this.create();
  27916. }
  27917. if (!this._dynamic) {
  27918. // Cache for static uniform buffers
  27919. var changed = false;
  27920. for (var i = 0; i < size; i++) {
  27921. if (this._bufferData[location + i] !== data[i]) {
  27922. changed = true;
  27923. this._bufferData[location + i] = data[i];
  27924. }
  27925. }
  27926. this._needSync = this._needSync || changed;
  27927. }
  27928. else {
  27929. // No cache for dynamic
  27930. for (var i = 0; i < size; i++) {
  27931. this._bufferData[location + i] = data[i];
  27932. }
  27933. }
  27934. };
  27935. // Update methods
  27936. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  27937. // To match std140, matrix must be realigned
  27938. for (var i = 0; i < 3; i++) {
  27939. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  27940. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  27941. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  27942. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27943. }
  27944. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  27945. };
  27946. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  27947. this._currentEffect.setMatrix3x3(name, matrix);
  27948. };
  27949. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  27950. this._currentEffect.setMatrix2x2(name, matrix);
  27951. };
  27952. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  27953. // To match std140, matrix must be realigned
  27954. for (var i = 0; i < 2; i++) {
  27955. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  27956. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  27957. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  27958. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27959. }
  27960. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  27961. };
  27962. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  27963. this._currentEffect.setFloat(name, x);
  27964. };
  27965. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  27966. UniformBuffer._tempBuffer[0] = x;
  27967. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  27968. };
  27969. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  27970. if (suffix === void 0) { suffix = ""; }
  27971. this._currentEffect.setFloat2(name + suffix, x, y);
  27972. };
  27973. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  27974. if (suffix === void 0) { suffix = ""; }
  27975. UniformBuffer._tempBuffer[0] = x;
  27976. UniformBuffer._tempBuffer[1] = y;
  27977. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  27978. };
  27979. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  27980. if (suffix === void 0) { suffix = ""; }
  27981. this._currentEffect.setFloat3(name + suffix, x, y, z);
  27982. };
  27983. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  27984. if (suffix === void 0) { suffix = ""; }
  27985. UniformBuffer._tempBuffer[0] = x;
  27986. UniformBuffer._tempBuffer[1] = y;
  27987. UniformBuffer._tempBuffer[2] = z;
  27988. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27989. };
  27990. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  27991. if (suffix === void 0) { suffix = ""; }
  27992. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  27993. };
  27994. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  27995. if (suffix === void 0) { suffix = ""; }
  27996. UniformBuffer._tempBuffer[0] = x;
  27997. UniformBuffer._tempBuffer[1] = y;
  27998. UniformBuffer._tempBuffer[2] = z;
  27999. UniformBuffer._tempBuffer[3] = w;
  28000. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28001. };
  28002. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28003. this._currentEffect.setMatrix(name, mat);
  28004. };
  28005. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28006. this.updateUniform(name, mat.toArray(), 16);
  28007. };
  28008. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28009. this._currentEffect.setVector3(name, vector);
  28010. };
  28011. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28012. vector.toArray(UniformBuffer._tempBuffer);
  28013. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28014. };
  28015. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28016. this._currentEffect.setVector4(name, vector);
  28017. };
  28018. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28019. vector.toArray(UniformBuffer._tempBuffer);
  28020. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28021. };
  28022. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28023. if (suffix === void 0) { suffix = ""; }
  28024. this._currentEffect.setColor3(name + suffix, color);
  28025. };
  28026. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28027. if (suffix === void 0) { suffix = ""; }
  28028. color.toArray(UniformBuffer._tempBuffer);
  28029. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28030. };
  28031. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28032. if (suffix === void 0) { suffix = ""; }
  28033. this._currentEffect.setColor4(name + suffix, color, alpha);
  28034. };
  28035. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28036. if (suffix === void 0) { suffix = ""; }
  28037. color.toArray(UniformBuffer._tempBuffer);
  28038. UniformBuffer._tempBuffer[3] = alpha;
  28039. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28040. };
  28041. /**
  28042. * Sets a sampler uniform on the effect.
  28043. * @param {string} name Name of the sampler.
  28044. * @param {Texture} texture
  28045. */
  28046. UniformBuffer.prototype.setTexture = function (name, texture) {
  28047. this._currentEffect.setTexture(name, texture);
  28048. };
  28049. /**
  28050. * Directly updates the value of the uniform in the cache AND on the GPU.
  28051. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28052. * @param {number[]|Float32Array} data Flattened data
  28053. */
  28054. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28055. this.updateUniform(uniformName, data, data.length);
  28056. this.update();
  28057. };
  28058. /**
  28059. * Binds this uniform buffer to an effect.
  28060. * @param {Effect} effect
  28061. * @param {string} name Name of the uniform block in the shader.
  28062. */
  28063. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28064. this._currentEffect = effect;
  28065. if (this._noUBO || !this._buffer) {
  28066. return;
  28067. }
  28068. effect.bindUniformBuffer(this._buffer, name);
  28069. };
  28070. /**
  28071. * Disposes the uniform buffer.
  28072. */
  28073. UniformBuffer.prototype.dispose = function () {
  28074. if (this._noUBO) {
  28075. return;
  28076. }
  28077. var index = this._engine._uniformBuffers.indexOf(this);
  28078. if (index !== -1) {
  28079. this._engine._uniformBuffers.splice(index, 1);
  28080. }
  28081. if (!this._buffer) {
  28082. return;
  28083. }
  28084. if (this._engine._releaseBuffer(this._buffer)) {
  28085. this._buffer = null;
  28086. }
  28087. };
  28088. // Pool for avoiding memory leaks
  28089. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28090. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28091. return UniformBuffer;
  28092. }());
  28093. BABYLON.UniformBuffer = UniformBuffer;
  28094. })(BABYLON || (BABYLON = {}));
  28095. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28096. var BABYLON;
  28097. (function (BABYLON) {
  28098. var PushMaterial = /** @class */ (function (_super) {
  28099. __extends(PushMaterial, _super);
  28100. function PushMaterial(name, scene) {
  28101. var _this = _super.call(this, name, scene) || this;
  28102. _this.storeEffectOnSubMeshes = true;
  28103. return _this;
  28104. }
  28105. PushMaterial.prototype.getEffect = function () {
  28106. return this._activeEffect;
  28107. };
  28108. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28109. if (!mesh) {
  28110. return false;
  28111. }
  28112. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28113. return true;
  28114. }
  28115. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28116. };
  28117. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28118. this._activeEffect.setMatrix("world", world);
  28119. };
  28120. PushMaterial.prototype.bind = function (world, mesh) {
  28121. if (!mesh) {
  28122. return;
  28123. }
  28124. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28125. };
  28126. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28127. if (effect === void 0) { effect = null; }
  28128. _super.prototype._afterBind.call(this, mesh);
  28129. this.getScene()._cachedEffect = effect;
  28130. };
  28131. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28132. if (visibility === void 0) { visibility = 1; }
  28133. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28134. };
  28135. return PushMaterial;
  28136. }(BABYLON.Material));
  28137. BABYLON.PushMaterial = PushMaterial;
  28138. })(BABYLON || (BABYLON = {}));
  28139. //# sourceMappingURL=babylon.pushMaterial.js.map
  28140. var BABYLON;
  28141. (function (BABYLON) {
  28142. var VertexData = /** @class */ (function () {
  28143. function VertexData() {
  28144. }
  28145. VertexData.prototype.set = function (data, kind) {
  28146. switch (kind) {
  28147. case BABYLON.VertexBuffer.PositionKind:
  28148. this.positions = data;
  28149. break;
  28150. case BABYLON.VertexBuffer.NormalKind:
  28151. this.normals = data;
  28152. break;
  28153. case BABYLON.VertexBuffer.TangentKind:
  28154. this.tangents = data;
  28155. break;
  28156. case BABYLON.VertexBuffer.UVKind:
  28157. this.uvs = data;
  28158. break;
  28159. case BABYLON.VertexBuffer.UV2Kind:
  28160. this.uvs2 = data;
  28161. break;
  28162. case BABYLON.VertexBuffer.UV3Kind:
  28163. this.uvs3 = data;
  28164. break;
  28165. case BABYLON.VertexBuffer.UV4Kind:
  28166. this.uvs4 = data;
  28167. break;
  28168. case BABYLON.VertexBuffer.UV5Kind:
  28169. this.uvs5 = data;
  28170. break;
  28171. case BABYLON.VertexBuffer.UV6Kind:
  28172. this.uvs6 = data;
  28173. break;
  28174. case BABYLON.VertexBuffer.ColorKind:
  28175. this.colors = data;
  28176. break;
  28177. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28178. this.matricesIndices = data;
  28179. break;
  28180. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28181. this.matricesWeights = data;
  28182. break;
  28183. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28184. this.matricesIndicesExtra = data;
  28185. break;
  28186. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28187. this.matricesWeightsExtra = data;
  28188. break;
  28189. }
  28190. };
  28191. /**
  28192. * Associates the vertexData to the passed Mesh.
  28193. * Sets it as updatable or not (default `false`).
  28194. * Returns the VertexData.
  28195. */
  28196. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28197. this._applyTo(mesh, updatable);
  28198. return this;
  28199. };
  28200. /**
  28201. * Associates the vertexData to the passed Geometry.
  28202. * Sets it as updatable or not (default `false`).
  28203. * Returns the VertexData.
  28204. */
  28205. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28206. this._applyTo(geometry, updatable);
  28207. return this;
  28208. };
  28209. /**
  28210. * Updates the associated mesh.
  28211. * Returns the VertexData.
  28212. */
  28213. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28214. this._update(mesh);
  28215. return this;
  28216. };
  28217. /**
  28218. * Updates the associated geometry.
  28219. * Returns the VertexData.
  28220. */
  28221. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28222. this._update(geometry);
  28223. return this;
  28224. };
  28225. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28226. if (updatable === void 0) { updatable = false; }
  28227. if (this.positions) {
  28228. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28229. }
  28230. if (this.normals) {
  28231. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28232. }
  28233. if (this.tangents) {
  28234. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28235. }
  28236. if (this.uvs) {
  28237. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28238. }
  28239. if (this.uvs2) {
  28240. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28241. }
  28242. if (this.uvs3) {
  28243. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28244. }
  28245. if (this.uvs4) {
  28246. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28247. }
  28248. if (this.uvs5) {
  28249. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28250. }
  28251. if (this.uvs6) {
  28252. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28253. }
  28254. if (this.colors) {
  28255. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28256. }
  28257. if (this.matricesIndices) {
  28258. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28259. }
  28260. if (this.matricesWeights) {
  28261. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28262. }
  28263. if (this.matricesIndicesExtra) {
  28264. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28265. }
  28266. if (this.matricesWeightsExtra) {
  28267. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28268. }
  28269. if (this.indices) {
  28270. meshOrGeometry.setIndices(this.indices, null, updatable);
  28271. }
  28272. return this;
  28273. };
  28274. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28275. if (this.positions) {
  28276. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28277. }
  28278. if (this.normals) {
  28279. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28280. }
  28281. if (this.tangents) {
  28282. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28283. }
  28284. if (this.uvs) {
  28285. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28286. }
  28287. if (this.uvs2) {
  28288. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28289. }
  28290. if (this.uvs3) {
  28291. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28292. }
  28293. if (this.uvs4) {
  28294. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28295. }
  28296. if (this.uvs5) {
  28297. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28298. }
  28299. if (this.uvs6) {
  28300. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28301. }
  28302. if (this.colors) {
  28303. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28304. }
  28305. if (this.matricesIndices) {
  28306. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28307. }
  28308. if (this.matricesWeights) {
  28309. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28310. }
  28311. if (this.matricesIndicesExtra) {
  28312. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28313. }
  28314. if (this.matricesWeightsExtra) {
  28315. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28316. }
  28317. if (this.indices) {
  28318. meshOrGeometry.setIndices(this.indices, null);
  28319. }
  28320. return this;
  28321. };
  28322. /**
  28323. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28324. * Returns the VertexData.
  28325. */
  28326. VertexData.prototype.transform = function (matrix) {
  28327. var transformed = BABYLON.Vector3.Zero();
  28328. var index;
  28329. if (this.positions) {
  28330. var position = BABYLON.Vector3.Zero();
  28331. for (index = 0; index < this.positions.length; index += 3) {
  28332. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28333. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28334. this.positions[index] = transformed.x;
  28335. this.positions[index + 1] = transformed.y;
  28336. this.positions[index + 2] = transformed.z;
  28337. }
  28338. }
  28339. if (this.normals) {
  28340. var normal = BABYLON.Vector3.Zero();
  28341. for (index = 0; index < this.normals.length; index += 3) {
  28342. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28343. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28344. this.normals[index] = transformed.x;
  28345. this.normals[index + 1] = transformed.y;
  28346. this.normals[index + 2] = transformed.z;
  28347. }
  28348. }
  28349. if (this.tangents) {
  28350. var tangent = BABYLON.Vector4.Zero();
  28351. var tangentTransformed = BABYLON.Vector4.Zero();
  28352. for (index = 0; index < this.tangents.length; index += 4) {
  28353. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28354. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28355. this.tangents[index] = tangentTransformed.x;
  28356. this.tangents[index + 1] = tangentTransformed.y;
  28357. this.tangents[index + 2] = tangentTransformed.z;
  28358. this.tangents[index + 3] = tangentTransformed.w;
  28359. }
  28360. }
  28361. return this;
  28362. };
  28363. /**
  28364. * Merges the passed VertexData into the current one.
  28365. * Returns the modified VertexData.
  28366. */
  28367. VertexData.prototype.merge = function (other, options) {
  28368. options = options || {};
  28369. if (other.indices) {
  28370. if (!this.indices) {
  28371. this.indices = [];
  28372. }
  28373. var offset = this.positions ? this.positions.length / 3 : 0;
  28374. for (var index = 0; index < other.indices.length; index++) {
  28375. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28376. this.indices.push(other.indices[index] + offset);
  28377. }
  28378. }
  28379. this.positions = this._mergeElement(this.positions, other.positions);
  28380. if (!this.positions) {
  28381. return this;
  28382. }
  28383. var count = this.positions.length / 3;
  28384. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28385. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28386. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28387. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28388. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28389. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28390. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28391. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28392. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28393. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28394. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28395. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28396. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28397. return this;
  28398. };
  28399. VertexData.prototype._mergeElement = function (source, other, length) {
  28400. if (length === void 0) { length = 0; }
  28401. if (!other && !source) {
  28402. return null;
  28403. }
  28404. if (!other) {
  28405. return this._mergeElement(source, new Float32Array(source.length), length);
  28406. }
  28407. if (!source) {
  28408. if (length === 0 || length === other.length) {
  28409. return other;
  28410. }
  28411. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28412. }
  28413. var len = other.length + source.length;
  28414. var isSrcTypedArray = source instanceof Float32Array;
  28415. var isOthTypedArray = other instanceof Float32Array;
  28416. // use non-loop method when the source is Float32Array
  28417. if (isSrcTypedArray) {
  28418. var ret32 = new Float32Array(len);
  28419. ret32.set(source);
  28420. ret32.set(other, source.length);
  28421. return ret32;
  28422. // source is number[], when other is also use concat
  28423. }
  28424. else if (!isOthTypedArray) {
  28425. return source.concat(other);
  28426. // source is a number[], but other is a Float32Array, loop required
  28427. }
  28428. else {
  28429. var ret = source.slice(0); // copy source to a separate array
  28430. for (var i = 0, len = other.length; i < len; i++) {
  28431. ret.push(other[i]);
  28432. }
  28433. return ret;
  28434. }
  28435. };
  28436. /**
  28437. * Serializes the VertexData.
  28438. * Returns a serialized object.
  28439. */
  28440. VertexData.prototype.serialize = function () {
  28441. var serializationObject = this.serialize();
  28442. if (this.positions) {
  28443. serializationObject.positions = this.positions;
  28444. }
  28445. if (this.normals) {
  28446. serializationObject.normals = this.normals;
  28447. }
  28448. if (this.tangents) {
  28449. serializationObject.tangents = this.tangents;
  28450. }
  28451. if (this.uvs) {
  28452. serializationObject.uvs = this.uvs;
  28453. }
  28454. if (this.uvs2) {
  28455. serializationObject.uvs2 = this.uvs2;
  28456. }
  28457. if (this.uvs3) {
  28458. serializationObject.uvs3 = this.uvs3;
  28459. }
  28460. if (this.uvs4) {
  28461. serializationObject.uvs4 = this.uvs4;
  28462. }
  28463. if (this.uvs5) {
  28464. serializationObject.uvs5 = this.uvs5;
  28465. }
  28466. if (this.uvs6) {
  28467. serializationObject.uvs6 = this.uvs6;
  28468. }
  28469. if (this.colors) {
  28470. serializationObject.colors = this.colors;
  28471. }
  28472. if (this.matricesIndices) {
  28473. serializationObject.matricesIndices = this.matricesIndices;
  28474. serializationObject.matricesIndices._isExpanded = true;
  28475. }
  28476. if (this.matricesWeights) {
  28477. serializationObject.matricesWeights = this.matricesWeights;
  28478. }
  28479. if (this.matricesIndicesExtra) {
  28480. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28481. serializationObject.matricesIndicesExtra._isExpanded = true;
  28482. }
  28483. if (this.matricesWeightsExtra) {
  28484. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28485. }
  28486. serializationObject.indices = this.indices;
  28487. return serializationObject;
  28488. };
  28489. // Statics
  28490. /**
  28491. * Returns the object VertexData associated to the passed mesh.
  28492. */
  28493. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28494. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28495. };
  28496. /**
  28497. * Returns the object VertexData associated to the passed geometry.
  28498. */
  28499. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28500. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28501. };
  28502. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28503. var result = new VertexData();
  28504. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28505. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28506. }
  28507. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28508. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28509. }
  28510. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28511. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28512. }
  28513. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28514. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28515. }
  28516. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28517. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28518. }
  28519. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28520. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28521. }
  28522. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28523. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28524. }
  28525. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28526. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28527. }
  28528. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28529. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28530. }
  28531. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28532. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28533. }
  28534. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28535. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28536. }
  28537. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28538. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28539. }
  28540. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28541. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28542. }
  28543. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28544. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28545. }
  28546. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28547. return result;
  28548. };
  28549. /**
  28550. * Creates the vertexData of the Ribbon.
  28551. */
  28552. VertexData.CreateRibbon = function (options) {
  28553. var pathArray = options.pathArray;
  28554. var closeArray = options.closeArray || false;
  28555. var closePath = options.closePath || false;
  28556. var invertUV = options.invertUV || false;
  28557. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28558. var offset = options.offset || defaultOffset;
  28559. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28560. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28561. var customUV = options.uvs;
  28562. var customColors = options.colors;
  28563. var positions = [];
  28564. var indices = [];
  28565. var normals = [];
  28566. var uvs = [];
  28567. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28568. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28569. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28570. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28571. var minlg; // minimal length among all paths from pathArray
  28572. var lg = []; // array of path lengths : nb of vertex per path
  28573. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28574. var p; // path iterator
  28575. var i; // point iterator
  28576. var j; // point iterator
  28577. // if single path in pathArray
  28578. if (pathArray.length < 2) {
  28579. var ar1 = [];
  28580. var ar2 = [];
  28581. for (i = 0; i < pathArray[0].length - offset; i++) {
  28582. ar1.push(pathArray[0][i]);
  28583. ar2.push(pathArray[0][i + offset]);
  28584. }
  28585. pathArray = [ar1, ar2];
  28586. }
  28587. // positions and horizontal distances (u)
  28588. var idc = 0;
  28589. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  28590. var path;
  28591. var l;
  28592. minlg = pathArray[0].length;
  28593. var vectlg;
  28594. var dist;
  28595. for (p = 0; p < pathArray.length; p++) {
  28596. uTotalDistance[p] = 0;
  28597. us[p] = [0];
  28598. path = pathArray[p];
  28599. l = path.length;
  28600. minlg = (minlg < l) ? minlg : l;
  28601. j = 0;
  28602. while (j < l) {
  28603. positions.push(path[j].x, path[j].y, path[j].z);
  28604. if (j > 0) {
  28605. vectlg = path[j].subtract(path[j - 1]).length();
  28606. dist = vectlg + uTotalDistance[p];
  28607. us[p].push(dist);
  28608. uTotalDistance[p] = dist;
  28609. }
  28610. j++;
  28611. }
  28612. if (closePath) {
  28613. j--;
  28614. positions.push(path[0].x, path[0].y, path[0].z);
  28615. vectlg = path[j].subtract(path[0]).length();
  28616. dist = vectlg + uTotalDistance[p];
  28617. us[p].push(dist);
  28618. uTotalDistance[p] = dist;
  28619. }
  28620. lg[p] = l + closePathCorr;
  28621. idx[p] = idc;
  28622. idc += (l + closePathCorr);
  28623. }
  28624. // vertical distances (v)
  28625. var path1;
  28626. var path2;
  28627. var vertex1 = null;
  28628. var vertex2 = null;
  28629. for (i = 0; i < minlg + closePathCorr; i++) {
  28630. vTotalDistance[i] = 0;
  28631. vs[i] = [0];
  28632. for (p = 0; p < pathArray.length - 1; p++) {
  28633. path1 = pathArray[p];
  28634. path2 = pathArray[p + 1];
  28635. if (i === minlg) {
  28636. vertex1 = path1[0];
  28637. vertex2 = path2[0];
  28638. }
  28639. else {
  28640. vertex1 = path1[i];
  28641. vertex2 = path2[i];
  28642. }
  28643. vectlg = vertex2.subtract(vertex1).length();
  28644. dist = vectlg + vTotalDistance[i];
  28645. vs[i].push(dist);
  28646. vTotalDistance[i] = dist;
  28647. }
  28648. if (closeArray && vertex2 && vertex1) {
  28649. path1 = pathArray[p];
  28650. path2 = pathArray[0];
  28651. if (i === minlg) {
  28652. vertex2 = path2[0];
  28653. }
  28654. vectlg = vertex2.subtract(vertex1).length();
  28655. dist = vectlg + vTotalDistance[i];
  28656. vTotalDistance[i] = dist;
  28657. }
  28658. }
  28659. // uvs
  28660. var u;
  28661. var v;
  28662. if (customUV) {
  28663. for (p = 0; p < customUV.length; p++) {
  28664. uvs.push(customUV[p].x, customUV[p].y);
  28665. }
  28666. }
  28667. else {
  28668. for (p = 0; p < pathArray.length; p++) {
  28669. for (i = 0; i < minlg + closePathCorr; i++) {
  28670. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  28671. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  28672. if (invertUV) {
  28673. uvs.push(v, u);
  28674. }
  28675. else {
  28676. uvs.push(u, v);
  28677. }
  28678. }
  28679. }
  28680. }
  28681. // indices
  28682. p = 0; // path index
  28683. var pi = 0; // positions array index
  28684. var l1 = lg[p] - 1; // path1 length
  28685. var l2 = lg[p + 1] - 1; // path2 length
  28686. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28687. var shft = idx[1] - idx[0]; // shift
  28688. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28689. while (pi <= min && p < path1nb) {
  28690. // 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
  28691. indices.push(pi, pi + shft, pi + 1);
  28692. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28693. pi += 1;
  28694. if (pi === min) {
  28695. p++;
  28696. if (p === lg.length - 1) {
  28697. shft = idx[0] - idx[p];
  28698. l1 = lg[p] - 1;
  28699. l2 = lg[0] - 1;
  28700. }
  28701. else {
  28702. shft = idx[p + 1] - idx[p];
  28703. l1 = lg[p] - 1;
  28704. l2 = lg[p + 1] - 1;
  28705. }
  28706. pi = idx[p];
  28707. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28708. }
  28709. }
  28710. // normals
  28711. VertexData.ComputeNormals(positions, indices, normals);
  28712. if (closePath) {
  28713. var indexFirst = 0;
  28714. var indexLast = 0;
  28715. for (p = 0; p < pathArray.length; p++) {
  28716. indexFirst = idx[p] * 3;
  28717. if (p + 1 < pathArray.length) {
  28718. indexLast = (idx[p + 1] - 1) * 3;
  28719. }
  28720. else {
  28721. indexLast = normals.length - 3;
  28722. }
  28723. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28724. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28725. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28726. normals[indexLast] = normals[indexFirst];
  28727. normals[indexLast + 1] = normals[indexFirst + 1];
  28728. normals[indexLast + 2] = normals[indexFirst + 2];
  28729. }
  28730. }
  28731. // sides
  28732. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28733. // Colors
  28734. var colors = null;
  28735. if (customColors) {
  28736. colors = new Float32Array(customColors.length * 4);
  28737. for (var c = 0; c < customColors.length; c++) {
  28738. colors[c * 4] = customColors[c].r;
  28739. colors[c * 4 + 1] = customColors[c].g;
  28740. colors[c * 4 + 2] = customColors[c].b;
  28741. colors[c * 4 + 3] = customColors[c].a;
  28742. }
  28743. }
  28744. // Result
  28745. var vertexData = new VertexData();
  28746. var positions32 = new Float32Array(positions);
  28747. var normals32 = new Float32Array(normals);
  28748. var uvs32 = new Float32Array(uvs);
  28749. vertexData.indices = indices;
  28750. vertexData.positions = positions32;
  28751. vertexData.normals = normals32;
  28752. vertexData.uvs = uvs32;
  28753. if (colors) {
  28754. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28755. }
  28756. if (closePath) {
  28757. vertexData._idx = idx;
  28758. }
  28759. return vertexData;
  28760. };
  28761. /**
  28762. * Creates the VertexData of the Box.
  28763. */
  28764. VertexData.CreateBox = function (options) {
  28765. var normalsSource = [
  28766. new BABYLON.Vector3(0, 0, 1),
  28767. new BABYLON.Vector3(0, 0, -1),
  28768. new BABYLON.Vector3(1, 0, 0),
  28769. new BABYLON.Vector3(-1, 0, 0),
  28770. new BABYLON.Vector3(0, 1, 0),
  28771. new BABYLON.Vector3(0, -1, 0)
  28772. ];
  28773. var indices = [];
  28774. var positions = [];
  28775. var normals = [];
  28776. var uvs = [];
  28777. var width = options.width || options.size || 1;
  28778. var height = options.height || options.size || 1;
  28779. var depth = options.depth || options.size || 1;
  28780. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28781. var faceUV = options.faceUV || new Array(6);
  28782. var faceColors = options.faceColors;
  28783. var colors = [];
  28784. // default face colors and UV if undefined
  28785. for (var f = 0; f < 6; f++) {
  28786. if (faceUV[f] === undefined) {
  28787. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28788. }
  28789. if (faceColors && faceColors[f] === undefined) {
  28790. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28791. }
  28792. }
  28793. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28794. // Create each face in turn.
  28795. for (var index = 0; index < normalsSource.length; index++) {
  28796. var normal = normalsSource[index];
  28797. // Get two vectors perpendicular to the face normal and to each other.
  28798. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28799. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28800. // Six indices (two triangles) per face.
  28801. var verticesLength = positions.length / 3;
  28802. indices.push(verticesLength);
  28803. indices.push(verticesLength + 1);
  28804. indices.push(verticesLength + 2);
  28805. indices.push(verticesLength);
  28806. indices.push(verticesLength + 2);
  28807. indices.push(verticesLength + 3);
  28808. // Four vertices per face.
  28809. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28810. positions.push(vertex.x, vertex.y, vertex.z);
  28811. normals.push(normal.x, normal.y, normal.z);
  28812. uvs.push(faceUV[index].z, faceUV[index].w);
  28813. if (faceColors) {
  28814. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28815. }
  28816. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28817. positions.push(vertex.x, vertex.y, vertex.z);
  28818. normals.push(normal.x, normal.y, normal.z);
  28819. uvs.push(faceUV[index].x, faceUV[index].w);
  28820. if (faceColors) {
  28821. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28822. }
  28823. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28824. positions.push(vertex.x, vertex.y, vertex.z);
  28825. normals.push(normal.x, normal.y, normal.z);
  28826. uvs.push(faceUV[index].x, faceUV[index].y);
  28827. if (faceColors) {
  28828. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28829. }
  28830. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28831. positions.push(vertex.x, vertex.y, vertex.z);
  28832. normals.push(normal.x, normal.y, normal.z);
  28833. uvs.push(faceUV[index].z, faceUV[index].y);
  28834. if (faceColors) {
  28835. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28836. }
  28837. }
  28838. // sides
  28839. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28840. // Result
  28841. var vertexData = new VertexData();
  28842. vertexData.indices = indices;
  28843. vertexData.positions = positions;
  28844. vertexData.normals = normals;
  28845. vertexData.uvs = uvs;
  28846. if (faceColors) {
  28847. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28848. vertexData.colors = totalColors;
  28849. }
  28850. return vertexData;
  28851. };
  28852. /**
  28853. * Creates the VertexData of the Sphere.
  28854. */
  28855. VertexData.CreateSphere = function (options) {
  28856. var segments = options.segments || 32;
  28857. var diameterX = options.diameterX || options.diameter || 1;
  28858. var diameterY = options.diameterY || options.diameter || 1;
  28859. var diameterZ = options.diameterZ || options.diameter || 1;
  28860. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28861. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28862. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28863. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28864. var totalZRotationSteps = 2 + segments;
  28865. var totalYRotationSteps = 2 * totalZRotationSteps;
  28866. var indices = [];
  28867. var positions = [];
  28868. var normals = [];
  28869. var uvs = [];
  28870. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28871. var normalizedZ = zRotationStep / totalZRotationSteps;
  28872. var angleZ = normalizedZ * Math.PI * slice;
  28873. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28874. var normalizedY = yRotationStep / totalYRotationSteps;
  28875. var angleY = normalizedY * Math.PI * 2 * arc;
  28876. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28877. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28878. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28879. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28880. var vertex = complete.multiply(radius);
  28881. var normal = complete.divide(radius).normalize();
  28882. positions.push(vertex.x, vertex.y, vertex.z);
  28883. normals.push(normal.x, normal.y, normal.z);
  28884. uvs.push(normalizedY, normalizedZ);
  28885. }
  28886. if (zRotationStep > 0) {
  28887. var verticesCount = positions.length / 3;
  28888. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28889. indices.push((firstIndex));
  28890. indices.push((firstIndex + 1));
  28891. indices.push(firstIndex + totalYRotationSteps + 1);
  28892. indices.push((firstIndex + totalYRotationSteps + 1));
  28893. indices.push((firstIndex + 1));
  28894. indices.push((firstIndex + totalYRotationSteps + 2));
  28895. }
  28896. }
  28897. }
  28898. // Sides
  28899. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28900. // Result
  28901. var vertexData = new VertexData();
  28902. vertexData.indices = indices;
  28903. vertexData.positions = positions;
  28904. vertexData.normals = normals;
  28905. vertexData.uvs = uvs;
  28906. return vertexData;
  28907. };
  28908. /**
  28909. * Creates the VertexData of the Cylinder or Cone.
  28910. */
  28911. VertexData.CreateCylinder = function (options) {
  28912. var height = options.height || 2;
  28913. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28914. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  28915. var tessellation = options.tessellation || 24;
  28916. var subdivisions = options.subdivisions || 1;
  28917. var hasRings = options.hasRings ? true : false;
  28918. var enclose = options.enclose ? true : false;
  28919. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28920. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28921. var faceUV = options.faceUV || new Array(3);
  28922. var faceColors = options.faceColors;
  28923. // default face colors and UV if undefined
  28924. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28925. var ringNb = (hasRings) ? subdivisions : 1;
  28926. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28927. var f;
  28928. for (f = 0; f < surfaceNb; f++) {
  28929. if (faceColors && faceColors[f] === undefined) {
  28930. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28931. }
  28932. }
  28933. for (f = 0; f < surfaceNb; f++) {
  28934. if (faceUV && faceUV[f] === undefined) {
  28935. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28936. }
  28937. }
  28938. var indices = new Array();
  28939. var positions = new Array();
  28940. var normals = new Array();
  28941. var uvs = new Array();
  28942. var colors = new Array();
  28943. var angle_step = Math.PI * 2 * arc / tessellation;
  28944. var angle;
  28945. var h;
  28946. var radius;
  28947. var tan = (diameterBottom - diameterTop) / 2 / height;
  28948. var ringVertex = BABYLON.Vector3.Zero();
  28949. var ringNormal = BABYLON.Vector3.Zero();
  28950. var ringFirstVertex = BABYLON.Vector3.Zero();
  28951. var ringFirstNormal = BABYLON.Vector3.Zero();
  28952. var quadNormal = BABYLON.Vector3.Zero();
  28953. var Y = BABYLON.Axis.Y;
  28954. // positions, normals, uvs
  28955. var i;
  28956. var j;
  28957. var r;
  28958. var ringIdx = 1;
  28959. var s = 1; // surface index
  28960. var cs = 0;
  28961. var v = 0;
  28962. for (i = 0; i <= subdivisions; i++) {
  28963. h = i / subdivisions;
  28964. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28965. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28966. for (r = 0; r < ringIdx; r++) {
  28967. if (hasRings) {
  28968. s += r;
  28969. }
  28970. if (enclose) {
  28971. s += 2 * r;
  28972. }
  28973. for (j = 0; j <= tessellation; j++) {
  28974. angle = j * angle_step;
  28975. // position
  28976. ringVertex.x = Math.cos(-angle) * radius;
  28977. ringVertex.y = -height / 2 + h * height;
  28978. ringVertex.z = Math.sin(-angle) * radius;
  28979. // normal
  28980. if (diameterTop === 0 && i === subdivisions) {
  28981. // if no top cap, reuse former normals
  28982. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28983. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28984. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28985. }
  28986. else {
  28987. ringNormal.x = ringVertex.x;
  28988. ringNormal.z = ringVertex.z;
  28989. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28990. ringNormal.normalize();
  28991. }
  28992. // keep first ring vertex values for enclose
  28993. if (j === 0) {
  28994. ringFirstVertex.copyFrom(ringVertex);
  28995. ringFirstNormal.copyFrom(ringNormal);
  28996. }
  28997. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28998. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28999. if (hasRings) {
  29000. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29001. }
  29002. else {
  29003. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29004. }
  29005. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29006. if (faceColors) {
  29007. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29008. }
  29009. }
  29010. // if enclose, add four vertices and their dedicated normals
  29011. if (arc !== 1 && enclose) {
  29012. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29013. positions.push(0, ringVertex.y, 0);
  29014. positions.push(0, ringVertex.y, 0);
  29015. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29016. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29017. quadNormal.normalize();
  29018. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29019. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29020. quadNormal.normalize();
  29021. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29022. if (hasRings) {
  29023. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29024. }
  29025. else {
  29026. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29027. }
  29028. uvs.push(faceUV[s + 1].x, v);
  29029. uvs.push(faceUV[s + 1].z, v);
  29030. if (hasRings) {
  29031. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29032. }
  29033. else {
  29034. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29035. }
  29036. uvs.push(faceUV[s + 2].x, v);
  29037. uvs.push(faceUV[s + 2].z, v);
  29038. if (faceColors) {
  29039. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29040. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29041. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29042. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29043. }
  29044. }
  29045. if (cs !== s) {
  29046. cs = s;
  29047. }
  29048. }
  29049. }
  29050. // indices
  29051. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29052. var s;
  29053. i = 0;
  29054. for (s = 0; s < subdivisions; s++) {
  29055. var i0 = 0;
  29056. var i1 = 0;
  29057. var i2 = 0;
  29058. var i3 = 0;
  29059. for (j = 0; j < tessellation; j++) {
  29060. i0 = i * (e + 1) + j;
  29061. i1 = (i + 1) * (e + 1) + j;
  29062. i2 = i * (e + 1) + (j + 1);
  29063. i3 = (i + 1) * (e + 1) + (j + 1);
  29064. indices.push(i0, i1, i2);
  29065. indices.push(i3, i2, i1);
  29066. }
  29067. if (arc !== 1 && enclose) {
  29068. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29069. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29070. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29071. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29072. }
  29073. i = (hasRings) ? (i + 2) : (i + 1);
  29074. }
  29075. // Caps
  29076. var createCylinderCap = function (isTop) {
  29077. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29078. if (radius === 0) {
  29079. return;
  29080. }
  29081. // Cap positions, normals & uvs
  29082. var angle;
  29083. var circleVector;
  29084. var i;
  29085. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29086. var c = null;
  29087. if (faceColors) {
  29088. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29089. }
  29090. // cap center
  29091. var vbase = positions.length / 3;
  29092. var offset = isTop ? height / 2 : -height / 2;
  29093. var center = new BABYLON.Vector3(0, offset, 0);
  29094. positions.push(center.x, center.y, center.z);
  29095. normals.push(0, isTop ? 1 : -1, 0);
  29096. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29097. if (c) {
  29098. colors.push(c.r, c.g, c.b, c.a);
  29099. }
  29100. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29101. for (i = 0; i <= tessellation; i++) {
  29102. angle = Math.PI * 2 * i * arc / tessellation;
  29103. var cos = Math.cos(-angle);
  29104. var sin = Math.sin(-angle);
  29105. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29106. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29107. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29108. normals.push(0, isTop ? 1 : -1, 0);
  29109. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29110. if (c) {
  29111. colors.push(c.r, c.g, c.b, c.a);
  29112. }
  29113. }
  29114. // Cap indices
  29115. for (i = 0; i < tessellation; i++) {
  29116. if (!isTop) {
  29117. indices.push(vbase);
  29118. indices.push(vbase + (i + 1));
  29119. indices.push(vbase + (i + 2));
  29120. }
  29121. else {
  29122. indices.push(vbase);
  29123. indices.push(vbase + (i + 2));
  29124. indices.push(vbase + (i + 1));
  29125. }
  29126. }
  29127. };
  29128. // add caps to geometry
  29129. createCylinderCap(false);
  29130. createCylinderCap(true);
  29131. // Sides
  29132. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29133. var vertexData = new VertexData();
  29134. vertexData.indices = indices;
  29135. vertexData.positions = positions;
  29136. vertexData.normals = normals;
  29137. vertexData.uvs = uvs;
  29138. if (faceColors) {
  29139. vertexData.colors = colors;
  29140. }
  29141. return vertexData;
  29142. };
  29143. /**
  29144. * Creates the VertexData of the Torus.
  29145. */
  29146. VertexData.CreateTorus = function (options) {
  29147. var indices = [];
  29148. var positions = [];
  29149. var normals = [];
  29150. var uvs = [];
  29151. var diameter = options.diameter || 1;
  29152. var thickness = options.thickness || 0.5;
  29153. var tessellation = options.tessellation || 16;
  29154. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29155. var stride = tessellation + 1;
  29156. for (var i = 0; i <= tessellation; i++) {
  29157. var u = i / tessellation;
  29158. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29159. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29160. for (var j = 0; j <= tessellation; j++) {
  29161. var v = 1 - j / tessellation;
  29162. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29163. var dx = Math.cos(innerAngle);
  29164. var dy = Math.sin(innerAngle);
  29165. // Create a vertex.
  29166. var normal = new BABYLON.Vector3(dx, dy, 0);
  29167. var position = normal.scale(thickness / 2);
  29168. var textureCoordinate = new BABYLON.Vector2(u, v);
  29169. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29170. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29171. positions.push(position.x, position.y, position.z);
  29172. normals.push(normal.x, normal.y, normal.z);
  29173. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29174. // And create indices for two triangles.
  29175. var nextI = (i + 1) % stride;
  29176. var nextJ = (j + 1) % stride;
  29177. indices.push(i * stride + j);
  29178. indices.push(i * stride + nextJ);
  29179. indices.push(nextI * stride + j);
  29180. indices.push(i * stride + nextJ);
  29181. indices.push(nextI * stride + nextJ);
  29182. indices.push(nextI * stride + j);
  29183. }
  29184. }
  29185. // Sides
  29186. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29187. // Result
  29188. var vertexData = new VertexData();
  29189. vertexData.indices = indices;
  29190. vertexData.positions = positions;
  29191. vertexData.normals = normals;
  29192. vertexData.uvs = uvs;
  29193. return vertexData;
  29194. };
  29195. /**
  29196. * Creates the VertexData of the LineSystem.
  29197. */
  29198. VertexData.CreateLineSystem = function (options) {
  29199. var indices = [];
  29200. var positions = [];
  29201. var lines = options.lines;
  29202. var idx = 0;
  29203. for (var l = 0; l < lines.length; l++) {
  29204. var points = lines[l];
  29205. for (var index = 0; index < points.length; index++) {
  29206. positions.push(points[index].x, points[index].y, points[index].z);
  29207. if (index > 0) {
  29208. indices.push(idx - 1);
  29209. indices.push(idx);
  29210. }
  29211. idx++;
  29212. }
  29213. }
  29214. var vertexData = new VertexData();
  29215. vertexData.indices = indices;
  29216. vertexData.positions = positions;
  29217. return vertexData;
  29218. };
  29219. /**
  29220. * Create the VertexData of the DashedLines.
  29221. */
  29222. VertexData.CreateDashedLines = function (options) {
  29223. var dashSize = options.dashSize || 3;
  29224. var gapSize = options.gapSize || 1;
  29225. var dashNb = options.dashNb || 200;
  29226. var points = options.points;
  29227. var positions = new Array();
  29228. var indices = new Array();
  29229. var curvect = BABYLON.Vector3.Zero();
  29230. var lg = 0;
  29231. var nb = 0;
  29232. var shft = 0;
  29233. var dashshft = 0;
  29234. var curshft = 0;
  29235. var idx = 0;
  29236. var i = 0;
  29237. for (i = 0; i < points.length - 1; i++) {
  29238. points[i + 1].subtractToRef(points[i], curvect);
  29239. lg += curvect.length();
  29240. }
  29241. shft = lg / dashNb;
  29242. dashshft = dashSize * shft / (dashSize + gapSize);
  29243. for (i = 0; i < points.length - 1; i++) {
  29244. points[i + 1].subtractToRef(points[i], curvect);
  29245. nb = Math.floor(curvect.length() / shft);
  29246. curvect.normalize();
  29247. for (var j = 0; j < nb; j++) {
  29248. curshft = shft * j;
  29249. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29250. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29251. indices.push(idx, idx + 1);
  29252. idx += 2;
  29253. }
  29254. }
  29255. // Result
  29256. var vertexData = new VertexData();
  29257. vertexData.positions = positions;
  29258. vertexData.indices = indices;
  29259. return vertexData;
  29260. };
  29261. /**
  29262. * Creates the VertexData of the Ground.
  29263. */
  29264. VertexData.CreateGround = function (options) {
  29265. var indices = [];
  29266. var positions = [];
  29267. var normals = [];
  29268. var uvs = [];
  29269. var row, col;
  29270. var width = options.width || 1;
  29271. var height = options.height || 1;
  29272. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29273. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29274. for (row = 0; row <= subdivisionsY; row++) {
  29275. for (col = 0; col <= subdivisionsX; col++) {
  29276. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29277. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29278. positions.push(position.x, position.y, position.z);
  29279. normals.push(normal.x, normal.y, normal.z);
  29280. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29281. }
  29282. }
  29283. for (row = 0; row < subdivisionsY; row++) {
  29284. for (col = 0; col < subdivisionsX; col++) {
  29285. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29286. indices.push(col + 1 + row * (subdivisionsX + 1));
  29287. indices.push(col + row * (subdivisionsX + 1));
  29288. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29289. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29290. indices.push(col + row * (subdivisionsX + 1));
  29291. }
  29292. }
  29293. // Result
  29294. var vertexData = new VertexData();
  29295. vertexData.indices = indices;
  29296. vertexData.positions = positions;
  29297. vertexData.normals = normals;
  29298. vertexData.uvs = uvs;
  29299. return vertexData;
  29300. };
  29301. /**
  29302. * Creates the VertexData of the TiledGround.
  29303. */
  29304. VertexData.CreateTiledGround = function (options) {
  29305. var xmin = options.xmin || -1.0;
  29306. var zmin = options.zmin || -1.0;
  29307. var xmax = options.xmax || 1.0;
  29308. var zmax = options.zmax || 1.0;
  29309. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29310. var precision = options.precision || { w: 1, h: 1 };
  29311. var indices = new Array();
  29312. var positions = new Array();
  29313. var normals = new Array();
  29314. var uvs = new Array();
  29315. var row, col, tileRow, tileCol;
  29316. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29317. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29318. precision.w = (precision.w < 1) ? 1 : precision.w;
  29319. precision.h = (precision.h < 1) ? 1 : precision.h;
  29320. var tileSize = {
  29321. 'w': (xmax - xmin) / subdivisions.w,
  29322. 'h': (zmax - zmin) / subdivisions.h
  29323. };
  29324. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29325. // Indices
  29326. var base = positions.length / 3;
  29327. var rowLength = precision.w + 1;
  29328. for (row = 0; row < precision.h; row++) {
  29329. for (col = 0; col < precision.w; col++) {
  29330. var square = [
  29331. base + col + row * rowLength,
  29332. base + (col + 1) + row * rowLength,
  29333. base + (col + 1) + (row + 1) * rowLength,
  29334. base + col + (row + 1) * rowLength
  29335. ];
  29336. indices.push(square[1]);
  29337. indices.push(square[2]);
  29338. indices.push(square[3]);
  29339. indices.push(square[0]);
  29340. indices.push(square[1]);
  29341. indices.push(square[3]);
  29342. }
  29343. }
  29344. // Position, normals and uvs
  29345. var position = BABYLON.Vector3.Zero();
  29346. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29347. for (row = 0; row <= precision.h; row++) {
  29348. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29349. for (col = 0; col <= precision.w; col++) {
  29350. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29351. position.y = 0;
  29352. positions.push(position.x, position.y, position.z);
  29353. normals.push(normal.x, normal.y, normal.z);
  29354. uvs.push(col / precision.w, row / precision.h);
  29355. }
  29356. }
  29357. }
  29358. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29359. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29360. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29361. }
  29362. }
  29363. // Result
  29364. var vertexData = new VertexData();
  29365. vertexData.indices = indices;
  29366. vertexData.positions = positions;
  29367. vertexData.normals = normals;
  29368. vertexData.uvs = uvs;
  29369. return vertexData;
  29370. };
  29371. /**
  29372. * Creates the VertexData of the Ground designed from a heightmap.
  29373. */
  29374. VertexData.CreateGroundFromHeightMap = function (options) {
  29375. var indices = [];
  29376. var positions = [];
  29377. var normals = [];
  29378. var uvs = [];
  29379. var row, col;
  29380. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29381. // Vertices
  29382. for (row = 0; row <= options.subdivisions; row++) {
  29383. for (col = 0; col <= options.subdivisions; col++) {
  29384. 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));
  29385. // Compute height
  29386. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29387. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29388. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29389. var r = options.buffer[pos] / 255.0;
  29390. var g = options.buffer[pos + 1] / 255.0;
  29391. var b = options.buffer[pos + 2] / 255.0;
  29392. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29393. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29394. // Add vertex
  29395. positions.push(position.x, position.y, position.z);
  29396. normals.push(0, 0, 0);
  29397. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29398. }
  29399. }
  29400. // Indices
  29401. for (row = 0; row < options.subdivisions; row++) {
  29402. for (col = 0; col < options.subdivisions; col++) {
  29403. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29404. indices.push(col + 1 + row * (options.subdivisions + 1));
  29405. indices.push(col + row * (options.subdivisions + 1));
  29406. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29407. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29408. indices.push(col + row * (options.subdivisions + 1));
  29409. }
  29410. }
  29411. // Normals
  29412. VertexData.ComputeNormals(positions, indices, normals);
  29413. // Result
  29414. var vertexData = new VertexData();
  29415. vertexData.indices = indices;
  29416. vertexData.positions = positions;
  29417. vertexData.normals = normals;
  29418. vertexData.uvs = uvs;
  29419. return vertexData;
  29420. };
  29421. /**
  29422. * Creates the VertexData of the Plane.
  29423. */
  29424. VertexData.CreatePlane = function (options) {
  29425. var indices = [];
  29426. var positions = [];
  29427. var normals = [];
  29428. var uvs = [];
  29429. var width = options.width || options.size || 1;
  29430. var height = options.height || options.size || 1;
  29431. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29432. // Vertices
  29433. var halfWidth = width / 2.0;
  29434. var halfHeight = height / 2.0;
  29435. positions.push(-halfWidth, -halfHeight, 0);
  29436. normals.push(0, 0, -1.0);
  29437. uvs.push(0.0, 0.0);
  29438. positions.push(halfWidth, -halfHeight, 0);
  29439. normals.push(0, 0, -1.0);
  29440. uvs.push(1.0, 0.0);
  29441. positions.push(halfWidth, halfHeight, 0);
  29442. normals.push(0, 0, -1.0);
  29443. uvs.push(1.0, 1.0);
  29444. positions.push(-halfWidth, halfHeight, 0);
  29445. normals.push(0, 0, -1.0);
  29446. uvs.push(0.0, 1.0);
  29447. // Indices
  29448. indices.push(0);
  29449. indices.push(1);
  29450. indices.push(2);
  29451. indices.push(0);
  29452. indices.push(2);
  29453. indices.push(3);
  29454. // Sides
  29455. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29456. // Result
  29457. var vertexData = new VertexData();
  29458. vertexData.indices = indices;
  29459. vertexData.positions = positions;
  29460. vertexData.normals = normals;
  29461. vertexData.uvs = uvs;
  29462. return vertexData;
  29463. };
  29464. /**
  29465. * Creates the VertexData of the Disc or regular Polygon.
  29466. */
  29467. VertexData.CreateDisc = function (options) {
  29468. var positions = new Array();
  29469. var indices = new Array();
  29470. var normals = new Array();
  29471. var uvs = new Array();
  29472. var radius = options.radius || 0.5;
  29473. var tessellation = options.tessellation || 64;
  29474. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29475. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29476. // positions and uvs
  29477. positions.push(0, 0, 0); // disc center first
  29478. uvs.push(0.5, 0.5);
  29479. var theta = Math.PI * 2 * arc;
  29480. var step = theta / tessellation;
  29481. for (var a = 0; a < theta; a += step) {
  29482. var x = Math.cos(a);
  29483. var y = Math.sin(a);
  29484. var u = (x + 1) / 2;
  29485. var v = (1 - y) / 2;
  29486. positions.push(radius * x, radius * y, 0);
  29487. uvs.push(u, v);
  29488. }
  29489. if (arc === 1) {
  29490. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29491. uvs.push(uvs[2], uvs[3]);
  29492. }
  29493. //indices
  29494. var vertexNb = positions.length / 3;
  29495. for (var i = 1; i < vertexNb - 1; i++) {
  29496. indices.push(i + 1, 0, i);
  29497. }
  29498. // result
  29499. VertexData.ComputeNormals(positions, indices, normals);
  29500. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29501. var vertexData = new VertexData();
  29502. vertexData.indices = indices;
  29503. vertexData.positions = positions;
  29504. vertexData.normals = normals;
  29505. vertexData.uvs = uvs;
  29506. return vertexData;
  29507. };
  29508. /**
  29509. * Re-creates the VertexData of the Polygon for sideOrientation.
  29510. */
  29511. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29512. var faceUV = fUV || new Array(3);
  29513. var faceColors = fColors;
  29514. var colors = [];
  29515. // default face colors and UV if undefined
  29516. for (var f = 0; f < 3; f++) {
  29517. if (faceUV[f] === undefined) {
  29518. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29519. }
  29520. if (faceColors && faceColors[f] === undefined) {
  29521. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29522. }
  29523. }
  29524. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29525. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29526. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29527. var indices = polygon.getIndices();
  29528. // set face colours and textures
  29529. var idx = 0;
  29530. var face = 0;
  29531. for (var index = 0; index < normals.length; index += 3) {
  29532. //Edge Face no. 1
  29533. if (Math.abs(normals[index + 1]) < 0.001) {
  29534. face = 1;
  29535. }
  29536. //Top Face no. 0
  29537. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29538. face = 0;
  29539. }
  29540. //Bottom Face no. 2
  29541. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29542. face = 2;
  29543. }
  29544. idx = index / 3;
  29545. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29546. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29547. if (faceColors) {
  29548. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29549. }
  29550. }
  29551. // sides
  29552. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29553. // Result
  29554. var vertexData = new VertexData();
  29555. vertexData.indices = indices;
  29556. vertexData.positions = positions;
  29557. vertexData.normals = normals;
  29558. vertexData.uvs = uvs;
  29559. if (faceColors) {
  29560. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29561. vertexData.colors = totalColors;
  29562. }
  29563. return vertexData;
  29564. };
  29565. /**
  29566. * Creates the VertexData of the IcoSphere.
  29567. */
  29568. VertexData.CreateIcoSphere = function (options) {
  29569. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29570. var radius = options.radius || 1;
  29571. var flat = (options.flat === undefined) ? true : options.flat;
  29572. var subdivisions = options.subdivisions || 4;
  29573. var radiusX = options.radiusX || radius;
  29574. var radiusY = options.radiusY || radius;
  29575. var radiusZ = options.radiusZ || radius;
  29576. var t = (1 + Math.sqrt(5)) / 2;
  29577. // 12 vertex x,y,z
  29578. var ico_vertices = [
  29579. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29580. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29581. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29582. ];
  29583. // index of 3 vertex makes a face of icopshere
  29584. var ico_indices = [
  29585. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29586. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29587. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29588. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29589. ];
  29590. // vertex for uv have aliased position, not for UV
  29591. var vertices_unalias_id = [
  29592. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29593. // vertex alias
  29594. 0,
  29595. 2,
  29596. 3,
  29597. 3,
  29598. 3,
  29599. 4,
  29600. 7,
  29601. 8,
  29602. 9,
  29603. 9,
  29604. 10,
  29605. 11 // 23: B + 12
  29606. ];
  29607. // uv as integer step (not pixels !)
  29608. var ico_vertexuv = [
  29609. 5, 1, 3, 1, 6, 4, 0, 0,
  29610. 5, 3, 4, 2, 2, 2, 4, 0,
  29611. 2, 0, 1, 1, 6, 0, 6, 2,
  29612. // vertex alias (for same vertex on different faces)
  29613. 0, 4,
  29614. 3, 3,
  29615. 4, 4,
  29616. 3, 1,
  29617. 4, 2,
  29618. 4, 4,
  29619. 0, 2,
  29620. 1, 1,
  29621. 2, 2,
  29622. 3, 3,
  29623. 1, 3,
  29624. 2, 4 // 23: B + 12
  29625. ];
  29626. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29627. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29628. // First island of uv mapping
  29629. // v = 4h 3+ 2
  29630. // v = 3h 9+ 4
  29631. // v = 2h 9+ 5 B
  29632. // v = 1h 9 1 0
  29633. // v = 0h 3 8 7 A
  29634. // u = 0 1 2 3 4 5 6 *a
  29635. // Second island of uv mapping
  29636. // v = 4h 0+ B+ 4+
  29637. // v = 3h A+ 2+
  29638. // v = 2h 7+ 6 3+
  29639. // v = 1h 8+ 3+
  29640. // v = 0h
  29641. // u = 0 1 2 3 4 5 6 *a
  29642. // Face layout on texture UV mapping
  29643. // ============
  29644. // \ 4 /\ 16 / ======
  29645. // \ / \ / /\ 11 /
  29646. // \/ 7 \/ / \ /
  29647. // ======= / 10 \/
  29648. // /\ 17 /\ =======
  29649. // / \ / \ \ 15 /\
  29650. // / 8 \/ 12 \ \ / \
  29651. // ============ \/ 6 \
  29652. // \ 18 /\ ============
  29653. // \ / \ \ 5 /\ 0 /
  29654. // \/ 13 \ \ / \ /
  29655. // ======= \/ 1 \/
  29656. // =============
  29657. // /\ 19 /\ 2 /\
  29658. // / \ / \ / \
  29659. // / 14 \/ 9 \/ 3 \
  29660. // ===================
  29661. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29662. var ustep = 138 / 1024;
  29663. var vstep = 239 / 1024;
  29664. var uoffset = 60 / 1024;
  29665. var voffset = 26 / 1024;
  29666. // Second island should have margin, not to touch the first island
  29667. // avoid any borderline artefact in pixel rounding
  29668. var island_u_offset = -40 / 1024;
  29669. var island_v_offset = +20 / 1024;
  29670. // face is either island 0 or 1 :
  29671. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29672. var island = [
  29673. 0, 0, 0, 0, 1,
  29674. 0, 0, 1, 1, 0,
  29675. 0, 0, 1, 1, 0,
  29676. 0, 1, 1, 1, 0 // 15 - 19
  29677. ];
  29678. var indices = new Array();
  29679. var positions = new Array();
  29680. var normals = new Array();
  29681. var uvs = new Array();
  29682. var current_indice = 0;
  29683. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29684. var face_vertex_pos = new Array(3);
  29685. var face_vertex_uv = new Array(3);
  29686. var v012;
  29687. for (v012 = 0; v012 < 3; v012++) {
  29688. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29689. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29690. }
  29691. // create all with normals
  29692. for (var face = 0; face < 20; face++) {
  29693. // 3 vertex per face
  29694. for (v012 = 0; v012 < 3; v012++) {
  29695. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29696. var v_id = ico_indices[3 * face + v012];
  29697. // vertex have 3D position (x,y,z)
  29698. 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]);
  29699. // Normalize to get normal, then scale to radius
  29700. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29701. // uv Coordinates from vertex ID
  29702. 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);
  29703. }
  29704. // Subdivide the face (interpolate pos, norm, uv)
  29705. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29706. // - norm is linear interpolation of vertex corner normal
  29707. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29708. // - uv is linear interpolation
  29709. //
  29710. // Topology is as below for sub-divide by 2
  29711. // vertex shown as v0,v1,v2
  29712. // interp index is i1 to progress in range [v0,v1[
  29713. // interp index is i2 to progress in range [v0,v2[
  29714. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29715. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29716. //
  29717. //
  29718. // i2 v2
  29719. // ^ ^
  29720. // / / \
  29721. // / / \
  29722. // / / \
  29723. // / / (0,1) \
  29724. // / #---------\
  29725. // / / \ (0,0)'/ \
  29726. // / / \ / \
  29727. // / / \ / \
  29728. // / / (0,0) \ / (1,0) \
  29729. // / #---------#---------\
  29730. // v0 v1
  29731. //
  29732. // --------------------> i1
  29733. //
  29734. // interp of (i1,i2):
  29735. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29736. // along i1 : lerp(x0,x1, i1/(S-i2))
  29737. //
  29738. // centroid of triangle is needed to get help normal computation
  29739. // (c1,c2) are used for centroid location
  29740. var interp_vertex = function (i1, i2, c1, c2) {
  29741. // vertex is interpolated from
  29742. // - face_vertex_pos[0..2]
  29743. // - face_vertex_uv[0..2]
  29744. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29745. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29746. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29747. pos_interp.normalize();
  29748. var vertex_normal;
  29749. if (flat) {
  29750. // in flat mode, recalculate normal as face centroid normal
  29751. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29752. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29753. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29754. }
  29755. else {
  29756. // in smooth mode, recalculate normal from each single vertex position
  29757. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29758. }
  29759. // Vertex normal need correction due to X,Y,Z radius scaling
  29760. vertex_normal.x /= radiusX;
  29761. vertex_normal.y /= radiusY;
  29762. vertex_normal.z /= radiusZ;
  29763. vertex_normal.normalize();
  29764. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29765. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29766. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29767. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29768. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29769. uvs.push(uv_interp.x, uv_interp.y);
  29770. // push each vertex has member of a face
  29771. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29772. indices.push(current_indice);
  29773. current_indice++;
  29774. };
  29775. for (var i2 = 0; i2 < subdivisions; i2++) {
  29776. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29777. // face : (i1,i2) for /\ :
  29778. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29779. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29780. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29781. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29782. if (i1 + i2 + 1 < subdivisions) {
  29783. // face : (i1,i2)' for \/ :
  29784. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29785. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29786. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29787. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29788. }
  29789. }
  29790. }
  29791. }
  29792. // Sides
  29793. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29794. // Result
  29795. var vertexData = new VertexData();
  29796. vertexData.indices = indices;
  29797. vertexData.positions = positions;
  29798. vertexData.normals = normals;
  29799. vertexData.uvs = uvs;
  29800. return vertexData;
  29801. };
  29802. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29803. /**
  29804. * Creates the VertexData of the Polyhedron.
  29805. */
  29806. VertexData.CreatePolyhedron = function (options) {
  29807. // provided polyhedron types :
  29808. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29809. // 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)
  29810. var polyhedra = [];
  29811. 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]] };
  29812. 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]] };
  29813. polyhedra[2] = {
  29814. 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]],
  29815. 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]]
  29816. };
  29817. polyhedra[3] = {
  29818. 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]],
  29819. 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]]
  29820. };
  29821. polyhedra[4] = {
  29822. 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]],
  29823. 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]]
  29824. };
  29825. 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]] };
  29826. 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]] };
  29827. 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]] };
  29828. 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]] };
  29829. 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]] };
  29830. 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]] };
  29831. 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]] };
  29832. 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]] };
  29833. 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]] };
  29834. polyhedra[14] = {
  29835. 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]],
  29836. 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]]
  29837. };
  29838. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29839. var size = options.size;
  29840. var sizeX = options.sizeX || size || 1;
  29841. var sizeY = options.sizeY || size || 1;
  29842. var sizeZ = options.sizeZ || size || 1;
  29843. var data = options.custom || polyhedra[type];
  29844. var nbfaces = data.face.length;
  29845. var faceUV = options.faceUV || new Array(nbfaces);
  29846. var faceColors = options.faceColors;
  29847. var flat = (options.flat === undefined) ? true : options.flat;
  29848. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29849. var positions = new Array();
  29850. var indices = new Array();
  29851. var normals = new Array();
  29852. var uvs = new Array();
  29853. var colors = new Array();
  29854. var index = 0;
  29855. var faceIdx = 0; // face cursor in the array "indexes"
  29856. var indexes = new Array();
  29857. var i = 0;
  29858. var f = 0;
  29859. var u, v, ang, x, y, tmp;
  29860. // default face colors and UV if undefined
  29861. if (flat) {
  29862. for (f = 0; f < nbfaces; f++) {
  29863. if (faceColors && faceColors[f] === undefined) {
  29864. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29865. }
  29866. if (faceUV && faceUV[f] === undefined) {
  29867. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29868. }
  29869. }
  29870. }
  29871. if (!flat) {
  29872. for (i = 0; i < data.vertex.length; i++) {
  29873. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29874. uvs.push(0, 0);
  29875. }
  29876. for (f = 0; f < nbfaces; f++) {
  29877. for (i = 0; i < data.face[f].length - 2; i++) {
  29878. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29879. }
  29880. }
  29881. }
  29882. else {
  29883. for (f = 0; f < nbfaces; f++) {
  29884. var fl = data.face[f].length; // number of vertices of the current face
  29885. ang = 2 * Math.PI / fl;
  29886. x = 0.5 * Math.tan(ang / 2);
  29887. y = 0.5;
  29888. // positions, uvs, colors
  29889. for (i = 0; i < fl; i++) {
  29890. // positions
  29891. 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);
  29892. indexes.push(index);
  29893. index++;
  29894. // uvs
  29895. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29896. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29897. uvs.push(u, v);
  29898. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29899. y = x * Math.sin(ang) + y * Math.cos(ang);
  29900. x = tmp;
  29901. // colors
  29902. if (faceColors) {
  29903. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29904. }
  29905. }
  29906. // indices from indexes
  29907. for (i = 0; i < fl - 2; i++) {
  29908. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29909. }
  29910. faceIdx += fl;
  29911. }
  29912. }
  29913. VertexData.ComputeNormals(positions, indices, normals);
  29914. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29915. var vertexData = new VertexData();
  29916. vertexData.positions = positions;
  29917. vertexData.indices = indices;
  29918. vertexData.normals = normals;
  29919. vertexData.uvs = uvs;
  29920. if (faceColors && flat) {
  29921. vertexData.colors = colors;
  29922. }
  29923. return vertexData;
  29924. };
  29925. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29926. /**
  29927. * Creates the VertexData of the Torus Knot.
  29928. */
  29929. VertexData.CreateTorusKnot = function (options) {
  29930. var indices = new Array();
  29931. var positions = new Array();
  29932. var normals = new Array();
  29933. var uvs = new Array();
  29934. var radius = options.radius || 2;
  29935. var tube = options.tube || 0.5;
  29936. var radialSegments = options.radialSegments || 32;
  29937. var tubularSegments = options.tubularSegments || 32;
  29938. var p = options.p || 2;
  29939. var q = options.q || 3;
  29940. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29941. // Helper
  29942. var getPos = function (angle) {
  29943. var cu = Math.cos(angle);
  29944. var su = Math.sin(angle);
  29945. var quOverP = q / p * angle;
  29946. var cs = Math.cos(quOverP);
  29947. var tx = radius * (2 + cs) * 0.5 * cu;
  29948. var ty = radius * (2 + cs) * su * 0.5;
  29949. var tz = radius * Math.sin(quOverP) * 0.5;
  29950. return new BABYLON.Vector3(tx, ty, tz);
  29951. };
  29952. // Vertices
  29953. var i;
  29954. var j;
  29955. for (i = 0; i <= radialSegments; i++) {
  29956. var modI = i % radialSegments;
  29957. var u = modI / radialSegments * 2 * p * Math.PI;
  29958. var p1 = getPos(u);
  29959. var p2 = getPos(u + 0.01);
  29960. var tang = p2.subtract(p1);
  29961. var n = p2.add(p1);
  29962. var bitan = BABYLON.Vector3.Cross(tang, n);
  29963. n = BABYLON.Vector3.Cross(bitan, tang);
  29964. bitan.normalize();
  29965. n.normalize();
  29966. for (j = 0; j < tubularSegments; j++) {
  29967. var modJ = j % tubularSegments;
  29968. var v = modJ / tubularSegments * 2 * Math.PI;
  29969. var cx = -tube * Math.cos(v);
  29970. var cy = tube * Math.sin(v);
  29971. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29972. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29973. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29974. uvs.push(i / radialSegments);
  29975. uvs.push(j / tubularSegments);
  29976. }
  29977. }
  29978. for (i = 0; i < radialSegments; i++) {
  29979. for (j = 0; j < tubularSegments; j++) {
  29980. var jNext = (j + 1) % tubularSegments;
  29981. var a = i * tubularSegments + j;
  29982. var b = (i + 1) * tubularSegments + j;
  29983. var c = (i + 1) * tubularSegments + jNext;
  29984. var d = i * tubularSegments + jNext;
  29985. indices.push(d);
  29986. indices.push(b);
  29987. indices.push(a);
  29988. indices.push(d);
  29989. indices.push(c);
  29990. indices.push(b);
  29991. }
  29992. }
  29993. // Normals
  29994. VertexData.ComputeNormals(positions, indices, normals);
  29995. // Sides
  29996. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29997. // Result
  29998. var vertexData = new VertexData();
  29999. vertexData.indices = indices;
  30000. vertexData.positions = positions;
  30001. vertexData.normals = normals;
  30002. vertexData.uvs = uvs;
  30003. return vertexData;
  30004. };
  30005. // Tools
  30006. /**
  30007. * @param {any} - positions (number[] or Float32Array)
  30008. * @param {any} - indices (number[] or Uint16Array)
  30009. * @param {any} - normals (number[] or Float32Array)
  30010. * options (optional) :
  30011. * facetPositions : optional array of facet positions (vector3)
  30012. * facetNormals : optional array of facet normals (vector3)
  30013. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30014. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30015. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30016. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30017. * bInfo : optional bounding info, required for facetPartitioning computation
  30018. */
  30019. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30020. // temporary scalar variables
  30021. var index = 0; // facet index
  30022. var p1p2x = 0.0; // p1p2 vector x coordinate
  30023. var p1p2y = 0.0; // p1p2 vector y coordinate
  30024. var p1p2z = 0.0; // p1p2 vector z coordinate
  30025. var p3p2x = 0.0; // p3p2 vector x coordinate
  30026. var p3p2y = 0.0; // p3p2 vector y coordinate
  30027. var p3p2z = 0.0; // p3p2 vector z coordinate
  30028. var faceNormalx = 0.0; // facet normal x coordinate
  30029. var faceNormaly = 0.0; // facet normal y coordinate
  30030. var faceNormalz = 0.0; // facet normal z coordinate
  30031. var length = 0.0; // facet normal length before normalization
  30032. var v1x = 0; // vector1 x index in the positions array
  30033. var v1y = 0; // vector1 y index in the positions array
  30034. var v1z = 0; // vector1 z index in the positions array
  30035. var v2x = 0; // vector2 x index in the positions array
  30036. var v2y = 0; // vector2 y index in the positions array
  30037. var v2z = 0; // vector2 z index in the positions array
  30038. var v3x = 0; // vector3 x index in the positions array
  30039. var v3y = 0; // vector3 y index in the positions array
  30040. var v3z = 0; // vector3 z index in the positions array
  30041. var computeFacetNormals = false;
  30042. var computeFacetPositions = false;
  30043. var computeFacetPartitioning = false;
  30044. var faceNormalSign = 1;
  30045. var ratio = 0;
  30046. if (options) {
  30047. computeFacetNormals = (options.facetNormals) ? true : false;
  30048. computeFacetPositions = (options.facetPositions) ? true : false;
  30049. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30050. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30051. ratio = options.ratio || 0;
  30052. }
  30053. // facetPartitioning reinit if needed
  30054. var xSubRatio = 0;
  30055. var ySubRatio = 0;
  30056. var zSubRatio = 0;
  30057. var subSq = 0;
  30058. if (computeFacetPartitioning && options && options.bbSize) {
  30059. var ox = 0; // X partitioning index for facet position
  30060. var oy = 0; // Y partinioning index for facet position
  30061. var oz = 0; // Z partinioning index for facet position
  30062. var b1x = 0; // X partitioning index for facet v1 vertex
  30063. var b1y = 0; // Y partitioning index for facet v1 vertex
  30064. var b1z = 0; // z partitioning index for facet v1 vertex
  30065. var b2x = 0; // X partitioning index for facet v2 vertex
  30066. var b2y = 0; // Y partitioning index for facet v2 vertex
  30067. var b2z = 0; // Z partitioning index for facet v2 vertex
  30068. var b3x = 0; // X partitioning index for facet v3 vertex
  30069. var b3y = 0; // Y partitioning index for facet v3 vertex
  30070. var b3z = 0; // Z partitioning index for facet v3 vertex
  30071. var block_idx_o = 0; // facet barycenter block index
  30072. var block_idx_v1 = 0; // v1 vertex block index
  30073. var block_idx_v2 = 0; // v2 vertex block index
  30074. var block_idx_v3 = 0; // v3 vertex block index
  30075. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30076. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30077. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30078. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30079. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30080. subSq = options.subDiv.max * options.subDiv.max;
  30081. options.facetPartitioning.length = 0;
  30082. }
  30083. // reset the normals
  30084. for (index = 0; index < positions.length; index++) {
  30085. normals[index] = 0.0;
  30086. }
  30087. // Loop : 1 indice triplet = 1 facet
  30088. var nbFaces = indices.length / 3;
  30089. for (index = 0; index < nbFaces; index++) {
  30090. // get the indexes of the coordinates of each vertex of the facet
  30091. v1x = indices[index * 3] * 3;
  30092. v1y = v1x + 1;
  30093. v1z = v1x + 2;
  30094. v2x = indices[index * 3 + 1] * 3;
  30095. v2y = v2x + 1;
  30096. v2z = v2x + 2;
  30097. v3x = indices[index * 3 + 2] * 3;
  30098. v3y = v3x + 1;
  30099. v3z = v3x + 2;
  30100. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30101. p1p2y = positions[v1y] - positions[v2y];
  30102. p1p2z = positions[v1z] - positions[v2z];
  30103. p3p2x = positions[v3x] - positions[v2x];
  30104. p3p2y = positions[v3y] - positions[v2y];
  30105. p3p2z = positions[v3z] - positions[v2z];
  30106. // compute the face normal with the cross product
  30107. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30108. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30109. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30110. // normalize this normal and store it in the array facetData
  30111. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30112. length = (length === 0) ? 1.0 : length;
  30113. faceNormalx /= length;
  30114. faceNormaly /= length;
  30115. faceNormalz /= length;
  30116. if (computeFacetNormals && options) {
  30117. options.facetNormals[index].x = faceNormalx;
  30118. options.facetNormals[index].y = faceNormaly;
  30119. options.facetNormals[index].z = faceNormalz;
  30120. }
  30121. if (computeFacetPositions && options) {
  30122. // compute and the facet barycenter coordinates in the array facetPositions
  30123. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30124. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30125. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30126. }
  30127. if (computeFacetPartitioning && options) {
  30128. // store the facet indexes in arrays in the main facetPartitioning array :
  30129. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30130. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30131. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30132. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30133. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30134. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30135. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30136. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30137. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30138. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30139. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30140. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30141. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30142. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30143. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30144. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30145. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30146. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30147. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30148. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30149. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30150. // push each facet index in each block containing the vertex
  30151. options.facetPartitioning[block_idx_v1].push(index);
  30152. if (block_idx_v2 != block_idx_v1) {
  30153. options.facetPartitioning[block_idx_v2].push(index);
  30154. }
  30155. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30156. options.facetPartitioning[block_idx_v3].push(index);
  30157. }
  30158. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30159. options.facetPartitioning[block_idx_o].push(index);
  30160. }
  30161. }
  30162. // compute the normals anyway
  30163. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30164. normals[v1y] += faceNormaly;
  30165. normals[v1z] += faceNormalz;
  30166. normals[v2x] += faceNormalx;
  30167. normals[v2y] += faceNormaly;
  30168. normals[v2z] += faceNormalz;
  30169. normals[v3x] += faceNormalx;
  30170. normals[v3y] += faceNormaly;
  30171. normals[v3z] += faceNormalz;
  30172. }
  30173. // last normalization of each normal
  30174. for (index = 0; index < normals.length / 3; index++) {
  30175. faceNormalx = normals[index * 3];
  30176. faceNormaly = normals[index * 3 + 1];
  30177. faceNormalz = normals[index * 3 + 2];
  30178. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30179. length = (length === 0) ? 1.0 : length;
  30180. faceNormalx /= length;
  30181. faceNormaly /= length;
  30182. faceNormalz /= length;
  30183. normals[index * 3] = faceNormalx;
  30184. normals[index * 3 + 1] = faceNormaly;
  30185. normals[index * 3 + 2] = faceNormalz;
  30186. }
  30187. };
  30188. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30189. var li = indices.length;
  30190. var ln = normals.length;
  30191. var i;
  30192. var n;
  30193. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30194. switch (sideOrientation) {
  30195. case BABYLON.Mesh.FRONTSIDE:
  30196. // nothing changed
  30197. break;
  30198. case BABYLON.Mesh.BACKSIDE:
  30199. var tmp;
  30200. // indices
  30201. for (i = 0; i < li; i += 3) {
  30202. tmp = indices[i];
  30203. indices[i] = indices[i + 2];
  30204. indices[i + 2] = tmp;
  30205. }
  30206. // normals
  30207. for (n = 0; n < ln; n++) {
  30208. normals[n] = -normals[n];
  30209. }
  30210. break;
  30211. case BABYLON.Mesh.DOUBLESIDE:
  30212. // positions
  30213. var lp = positions.length;
  30214. var l = lp / 3;
  30215. for (var p = 0; p < lp; p++) {
  30216. positions[lp + p] = positions[p];
  30217. }
  30218. // indices
  30219. for (i = 0; i < li; i += 3) {
  30220. indices[i + li] = indices[i + 2] + l;
  30221. indices[i + 1 + li] = indices[i + 1] + l;
  30222. indices[i + 2 + li] = indices[i] + l;
  30223. }
  30224. // normals
  30225. for (n = 0; n < ln; n++) {
  30226. normals[ln + n] = -normals[n];
  30227. }
  30228. // uvs
  30229. var lu = uvs.length;
  30230. var u = 0;
  30231. for (u = 0; u < lu; u++) {
  30232. uvs[u + lu] = uvs[u];
  30233. }
  30234. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30235. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30236. u = 0;
  30237. for (i = 0; i < lu / 2; i++) {
  30238. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30239. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30240. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30241. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30242. u += 2;
  30243. }
  30244. break;
  30245. }
  30246. };
  30247. /**
  30248. * Creates a new VertexData from the imported parameters.
  30249. */
  30250. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30251. var vertexData = new VertexData();
  30252. // positions
  30253. var positions = parsedVertexData.positions;
  30254. if (positions) {
  30255. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30256. }
  30257. // normals
  30258. var normals = parsedVertexData.normals;
  30259. if (normals) {
  30260. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30261. }
  30262. // tangents
  30263. var tangents = parsedVertexData.tangents;
  30264. if (tangents) {
  30265. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30266. }
  30267. // uvs
  30268. var uvs = parsedVertexData.uvs;
  30269. if (uvs) {
  30270. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30271. }
  30272. // uv2s
  30273. var uv2s = parsedVertexData.uv2s;
  30274. if (uv2s) {
  30275. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30276. }
  30277. // uv3s
  30278. var uv3s = parsedVertexData.uv3s;
  30279. if (uv3s) {
  30280. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30281. }
  30282. // uv4s
  30283. var uv4s = parsedVertexData.uv4s;
  30284. if (uv4s) {
  30285. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30286. }
  30287. // uv5s
  30288. var uv5s = parsedVertexData.uv5s;
  30289. if (uv5s) {
  30290. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30291. }
  30292. // uv6s
  30293. var uv6s = parsedVertexData.uv6s;
  30294. if (uv6s) {
  30295. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30296. }
  30297. // colors
  30298. var colors = parsedVertexData.colors;
  30299. if (colors) {
  30300. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30301. }
  30302. // matricesIndices
  30303. var matricesIndices = parsedVertexData.matricesIndices;
  30304. if (matricesIndices) {
  30305. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30306. }
  30307. // matricesWeights
  30308. var matricesWeights = parsedVertexData.matricesWeights;
  30309. if (matricesWeights) {
  30310. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30311. }
  30312. // indices
  30313. var indices = parsedVertexData.indices;
  30314. if (indices) {
  30315. vertexData.indices = indices;
  30316. }
  30317. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30318. };
  30319. return VertexData;
  30320. }());
  30321. BABYLON.VertexData = VertexData;
  30322. })(BABYLON || (BABYLON = {}));
  30323. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30324. var BABYLON;
  30325. (function (BABYLON) {
  30326. var Geometry = /** @class */ (function () {
  30327. function Geometry(id, scene, vertexData, updatable, mesh) {
  30328. if (updatable === void 0) { updatable = false; }
  30329. if (mesh === void 0) { mesh = null; }
  30330. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30331. this._totalVertices = 0;
  30332. this._isDisposed = false;
  30333. this._indexBufferIsUpdatable = false;
  30334. this.id = id;
  30335. this._engine = scene.getEngine();
  30336. this._meshes = [];
  30337. this._scene = scene;
  30338. //Init vertex buffer cache
  30339. this._vertexBuffers = {};
  30340. this._indices = [];
  30341. this._updatable = updatable;
  30342. // vertexData
  30343. if (vertexData) {
  30344. this.setAllVerticesData(vertexData, updatable);
  30345. }
  30346. else {
  30347. this._totalVertices = 0;
  30348. this._indices = [];
  30349. }
  30350. if (this._engine.getCaps().vertexArrayObject) {
  30351. this._vertexArrayObjects = {};
  30352. }
  30353. // applyToMesh
  30354. if (mesh) {
  30355. if (mesh.getClassName() === "LinesMesh") {
  30356. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30357. this.updateExtend();
  30358. }
  30359. this.applyToMesh(mesh);
  30360. mesh.computeWorldMatrix(true);
  30361. }
  30362. }
  30363. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30364. /**
  30365. * 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
  30366. * @returns The Bias Vector
  30367. */
  30368. get: function () {
  30369. return this._boundingBias;
  30370. },
  30371. set: function (value) {
  30372. if (this._boundingBias && this._boundingBias.equals(value)) {
  30373. return;
  30374. }
  30375. this._boundingBias = value.clone();
  30376. this.updateBoundingInfo(true, null);
  30377. },
  30378. enumerable: true,
  30379. configurable: true
  30380. });
  30381. Geometry.CreateGeometryForMesh = function (mesh) {
  30382. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30383. geometry.applyToMesh(mesh);
  30384. return geometry;
  30385. };
  30386. Object.defineProperty(Geometry.prototype, "extend", {
  30387. get: function () {
  30388. return this._extend;
  30389. },
  30390. enumerable: true,
  30391. configurable: true
  30392. });
  30393. Geometry.prototype.getScene = function () {
  30394. return this._scene;
  30395. };
  30396. Geometry.prototype.getEngine = function () {
  30397. return this._engine;
  30398. };
  30399. Geometry.prototype.isReady = function () {
  30400. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30401. };
  30402. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30403. get: function () {
  30404. for (var index = 0; index < this._meshes.length; index++) {
  30405. if (!this._meshes[index].doNotSerialize) {
  30406. return false;
  30407. }
  30408. }
  30409. return true;
  30410. },
  30411. enumerable: true,
  30412. configurable: true
  30413. });
  30414. Geometry.prototype._rebuild = function () {
  30415. if (this._vertexArrayObjects) {
  30416. this._vertexArrayObjects = {};
  30417. }
  30418. // Index buffer
  30419. if (this._meshes.length !== 0 && this._indices) {
  30420. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30421. }
  30422. // Vertex buffers
  30423. for (var key in this._vertexBuffers) {
  30424. var vertexBuffer = this._vertexBuffers[key];
  30425. vertexBuffer._rebuild();
  30426. }
  30427. };
  30428. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30429. vertexData.applyToGeometry(this, updatable);
  30430. this.notifyUpdate();
  30431. };
  30432. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30433. if (updatable === void 0) { updatable = false; }
  30434. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30435. this.setVerticesBuffer(buffer);
  30436. };
  30437. Geometry.prototype.removeVerticesData = function (kind) {
  30438. if (this._vertexBuffers[kind]) {
  30439. this._vertexBuffers[kind].dispose();
  30440. delete this._vertexBuffers[kind];
  30441. }
  30442. };
  30443. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30444. var kind = buffer.getKind();
  30445. if (this._vertexBuffers[kind]) {
  30446. this._vertexBuffers[kind].dispose();
  30447. }
  30448. this._vertexBuffers[kind] = buffer;
  30449. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30450. var data = buffer.getData();
  30451. var stride = buffer.getStrideSize();
  30452. this._totalVertices = data.length / stride;
  30453. this.updateExtend(data, stride);
  30454. this._resetPointsArrayCache();
  30455. var meshes = this._meshes;
  30456. var numOfMeshes = meshes.length;
  30457. for (var index = 0; index < numOfMeshes; index++) {
  30458. var mesh = meshes[index];
  30459. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30460. mesh._createGlobalSubMesh(false);
  30461. mesh.computeWorldMatrix(true);
  30462. }
  30463. }
  30464. this.notifyUpdate(kind);
  30465. if (this._vertexArrayObjects) {
  30466. this._disposeVertexArrayObjects();
  30467. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30468. }
  30469. };
  30470. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30471. var vertexBuffer = this.getVertexBuffer(kind);
  30472. if (!vertexBuffer) {
  30473. return;
  30474. }
  30475. vertexBuffer.updateDirectly(data, offset);
  30476. this.notifyUpdate(kind);
  30477. };
  30478. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30479. if (updateExtends === void 0) { updateExtends = false; }
  30480. var vertexBuffer = this.getVertexBuffer(kind);
  30481. if (!vertexBuffer) {
  30482. return;
  30483. }
  30484. vertexBuffer.update(data);
  30485. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30486. var stride = vertexBuffer.getStrideSize();
  30487. this._totalVertices = data.length / stride;
  30488. this.updateBoundingInfo(updateExtends, data);
  30489. }
  30490. this.notifyUpdate(kind);
  30491. };
  30492. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30493. if (updateExtends) {
  30494. this.updateExtend(data);
  30495. }
  30496. var meshes = this._meshes;
  30497. var numOfMeshes = meshes.length;
  30498. this._resetPointsArrayCache();
  30499. for (var index = 0; index < numOfMeshes; index++) {
  30500. var mesh = meshes[index];
  30501. if (updateExtends) {
  30502. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30503. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30504. var subMesh = mesh.subMeshes[subIndex];
  30505. subMesh.refreshBoundingInfo();
  30506. }
  30507. }
  30508. }
  30509. };
  30510. Geometry.prototype._bind = function (effect, indexToBind) {
  30511. if (!effect) {
  30512. return;
  30513. }
  30514. if (indexToBind === undefined) {
  30515. indexToBind = this._indexBuffer;
  30516. }
  30517. var vbs = this.getVertexBuffers();
  30518. if (!vbs) {
  30519. return;
  30520. }
  30521. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30522. this._engine.bindBuffers(vbs, indexToBind, effect);
  30523. return;
  30524. }
  30525. // Using VAO
  30526. if (!this._vertexArrayObjects[effect.key]) {
  30527. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30528. }
  30529. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30530. };
  30531. Geometry.prototype.getTotalVertices = function () {
  30532. if (!this.isReady()) {
  30533. return 0;
  30534. }
  30535. return this._totalVertices;
  30536. };
  30537. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30538. var vertexBuffer = this.getVertexBuffer(kind);
  30539. if (!vertexBuffer) {
  30540. return null;
  30541. }
  30542. var orig = vertexBuffer.getData();
  30543. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30544. return orig;
  30545. }
  30546. else {
  30547. var len = orig.length;
  30548. var copy = [];
  30549. for (var i = 0; i < len; i++) {
  30550. copy.push(orig[i]);
  30551. }
  30552. return copy;
  30553. }
  30554. };
  30555. /**
  30556. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30557. * Possible `kind` values :
  30558. * - BABYLON.VertexBuffer.PositionKind
  30559. * - BABYLON.VertexBuffer.UVKind
  30560. * - BABYLON.VertexBuffer.UV2Kind
  30561. * - BABYLON.VertexBuffer.UV3Kind
  30562. * - BABYLON.VertexBuffer.UV4Kind
  30563. * - BABYLON.VertexBuffer.UV5Kind
  30564. * - BABYLON.VertexBuffer.UV6Kind
  30565. * - BABYLON.VertexBuffer.ColorKind
  30566. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30567. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30568. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30569. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30570. */
  30571. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  30572. var vb = this._vertexBuffers[kind];
  30573. if (!vb) {
  30574. return false;
  30575. }
  30576. return vb.isUpdatable();
  30577. };
  30578. Geometry.prototype.getVertexBuffer = function (kind) {
  30579. if (!this.isReady()) {
  30580. return null;
  30581. }
  30582. return this._vertexBuffers[kind];
  30583. };
  30584. Geometry.prototype.getVertexBuffers = function () {
  30585. if (!this.isReady()) {
  30586. return null;
  30587. }
  30588. return this._vertexBuffers;
  30589. };
  30590. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30591. if (!this._vertexBuffers) {
  30592. if (this._delayInfo) {
  30593. return this._delayInfo.indexOf(kind) !== -1;
  30594. }
  30595. return false;
  30596. }
  30597. return this._vertexBuffers[kind] !== undefined;
  30598. };
  30599. Geometry.prototype.getVerticesDataKinds = function () {
  30600. var result = [];
  30601. var kind;
  30602. if (!this._vertexBuffers && this._delayInfo) {
  30603. for (kind in this._delayInfo) {
  30604. result.push(kind);
  30605. }
  30606. }
  30607. else {
  30608. for (kind in this._vertexBuffers) {
  30609. result.push(kind);
  30610. }
  30611. }
  30612. return result;
  30613. };
  30614. Geometry.prototype.updateIndices = function (indices, offset) {
  30615. if (!this._indexBuffer) {
  30616. return;
  30617. }
  30618. if (!this._indexBufferIsUpdatable) {
  30619. this.setIndices(indices, null, true);
  30620. }
  30621. else {
  30622. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  30623. }
  30624. };
  30625. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  30626. if (totalVertices === void 0) { totalVertices = null; }
  30627. if (updatable === void 0) { updatable = false; }
  30628. if (this._indexBuffer) {
  30629. this._engine._releaseBuffer(this._indexBuffer);
  30630. }
  30631. this._disposeVertexArrayObjects();
  30632. this._indices = indices;
  30633. this._indexBufferIsUpdatable = updatable;
  30634. if (this._meshes.length !== 0 && this._indices) {
  30635. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  30636. }
  30637. if (totalVertices != undefined) {
  30638. this._totalVertices = totalVertices;
  30639. }
  30640. var meshes = this._meshes;
  30641. var numOfMeshes = meshes.length;
  30642. for (var index = 0; index < numOfMeshes; index++) {
  30643. meshes[index]._createGlobalSubMesh(true);
  30644. }
  30645. this.notifyUpdate();
  30646. };
  30647. Geometry.prototype.getTotalIndices = function () {
  30648. if (!this.isReady()) {
  30649. return 0;
  30650. }
  30651. return this._indices.length;
  30652. };
  30653. Geometry.prototype.getIndices = function (copyWhenShared) {
  30654. if (!this.isReady()) {
  30655. return null;
  30656. }
  30657. var orig = this._indices;
  30658. if (!copyWhenShared || this._meshes.length === 1) {
  30659. return orig;
  30660. }
  30661. else {
  30662. var len = orig.length;
  30663. var copy = [];
  30664. for (var i = 0; i < len; i++) {
  30665. copy.push(orig[i]);
  30666. }
  30667. return copy;
  30668. }
  30669. };
  30670. Geometry.prototype.getIndexBuffer = function () {
  30671. if (!this.isReady()) {
  30672. return null;
  30673. }
  30674. return this._indexBuffer;
  30675. };
  30676. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  30677. if (effect === void 0) { effect = null; }
  30678. if (!effect || !this._vertexArrayObjects) {
  30679. return;
  30680. }
  30681. if (this._vertexArrayObjects[effect.key]) {
  30682. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  30683. delete this._vertexArrayObjects[effect.key];
  30684. }
  30685. };
  30686. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30687. var meshes = this._meshes;
  30688. var index = meshes.indexOf(mesh);
  30689. if (index === -1) {
  30690. return;
  30691. }
  30692. meshes.splice(index, 1);
  30693. mesh._geometry = null;
  30694. if (meshes.length === 0 && shouldDispose) {
  30695. this.dispose();
  30696. }
  30697. };
  30698. Geometry.prototype.applyToMesh = function (mesh) {
  30699. if (mesh._geometry === this) {
  30700. return;
  30701. }
  30702. var previousGeometry = mesh._geometry;
  30703. if (previousGeometry) {
  30704. previousGeometry.releaseForMesh(mesh);
  30705. }
  30706. var meshes = this._meshes;
  30707. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30708. mesh._geometry = this;
  30709. this._scene.pushGeometry(this);
  30710. meshes.push(mesh);
  30711. if (this.isReady()) {
  30712. this._applyToMesh(mesh);
  30713. }
  30714. else {
  30715. mesh._boundingInfo = this._boundingInfo;
  30716. }
  30717. };
  30718. Geometry.prototype.updateExtend = function (data, stride) {
  30719. if (data === void 0) { data = null; }
  30720. if (!data) {
  30721. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30722. }
  30723. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  30724. };
  30725. Geometry.prototype._applyToMesh = function (mesh) {
  30726. var numOfMeshes = this._meshes.length;
  30727. // vertexBuffers
  30728. for (var kind in this._vertexBuffers) {
  30729. if (numOfMeshes === 1) {
  30730. this._vertexBuffers[kind].create();
  30731. }
  30732. var buffer = this._vertexBuffers[kind].getBuffer();
  30733. if (buffer)
  30734. buffer.references = numOfMeshes;
  30735. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30736. if (!this._extend) {
  30737. this.updateExtend(this._vertexBuffers[kind].getData());
  30738. }
  30739. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30740. mesh._createGlobalSubMesh(false);
  30741. //bounding info was just created again, world matrix should be applied again.
  30742. mesh._updateBoundingInfo();
  30743. }
  30744. }
  30745. // indexBuffer
  30746. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30747. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30748. }
  30749. if (this._indexBuffer) {
  30750. this._indexBuffer.references = numOfMeshes;
  30751. }
  30752. };
  30753. Geometry.prototype.notifyUpdate = function (kind) {
  30754. if (this.onGeometryUpdated) {
  30755. this.onGeometryUpdated(this, kind);
  30756. }
  30757. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30758. var mesh = _a[_i];
  30759. mesh._markSubMeshesAsAttributesDirty();
  30760. }
  30761. };
  30762. Geometry.prototype.load = function (scene, onLoaded) {
  30763. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30764. return;
  30765. }
  30766. if (this.isReady()) {
  30767. if (onLoaded) {
  30768. onLoaded();
  30769. }
  30770. return;
  30771. }
  30772. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30773. this._queueLoad(scene, onLoaded);
  30774. };
  30775. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30776. var _this = this;
  30777. if (!this.delayLoadingFile) {
  30778. return;
  30779. }
  30780. scene._addPendingData(this);
  30781. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30782. if (!_this._delayLoadingFunction) {
  30783. return;
  30784. }
  30785. _this._delayLoadingFunction(JSON.parse(data), _this);
  30786. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30787. _this._delayInfo = [];
  30788. scene._removePendingData(_this);
  30789. var meshes = _this._meshes;
  30790. var numOfMeshes = meshes.length;
  30791. for (var index = 0; index < numOfMeshes; index++) {
  30792. _this._applyToMesh(meshes[index]);
  30793. }
  30794. if (onLoaded) {
  30795. onLoaded();
  30796. }
  30797. }, function () { }, scene.database);
  30798. };
  30799. /**
  30800. * Invert the geometry to move from a right handed system to a left handed one.
  30801. */
  30802. Geometry.prototype.toLeftHanded = function () {
  30803. // Flip faces
  30804. var tIndices = this.getIndices(false);
  30805. if (tIndices != null && tIndices.length > 0) {
  30806. for (var i = 0; i < tIndices.length; i += 3) {
  30807. var tTemp = tIndices[i + 0];
  30808. tIndices[i + 0] = tIndices[i + 2];
  30809. tIndices[i + 2] = tTemp;
  30810. }
  30811. this.setIndices(tIndices);
  30812. }
  30813. // Negate position.z
  30814. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30815. if (tPositions != null && tPositions.length > 0) {
  30816. for (var i = 0; i < tPositions.length; i += 3) {
  30817. tPositions[i + 2] = -tPositions[i + 2];
  30818. }
  30819. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30820. }
  30821. // Negate normal.z
  30822. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30823. if (tNormals != null && tNormals.length > 0) {
  30824. for (var i = 0; i < tNormals.length; i += 3) {
  30825. tNormals[i + 2] = -tNormals[i + 2];
  30826. }
  30827. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30828. }
  30829. };
  30830. // Cache
  30831. Geometry.prototype._resetPointsArrayCache = function () {
  30832. this._positions = null;
  30833. };
  30834. Geometry.prototype._generatePointsArray = function () {
  30835. if (this._positions)
  30836. return true;
  30837. this._positions = [];
  30838. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30839. if (!data) {
  30840. return false;
  30841. }
  30842. for (var index = 0; index < data.length; index += 3) {
  30843. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30844. }
  30845. return true;
  30846. };
  30847. Geometry.prototype.isDisposed = function () {
  30848. return this._isDisposed;
  30849. };
  30850. Geometry.prototype._disposeVertexArrayObjects = function () {
  30851. if (this._vertexArrayObjects) {
  30852. for (var kind in this._vertexArrayObjects) {
  30853. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30854. }
  30855. this._vertexArrayObjects = {};
  30856. }
  30857. };
  30858. Geometry.prototype.dispose = function () {
  30859. var meshes = this._meshes;
  30860. var numOfMeshes = meshes.length;
  30861. var index;
  30862. for (index = 0; index < numOfMeshes; index++) {
  30863. this.releaseForMesh(meshes[index]);
  30864. }
  30865. this._meshes = [];
  30866. this._disposeVertexArrayObjects();
  30867. for (var kind in this._vertexBuffers) {
  30868. this._vertexBuffers[kind].dispose();
  30869. }
  30870. this._vertexBuffers = {};
  30871. this._totalVertices = 0;
  30872. if (this._indexBuffer) {
  30873. this._engine._releaseBuffer(this._indexBuffer);
  30874. }
  30875. this._indexBuffer = null;
  30876. this._indices = [];
  30877. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30878. this.delayLoadingFile = null;
  30879. this._delayLoadingFunction = null;
  30880. this._delayInfo = [];
  30881. this._boundingInfo = null;
  30882. this._scene.removeGeometry(this);
  30883. this._isDisposed = true;
  30884. };
  30885. Geometry.prototype.copy = function (id) {
  30886. var vertexData = new BABYLON.VertexData();
  30887. vertexData.indices = [];
  30888. var indices = this.getIndices();
  30889. if (indices) {
  30890. for (var index = 0; index < indices.length; index++) {
  30891. vertexData.indices.push(indices[index]);
  30892. }
  30893. }
  30894. var updatable = false;
  30895. var stopChecking = false;
  30896. var kind;
  30897. for (kind in this._vertexBuffers) {
  30898. // using slice() to make a copy of the array and not just reference it
  30899. var data = this.getVerticesData(kind);
  30900. if (data instanceof Float32Array) {
  30901. vertexData.set(new Float32Array(data), kind);
  30902. }
  30903. else {
  30904. vertexData.set(data.slice(0), kind);
  30905. }
  30906. if (!stopChecking) {
  30907. var vb = this.getVertexBuffer(kind);
  30908. if (vb) {
  30909. updatable = vb.isUpdatable();
  30910. stopChecking = !updatable;
  30911. }
  30912. }
  30913. }
  30914. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  30915. geometry.delayLoadState = this.delayLoadState;
  30916. geometry.delayLoadingFile = this.delayLoadingFile;
  30917. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30918. for (kind in this._delayInfo) {
  30919. geometry._delayInfo = geometry._delayInfo || [];
  30920. geometry._delayInfo.push(kind);
  30921. }
  30922. // Bounding info
  30923. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30924. return geometry;
  30925. };
  30926. Geometry.prototype.serialize = function () {
  30927. var serializationObject = {};
  30928. serializationObject.id = this.id;
  30929. serializationObject.updatable = this._updatable;
  30930. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30931. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30932. }
  30933. return serializationObject;
  30934. };
  30935. Geometry.prototype.toNumberArray = function (origin) {
  30936. if (Array.isArray(origin)) {
  30937. return origin;
  30938. }
  30939. else {
  30940. return Array.prototype.slice.call(origin);
  30941. }
  30942. };
  30943. Geometry.prototype.serializeVerticeData = function () {
  30944. var serializationObject = this.serialize();
  30945. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30946. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  30947. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30948. serializationObject.positions._updatable = true;
  30949. }
  30950. }
  30951. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30952. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  30953. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30954. serializationObject.normals._updatable = true;
  30955. }
  30956. }
  30957. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30958. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  30959. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  30960. serializationObject.uvs._updatable = true;
  30961. }
  30962. }
  30963. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30964. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  30965. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  30966. serializationObject.uv2s._updatable = true;
  30967. }
  30968. }
  30969. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30970. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  30971. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  30972. serializationObject.uv3s._updatable = true;
  30973. }
  30974. }
  30975. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30976. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  30977. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  30978. serializationObject.uv4s._updatable = true;
  30979. }
  30980. }
  30981. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30982. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  30983. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  30984. serializationObject.uv5s._updatable = true;
  30985. }
  30986. }
  30987. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30988. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  30989. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  30990. serializationObject.uv6s._updatable = true;
  30991. }
  30992. }
  30993. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30994. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  30995. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  30996. serializationObject.colors._updatable = true;
  30997. }
  30998. }
  30999. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31000. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31001. serializationObject.matricesIndices._isExpanded = true;
  31002. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31003. serializationObject.matricesIndices._updatable = true;
  31004. }
  31005. }
  31006. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31007. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31008. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31009. serializationObject.matricesWeights._updatable = true;
  31010. }
  31011. }
  31012. serializationObject.indices = this.toNumberArray(this.getIndices());
  31013. return serializationObject;
  31014. };
  31015. // Statics
  31016. Geometry.ExtractFromMesh = function (mesh, id) {
  31017. var geometry = mesh._geometry;
  31018. if (!geometry) {
  31019. return null;
  31020. }
  31021. return geometry.copy(id);
  31022. };
  31023. /**
  31024. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31025. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31026. * Be aware Math.random() could cause collisions, but:
  31027. * "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"
  31028. */
  31029. Geometry.RandomId = function () {
  31030. return BABYLON.Tools.RandomId();
  31031. };
  31032. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31033. var scene = mesh.getScene();
  31034. // Geometry
  31035. var geometryId = parsedGeometry.geometryId;
  31036. if (geometryId) {
  31037. var geometry = scene.getGeometryByID(geometryId);
  31038. if (geometry) {
  31039. geometry.applyToMesh(mesh);
  31040. }
  31041. }
  31042. else if (parsedGeometry instanceof ArrayBuffer) {
  31043. var binaryInfo = mesh._binaryInfo;
  31044. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31045. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31046. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31047. }
  31048. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31049. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31050. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31051. }
  31052. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31053. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31054. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31055. }
  31056. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31057. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31058. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31059. }
  31060. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31061. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31062. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31063. }
  31064. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31065. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31066. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31067. }
  31068. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31069. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31070. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31071. }
  31072. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31073. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31074. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31075. }
  31076. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31077. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31078. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31079. }
  31080. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31081. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31082. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31083. }
  31084. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31085. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31086. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31087. }
  31088. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31089. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31090. mesh.setIndices(indicesData, null);
  31091. }
  31092. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31093. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31094. mesh.subMeshes = [];
  31095. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31096. var materialIndex = subMeshesData[(i * 5) + 0];
  31097. var verticesStart = subMeshesData[(i * 5) + 1];
  31098. var verticesCount = subMeshesData[(i * 5) + 2];
  31099. var indexStart = subMeshesData[(i * 5) + 3];
  31100. var indexCount = subMeshesData[(i * 5) + 4];
  31101. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31102. }
  31103. }
  31104. }
  31105. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31106. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31107. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31108. if (parsedGeometry.uvs) {
  31109. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31110. }
  31111. if (parsedGeometry.uvs2) {
  31112. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31113. }
  31114. if (parsedGeometry.uvs3) {
  31115. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31116. }
  31117. if (parsedGeometry.uvs4) {
  31118. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31119. }
  31120. if (parsedGeometry.uvs5) {
  31121. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31122. }
  31123. if (parsedGeometry.uvs6) {
  31124. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31125. }
  31126. if (parsedGeometry.colors) {
  31127. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31128. }
  31129. if (parsedGeometry.matricesIndices) {
  31130. if (!parsedGeometry.matricesIndices._isExpanded) {
  31131. var floatIndices = [];
  31132. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31133. var matricesIndex = parsedGeometry.matricesIndices[i];
  31134. floatIndices.push(matricesIndex & 0x000000FF);
  31135. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31136. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31137. floatIndices.push(matricesIndex >> 24);
  31138. }
  31139. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31140. }
  31141. else {
  31142. delete parsedGeometry.matricesIndices._isExpanded;
  31143. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31144. }
  31145. }
  31146. if (parsedGeometry.matricesIndicesExtra) {
  31147. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31148. var floatIndices = [];
  31149. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31150. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31151. floatIndices.push(matricesIndex & 0x000000FF);
  31152. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31153. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31154. floatIndices.push(matricesIndex >> 24);
  31155. }
  31156. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31157. }
  31158. else {
  31159. delete parsedGeometry.matricesIndices._isExpanded;
  31160. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31161. }
  31162. }
  31163. if (parsedGeometry.matricesWeights) {
  31164. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31165. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31166. }
  31167. if (parsedGeometry.matricesWeightsExtra) {
  31168. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31169. }
  31170. mesh.setIndices(parsedGeometry.indices, null);
  31171. }
  31172. // SubMeshes
  31173. if (parsedGeometry.subMeshes) {
  31174. mesh.subMeshes = [];
  31175. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31176. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31177. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31178. }
  31179. }
  31180. // Flat shading
  31181. if (mesh._shouldGenerateFlatShading) {
  31182. mesh.convertToFlatShadedMesh();
  31183. delete mesh._shouldGenerateFlatShading;
  31184. }
  31185. // Update
  31186. mesh.computeWorldMatrix(true);
  31187. // Octree
  31188. if (scene['_selectionOctree']) {
  31189. scene['_selectionOctree'].addMesh(mesh);
  31190. }
  31191. };
  31192. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31193. var epsilon = 1e-3;
  31194. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31195. return;
  31196. }
  31197. var noInfluenceBoneIndex = 0.0;
  31198. if (parsedGeometry.skeletonId > -1) {
  31199. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31200. if (!skeleton) {
  31201. return;
  31202. }
  31203. noInfluenceBoneIndex = skeleton.bones.length;
  31204. }
  31205. else {
  31206. return;
  31207. }
  31208. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31209. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31210. var matricesWeights = parsedGeometry.matricesWeights;
  31211. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31212. var influencers = parsedGeometry.numBoneInfluencer;
  31213. var size = matricesWeights.length;
  31214. for (var i = 0; i < size; i += 4) {
  31215. var weight = 0.0;
  31216. var firstZeroWeight = -1;
  31217. for (var j = 0; j < 4; j++) {
  31218. var w = matricesWeights[i + j];
  31219. weight += w;
  31220. if (w < epsilon && firstZeroWeight < 0) {
  31221. firstZeroWeight = j;
  31222. }
  31223. }
  31224. if (matricesWeightsExtra) {
  31225. for (var j = 0; j < 4; j++) {
  31226. var w = matricesWeightsExtra[i + j];
  31227. weight += w;
  31228. if (w < epsilon && firstZeroWeight < 0) {
  31229. firstZeroWeight = j + 4;
  31230. }
  31231. }
  31232. }
  31233. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31234. firstZeroWeight = influencers - 1;
  31235. }
  31236. if (weight > epsilon) {
  31237. var mweight = 1.0 / weight;
  31238. for (var j = 0; j < 4; j++) {
  31239. matricesWeights[i + j] *= mweight;
  31240. }
  31241. if (matricesWeightsExtra) {
  31242. for (var j = 0; j < 4; j++) {
  31243. matricesWeightsExtra[i + j] *= mweight;
  31244. }
  31245. }
  31246. }
  31247. else {
  31248. if (firstZeroWeight >= 4) {
  31249. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31250. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31251. }
  31252. else {
  31253. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31254. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31255. }
  31256. }
  31257. }
  31258. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31259. if (parsedGeometry.matricesWeightsExtra) {
  31260. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31261. }
  31262. };
  31263. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31264. if (scene.getGeometryByID(parsedVertexData.id)) {
  31265. return null; // null since geometry could be something else than a box...
  31266. }
  31267. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31268. if (BABYLON.Tags) {
  31269. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31270. }
  31271. if (parsedVertexData.delayLoadingFile) {
  31272. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31273. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31274. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31275. geometry._delayInfo = [];
  31276. if (parsedVertexData.hasUVs) {
  31277. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31278. }
  31279. if (parsedVertexData.hasUVs2) {
  31280. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31281. }
  31282. if (parsedVertexData.hasUVs3) {
  31283. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31284. }
  31285. if (parsedVertexData.hasUVs4) {
  31286. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31287. }
  31288. if (parsedVertexData.hasUVs5) {
  31289. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31290. }
  31291. if (parsedVertexData.hasUVs6) {
  31292. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31293. }
  31294. if (parsedVertexData.hasColors) {
  31295. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31296. }
  31297. if (parsedVertexData.hasMatricesIndices) {
  31298. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31299. }
  31300. if (parsedVertexData.hasMatricesWeights) {
  31301. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31302. }
  31303. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31304. }
  31305. else {
  31306. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31307. }
  31308. scene.pushGeometry(geometry, true);
  31309. return geometry;
  31310. };
  31311. return Geometry;
  31312. }());
  31313. BABYLON.Geometry = Geometry;
  31314. /////// Primitives //////////////////////////////////////////////
  31315. (function (Geometry) {
  31316. var Primitives;
  31317. (function (Primitives) {
  31318. /// Abstract class
  31319. var _Primitive = /** @class */ (function (_super) {
  31320. __extends(_Primitive, _super);
  31321. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31322. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31323. if (mesh === void 0) { mesh = null; }
  31324. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31325. _this._canBeRegenerated = _canBeRegenerated;
  31326. _this._beingRegenerated = true;
  31327. _this.regenerate();
  31328. _this._beingRegenerated = false;
  31329. return _this;
  31330. }
  31331. _Primitive.prototype.canBeRegenerated = function () {
  31332. return this._canBeRegenerated;
  31333. };
  31334. _Primitive.prototype.regenerate = function () {
  31335. if (!this._canBeRegenerated) {
  31336. return;
  31337. }
  31338. this._beingRegenerated = true;
  31339. this.setAllVerticesData(this._regenerateVertexData(), false);
  31340. this._beingRegenerated = false;
  31341. };
  31342. _Primitive.prototype.asNewGeometry = function (id) {
  31343. return _super.prototype.copy.call(this, id);
  31344. };
  31345. // overrides
  31346. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31347. if (!this._beingRegenerated) {
  31348. return;
  31349. }
  31350. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31351. };
  31352. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31353. if (!this._beingRegenerated) {
  31354. return;
  31355. }
  31356. _super.prototype.setVerticesData.call(this, kind, data, false);
  31357. };
  31358. // to override
  31359. // protected
  31360. _Primitive.prototype._regenerateVertexData = function () {
  31361. throw new Error("Abstract method");
  31362. };
  31363. _Primitive.prototype.copy = function (id) {
  31364. throw new Error("Must be overriden in sub-classes.");
  31365. };
  31366. _Primitive.prototype.serialize = function () {
  31367. var serializationObject = _super.prototype.serialize.call(this);
  31368. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31369. return serializationObject;
  31370. };
  31371. return _Primitive;
  31372. }(Geometry));
  31373. Primitives._Primitive = _Primitive;
  31374. var Ribbon = /** @class */ (function (_super) {
  31375. __extends(Ribbon, _super);
  31376. // Members
  31377. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31378. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31379. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31380. _this.pathArray = pathArray;
  31381. _this.closeArray = closeArray;
  31382. _this.closePath = closePath;
  31383. _this.offset = offset;
  31384. _this.side = side;
  31385. return _this;
  31386. }
  31387. Ribbon.prototype._regenerateVertexData = function () {
  31388. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31389. };
  31390. Ribbon.prototype.copy = function (id) {
  31391. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31392. };
  31393. return Ribbon;
  31394. }(_Primitive));
  31395. Primitives.Ribbon = Ribbon;
  31396. var Box = /** @class */ (function (_super) {
  31397. __extends(Box, _super);
  31398. // Members
  31399. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31400. if (mesh === void 0) { mesh = null; }
  31401. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31402. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31403. _this.size = size;
  31404. _this.side = side;
  31405. return _this;
  31406. }
  31407. Box.prototype._regenerateVertexData = function () {
  31408. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31409. };
  31410. Box.prototype.copy = function (id) {
  31411. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31412. };
  31413. Box.prototype.serialize = function () {
  31414. var serializationObject = _super.prototype.serialize.call(this);
  31415. serializationObject.size = this.size;
  31416. return serializationObject;
  31417. };
  31418. Box.Parse = function (parsedBox, scene) {
  31419. if (scene.getGeometryByID(parsedBox.id)) {
  31420. return null; // null since geometry could be something else than a box...
  31421. }
  31422. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31423. if (BABYLON.Tags) {
  31424. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31425. }
  31426. scene.pushGeometry(box, true);
  31427. return box;
  31428. };
  31429. return Box;
  31430. }(_Primitive));
  31431. Primitives.Box = Box;
  31432. var Sphere = /** @class */ (function (_super) {
  31433. __extends(Sphere, _super);
  31434. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31435. if (mesh === void 0) { mesh = null; }
  31436. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31437. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31438. _this.segments = segments;
  31439. _this.diameter = diameter;
  31440. _this.side = side;
  31441. return _this;
  31442. }
  31443. Sphere.prototype._regenerateVertexData = function () {
  31444. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31445. };
  31446. Sphere.prototype.copy = function (id) {
  31447. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31448. };
  31449. Sphere.prototype.serialize = function () {
  31450. var serializationObject = _super.prototype.serialize.call(this);
  31451. serializationObject.segments = this.segments;
  31452. serializationObject.diameter = this.diameter;
  31453. return serializationObject;
  31454. };
  31455. Sphere.Parse = function (parsedSphere, scene) {
  31456. if (scene.getGeometryByID(parsedSphere.id)) {
  31457. return null; // null since geometry could be something else than a sphere...
  31458. }
  31459. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31460. if (BABYLON.Tags) {
  31461. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31462. }
  31463. scene.pushGeometry(sphere, true);
  31464. return sphere;
  31465. };
  31466. return Sphere;
  31467. }(_Primitive));
  31468. Primitives.Sphere = Sphere;
  31469. var Disc = /** @class */ (function (_super) {
  31470. __extends(Disc, _super);
  31471. // Members
  31472. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31473. if (mesh === void 0) { mesh = null; }
  31474. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31475. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31476. _this.radius = radius;
  31477. _this.tessellation = tessellation;
  31478. _this.side = side;
  31479. return _this;
  31480. }
  31481. Disc.prototype._regenerateVertexData = function () {
  31482. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31483. };
  31484. Disc.prototype.copy = function (id) {
  31485. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31486. };
  31487. return Disc;
  31488. }(_Primitive));
  31489. Primitives.Disc = Disc;
  31490. var Cylinder = /** @class */ (function (_super) {
  31491. __extends(Cylinder, _super);
  31492. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31493. if (subdivisions === void 0) { subdivisions = 1; }
  31494. if (mesh === void 0) { mesh = null; }
  31495. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31496. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31497. _this.height = height;
  31498. _this.diameterTop = diameterTop;
  31499. _this.diameterBottom = diameterBottom;
  31500. _this.tessellation = tessellation;
  31501. _this.subdivisions = subdivisions;
  31502. _this.side = side;
  31503. return _this;
  31504. }
  31505. Cylinder.prototype._regenerateVertexData = function () {
  31506. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31507. };
  31508. Cylinder.prototype.copy = function (id) {
  31509. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31510. };
  31511. Cylinder.prototype.serialize = function () {
  31512. var serializationObject = _super.prototype.serialize.call(this);
  31513. serializationObject.height = this.height;
  31514. serializationObject.diameterTop = this.diameterTop;
  31515. serializationObject.diameterBottom = this.diameterBottom;
  31516. serializationObject.tessellation = this.tessellation;
  31517. return serializationObject;
  31518. };
  31519. Cylinder.Parse = function (parsedCylinder, scene) {
  31520. if (scene.getGeometryByID(parsedCylinder.id)) {
  31521. return null; // null since geometry could be something else than a cylinder...
  31522. }
  31523. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31524. if (BABYLON.Tags) {
  31525. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31526. }
  31527. scene.pushGeometry(cylinder, true);
  31528. return cylinder;
  31529. };
  31530. return Cylinder;
  31531. }(_Primitive));
  31532. Primitives.Cylinder = Cylinder;
  31533. var Torus = /** @class */ (function (_super) {
  31534. __extends(Torus, _super);
  31535. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31536. if (mesh === void 0) { mesh = null; }
  31537. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31538. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31539. _this.diameter = diameter;
  31540. _this.thickness = thickness;
  31541. _this.tessellation = tessellation;
  31542. _this.side = side;
  31543. return _this;
  31544. }
  31545. Torus.prototype._regenerateVertexData = function () {
  31546. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31547. };
  31548. Torus.prototype.copy = function (id) {
  31549. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31550. };
  31551. Torus.prototype.serialize = function () {
  31552. var serializationObject = _super.prototype.serialize.call(this);
  31553. serializationObject.diameter = this.diameter;
  31554. serializationObject.thickness = this.thickness;
  31555. serializationObject.tessellation = this.tessellation;
  31556. return serializationObject;
  31557. };
  31558. Torus.Parse = function (parsedTorus, scene) {
  31559. if (scene.getGeometryByID(parsedTorus.id)) {
  31560. return null; // null since geometry could be something else than a torus...
  31561. }
  31562. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31563. if (BABYLON.Tags) {
  31564. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31565. }
  31566. scene.pushGeometry(torus, true);
  31567. return torus;
  31568. };
  31569. return Torus;
  31570. }(_Primitive));
  31571. Primitives.Torus = Torus;
  31572. var Ground = /** @class */ (function (_super) {
  31573. __extends(Ground, _super);
  31574. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31575. if (mesh === void 0) { mesh = null; }
  31576. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31577. _this.width = width;
  31578. _this.height = height;
  31579. _this.subdivisions = subdivisions;
  31580. return _this;
  31581. }
  31582. Ground.prototype._regenerateVertexData = function () {
  31583. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31584. };
  31585. Ground.prototype.copy = function (id) {
  31586. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31587. };
  31588. Ground.prototype.serialize = function () {
  31589. var serializationObject = _super.prototype.serialize.call(this);
  31590. serializationObject.width = this.width;
  31591. serializationObject.height = this.height;
  31592. serializationObject.subdivisions = this.subdivisions;
  31593. return serializationObject;
  31594. };
  31595. Ground.Parse = function (parsedGround, scene) {
  31596. if (scene.getGeometryByID(parsedGround.id)) {
  31597. return null; // null since geometry could be something else than a ground...
  31598. }
  31599. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31600. if (BABYLON.Tags) {
  31601. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31602. }
  31603. scene.pushGeometry(ground, true);
  31604. return ground;
  31605. };
  31606. return Ground;
  31607. }(_Primitive));
  31608. Primitives.Ground = Ground;
  31609. var TiledGround = /** @class */ (function (_super) {
  31610. __extends(TiledGround, _super);
  31611. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31612. if (mesh === void 0) { mesh = null; }
  31613. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31614. _this.xmin = xmin;
  31615. _this.zmin = zmin;
  31616. _this.xmax = xmax;
  31617. _this.zmax = zmax;
  31618. _this.subdivisions = subdivisions;
  31619. _this.precision = precision;
  31620. return _this;
  31621. }
  31622. TiledGround.prototype._regenerateVertexData = function () {
  31623. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31624. };
  31625. TiledGround.prototype.copy = function (id) {
  31626. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31627. };
  31628. return TiledGround;
  31629. }(_Primitive));
  31630. Primitives.TiledGround = TiledGround;
  31631. var Plane = /** @class */ (function (_super) {
  31632. __extends(Plane, _super);
  31633. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31634. if (mesh === void 0) { mesh = null; }
  31635. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31636. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31637. _this.size = size;
  31638. _this.side = side;
  31639. return _this;
  31640. }
  31641. Plane.prototype._regenerateVertexData = function () {
  31642. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31643. };
  31644. Plane.prototype.copy = function (id) {
  31645. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31646. };
  31647. Plane.prototype.serialize = function () {
  31648. var serializationObject = _super.prototype.serialize.call(this);
  31649. serializationObject.size = this.size;
  31650. return serializationObject;
  31651. };
  31652. Plane.Parse = function (parsedPlane, scene) {
  31653. if (scene.getGeometryByID(parsedPlane.id)) {
  31654. return null; // null since geometry could be something else than a ground...
  31655. }
  31656. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31657. if (BABYLON.Tags) {
  31658. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31659. }
  31660. scene.pushGeometry(plane, true);
  31661. return plane;
  31662. };
  31663. return Plane;
  31664. }(_Primitive));
  31665. Primitives.Plane = Plane;
  31666. var TorusKnot = /** @class */ (function (_super) {
  31667. __extends(TorusKnot, _super);
  31668. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31669. if (mesh === void 0) { mesh = null; }
  31670. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31671. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31672. _this.radius = radius;
  31673. _this.tube = tube;
  31674. _this.radialSegments = radialSegments;
  31675. _this.tubularSegments = tubularSegments;
  31676. _this.p = p;
  31677. _this.q = q;
  31678. _this.side = side;
  31679. return _this;
  31680. }
  31681. TorusKnot.prototype._regenerateVertexData = function () {
  31682. 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 });
  31683. };
  31684. TorusKnot.prototype.copy = function (id) {
  31685. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31686. };
  31687. TorusKnot.prototype.serialize = function () {
  31688. var serializationObject = _super.prototype.serialize.call(this);
  31689. serializationObject.radius = this.radius;
  31690. serializationObject.tube = this.tube;
  31691. serializationObject.radialSegments = this.radialSegments;
  31692. serializationObject.tubularSegments = this.tubularSegments;
  31693. serializationObject.p = this.p;
  31694. serializationObject.q = this.q;
  31695. return serializationObject;
  31696. };
  31697. ;
  31698. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31699. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31700. return null; // null since geometry could be something else than a ground...
  31701. }
  31702. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31703. if (BABYLON.Tags) {
  31704. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31705. }
  31706. scene.pushGeometry(torusKnot, true);
  31707. return torusKnot;
  31708. };
  31709. return TorusKnot;
  31710. }(_Primitive));
  31711. Primitives.TorusKnot = TorusKnot;
  31712. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31713. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31714. })(BABYLON || (BABYLON = {}));
  31715. //# sourceMappingURL=babylon.geometry.js.map
  31716. var BABYLON;
  31717. (function (BABYLON) {
  31718. var PostProcessManager = /** @class */ (function () {
  31719. function PostProcessManager(scene) {
  31720. this._vertexBuffers = {};
  31721. this._scene = scene;
  31722. }
  31723. PostProcessManager.prototype._prepareBuffers = function () {
  31724. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31725. return;
  31726. }
  31727. // VBO
  31728. var vertices = [];
  31729. vertices.push(1, 1);
  31730. vertices.push(-1, 1);
  31731. vertices.push(-1, -1);
  31732. vertices.push(1, -1);
  31733. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31734. this._buildIndexBuffer();
  31735. };
  31736. PostProcessManager.prototype._buildIndexBuffer = function () {
  31737. // Indices
  31738. var indices = [];
  31739. indices.push(0);
  31740. indices.push(1);
  31741. indices.push(2);
  31742. indices.push(0);
  31743. indices.push(2);
  31744. indices.push(3);
  31745. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31746. };
  31747. PostProcessManager.prototype._rebuild = function () {
  31748. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31749. if (!vb) {
  31750. return;
  31751. }
  31752. vb._rebuild();
  31753. this._buildIndexBuffer();
  31754. };
  31755. // Methods
  31756. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31757. if (sourceTexture === void 0) { sourceTexture = null; }
  31758. if (postProcesses === void 0) { postProcesses = null; }
  31759. var camera = this._scene.activeCamera;
  31760. if (!camera) {
  31761. return false;
  31762. }
  31763. var postProcesses = postProcesses || camera._postProcesses;
  31764. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31765. return false;
  31766. }
  31767. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31768. return true;
  31769. };
  31770. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31771. if (targetTexture === void 0) { targetTexture = null; }
  31772. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31773. if (!this._scene.activeCamera) {
  31774. return;
  31775. }
  31776. var engine = this._scene.getEngine();
  31777. for (var index = 0; index < postProcesses.length; index++) {
  31778. if (index < postProcesses.length - 1) {
  31779. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31780. }
  31781. else {
  31782. if (targetTexture) {
  31783. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31784. }
  31785. else {
  31786. engine.restoreDefaultFramebuffer();
  31787. }
  31788. }
  31789. var pp = postProcesses[index];
  31790. var effect = pp.apply();
  31791. if (effect) {
  31792. pp.onBeforeRenderObservable.notifyObservers(effect);
  31793. // VBOs
  31794. this._prepareBuffers();
  31795. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31796. // Draw order
  31797. engine.draw(true, 0, 6);
  31798. pp.onAfterRenderObservable.notifyObservers(effect);
  31799. }
  31800. }
  31801. // Restore depth buffer
  31802. engine.setDepthBuffer(true);
  31803. engine.setDepthWrite(true);
  31804. };
  31805. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31806. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31807. var camera = this._scene.activeCamera;
  31808. if (!camera) {
  31809. return;
  31810. }
  31811. postProcesses = postProcesses || camera._postProcesses;
  31812. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31813. return;
  31814. }
  31815. var engine = this._scene.getEngine();
  31816. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31817. if (index < len - 1) {
  31818. postProcesses[index + 1].activate(camera, targetTexture);
  31819. }
  31820. else {
  31821. if (targetTexture) {
  31822. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31823. }
  31824. else {
  31825. engine.restoreDefaultFramebuffer();
  31826. }
  31827. }
  31828. if (doNotPresent) {
  31829. break;
  31830. }
  31831. var pp = postProcesses[index];
  31832. var effect = pp.apply();
  31833. if (effect) {
  31834. pp.onBeforeRenderObservable.notifyObservers(effect);
  31835. // VBOs
  31836. this._prepareBuffers();
  31837. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31838. // Draw order
  31839. engine.draw(true, 0, 6);
  31840. pp.onAfterRenderObservable.notifyObservers(effect);
  31841. }
  31842. }
  31843. // Restore states
  31844. engine.setDepthBuffer(true);
  31845. engine.setDepthWrite(true);
  31846. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31847. };
  31848. PostProcessManager.prototype.dispose = function () {
  31849. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31850. if (buffer) {
  31851. buffer.dispose();
  31852. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31853. }
  31854. if (this._indexBuffer) {
  31855. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31856. this._indexBuffer = null;
  31857. }
  31858. };
  31859. return PostProcessManager;
  31860. }());
  31861. BABYLON.PostProcessManager = PostProcessManager;
  31862. })(BABYLON || (BABYLON = {}));
  31863. //# sourceMappingURL=babylon.postProcessManager.js.map
  31864. var BABYLON;
  31865. (function (BABYLON) {
  31866. /**
  31867. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31868. */
  31869. var PerformanceMonitor = /** @class */ (function () {
  31870. /**
  31871. * constructor
  31872. * @param frameSampleSize The number of samples required to saturate the sliding window
  31873. */
  31874. function PerformanceMonitor(frameSampleSize) {
  31875. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31876. this._enabled = true;
  31877. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31878. }
  31879. /**
  31880. * Samples current frame
  31881. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31882. */
  31883. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31884. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31885. if (!this._enabled)
  31886. return;
  31887. if (this._lastFrameTimeMs != null) {
  31888. var dt = timeMs - this._lastFrameTimeMs;
  31889. this._rollingFrameTime.add(dt);
  31890. }
  31891. this._lastFrameTimeMs = timeMs;
  31892. };
  31893. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31894. /**
  31895. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31896. * @return Average frame time in milliseconds
  31897. */
  31898. get: function () {
  31899. return this._rollingFrameTime.average;
  31900. },
  31901. enumerable: true,
  31902. configurable: true
  31903. });
  31904. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  31905. /**
  31906. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31907. * @return Frame time variance in milliseconds squared
  31908. */
  31909. get: function () {
  31910. return this._rollingFrameTime.variance;
  31911. },
  31912. enumerable: true,
  31913. configurable: true
  31914. });
  31915. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  31916. /**
  31917. * Returns the frame time of the most recent frame
  31918. * @return Frame time in milliseconds
  31919. */
  31920. get: function () {
  31921. return this._rollingFrameTime.history(0);
  31922. },
  31923. enumerable: true,
  31924. configurable: true
  31925. });
  31926. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  31927. /**
  31928. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  31929. * @return Framerate in frames per second
  31930. */
  31931. get: function () {
  31932. return 1000.0 / this._rollingFrameTime.average;
  31933. },
  31934. enumerable: true,
  31935. configurable: true
  31936. });
  31937. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  31938. /**
  31939. * Returns the average framerate in frames per second using the most recent frame time
  31940. * @return Framerate in frames per second
  31941. */
  31942. get: function () {
  31943. var history = this._rollingFrameTime.history(0);
  31944. if (history === 0) {
  31945. return 0;
  31946. }
  31947. return 1000.0 / history;
  31948. },
  31949. enumerable: true,
  31950. configurable: true
  31951. });
  31952. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  31953. /**
  31954. * Returns true if enough samples have been taken to completely fill the sliding window
  31955. * @return true if saturated
  31956. */
  31957. get: function () {
  31958. return this._rollingFrameTime.isSaturated();
  31959. },
  31960. enumerable: true,
  31961. configurable: true
  31962. });
  31963. /**
  31964. * Enables contributions to the sliding window sample set
  31965. */
  31966. PerformanceMonitor.prototype.enable = function () {
  31967. this._enabled = true;
  31968. };
  31969. /**
  31970. * Disables contributions to the sliding window sample set
  31971. * Samples will not be interpolated over the disabled period
  31972. */
  31973. PerformanceMonitor.prototype.disable = function () {
  31974. this._enabled = false;
  31975. //clear last sample to avoid interpolating over the disabled period when next enabled
  31976. this._lastFrameTimeMs = null;
  31977. this._lastChangeTimeMs = null;
  31978. };
  31979. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  31980. /**
  31981. * Returns true if sampling is enabled
  31982. * @return true if enabled
  31983. */
  31984. get: function () {
  31985. return this._enabled;
  31986. },
  31987. enumerable: true,
  31988. configurable: true
  31989. });
  31990. /**
  31991. * Resets performance monitor
  31992. */
  31993. PerformanceMonitor.prototype.reset = function () {
  31994. //clear last sample to avoid interpolating over the disabled period when next enabled
  31995. this._lastFrameTimeMs = null;
  31996. this._lastChangeTimeMs = null;
  31997. //wipe record
  31998. this._rollingFrameTime.reset();
  31999. };
  32000. return PerformanceMonitor;
  32001. }());
  32002. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32003. /**
  32004. * RollingAverage
  32005. *
  32006. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32007. */
  32008. var RollingAverage = /** @class */ (function () {
  32009. /**
  32010. * constructor
  32011. * @param length The number of samples required to saturate the sliding window
  32012. */
  32013. function RollingAverage(length) {
  32014. this._samples = new Array(length);
  32015. this.reset();
  32016. }
  32017. /**
  32018. * Adds a sample to the sample set
  32019. * @param v The sample value
  32020. */
  32021. RollingAverage.prototype.add = function (v) {
  32022. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32023. var delta;
  32024. //we need to check if we've already wrapped round
  32025. if (this.isSaturated()) {
  32026. //remove bottom of stack from mean
  32027. var bottomValue = this._samples[this._pos];
  32028. delta = bottomValue - this.average;
  32029. this.average -= delta / (this._sampleCount - 1);
  32030. this._m2 -= delta * (bottomValue - this.average);
  32031. }
  32032. else {
  32033. this._sampleCount++;
  32034. }
  32035. //add new value to mean
  32036. delta = v - this.average;
  32037. this.average += delta / (this._sampleCount);
  32038. this._m2 += delta * (v - this.average);
  32039. //set the new variance
  32040. this.variance = this._m2 / (this._sampleCount - 1);
  32041. this._samples[this._pos] = v;
  32042. this._pos++;
  32043. this._pos %= this._samples.length; //positive wrap around
  32044. };
  32045. /**
  32046. * Returns previously added values or null if outside of history or outside the sliding window domain
  32047. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32048. * @return Value previously recorded with add() or null if outside of range
  32049. */
  32050. RollingAverage.prototype.history = function (i) {
  32051. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32052. return 0;
  32053. }
  32054. var i0 = this._wrapPosition(this._pos - 1.0);
  32055. return this._samples[this._wrapPosition(i0 - i)];
  32056. };
  32057. /**
  32058. * Returns true if enough samples have been taken to completely fill the sliding window
  32059. * @return true if sample-set saturated
  32060. */
  32061. RollingAverage.prototype.isSaturated = function () {
  32062. return this._sampleCount >= this._samples.length;
  32063. };
  32064. /**
  32065. * Resets the rolling average (equivalent to 0 samples taken so far)
  32066. */
  32067. RollingAverage.prototype.reset = function () {
  32068. this.average = 0;
  32069. this.variance = 0;
  32070. this._sampleCount = 0;
  32071. this._pos = 0;
  32072. this._m2 = 0;
  32073. };
  32074. /**
  32075. * Wraps a value around the sample range boundaries
  32076. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32077. * @return Wrapped position in sample range
  32078. */
  32079. RollingAverage.prototype._wrapPosition = function (i) {
  32080. var max = this._samples.length;
  32081. return ((i % max) + max) % max;
  32082. };
  32083. return RollingAverage;
  32084. }());
  32085. BABYLON.RollingAverage = RollingAverage;
  32086. })(BABYLON || (BABYLON = {}));
  32087. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32088. var BABYLON;
  32089. (function (BABYLON) {
  32090. /**
  32091. * This groups together the common properties used for image processing either in direct forward pass
  32092. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32093. * or not.
  32094. */
  32095. var ImageProcessingConfiguration = /** @class */ (function () {
  32096. function ImageProcessingConfiguration() {
  32097. /**
  32098. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32099. */
  32100. this.colorCurves = new BABYLON.ColorCurves();
  32101. this._colorCurvesEnabled = false;
  32102. this._colorGradingEnabled = false;
  32103. this._colorGradingWithGreenDepth = true;
  32104. this._colorGradingBGR = true;
  32105. this._exposure = 1.0;
  32106. this._toneMappingEnabled = false;
  32107. this._contrast = 1.0;
  32108. /**
  32109. * Vignette stretch size.
  32110. */
  32111. this.vignetteStretch = 0;
  32112. /**
  32113. * Vignette centre X Offset.
  32114. */
  32115. this.vignetteCentreX = 0;
  32116. /**
  32117. * Vignette centre Y Offset.
  32118. */
  32119. this.vignetteCentreY = 0;
  32120. /**
  32121. * Vignette weight or intensity of the vignette effect.
  32122. */
  32123. this.vignetteWeight = 1.5;
  32124. /**
  32125. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32126. * if vignetteEnabled is set to true.
  32127. */
  32128. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32129. /**
  32130. * Camera field of view used by the Vignette effect.
  32131. */
  32132. this.vignetteCameraFov = 0.5;
  32133. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32134. this._vignetteEnabled = false;
  32135. this._applyByPostProcess = false;
  32136. /**
  32137. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32138. * @type {BABYLON.Observable}
  32139. */
  32140. this.onUpdateParameters = new BABYLON.Observable();
  32141. }
  32142. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32143. /**
  32144. * Gets wether the color curves effect is enabled.
  32145. */
  32146. get: function () {
  32147. return this._colorCurvesEnabled;
  32148. },
  32149. /**
  32150. * Sets wether the color curves effect is enabled.
  32151. */
  32152. set: function (value) {
  32153. if (this._colorCurvesEnabled === value) {
  32154. return;
  32155. }
  32156. this._colorCurvesEnabled = value;
  32157. this._updateParameters();
  32158. },
  32159. enumerable: true,
  32160. configurable: true
  32161. });
  32162. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32163. /**
  32164. * Gets wether the color grading effect is enabled.
  32165. */
  32166. get: function () {
  32167. return this._colorGradingEnabled;
  32168. },
  32169. /**
  32170. * Sets wether the color grading effect is enabled.
  32171. */
  32172. set: function (value) {
  32173. if (this._colorGradingEnabled === value) {
  32174. return;
  32175. }
  32176. this._colorGradingEnabled = value;
  32177. this._updateParameters();
  32178. },
  32179. enumerable: true,
  32180. configurable: true
  32181. });
  32182. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32183. /**
  32184. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32185. */
  32186. get: function () {
  32187. return this._colorGradingWithGreenDepth;
  32188. },
  32189. /**
  32190. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32191. */
  32192. set: function (value) {
  32193. if (this._colorGradingWithGreenDepth === value) {
  32194. return;
  32195. }
  32196. this._colorGradingWithGreenDepth = value;
  32197. this._updateParameters();
  32198. },
  32199. enumerable: true,
  32200. configurable: true
  32201. });
  32202. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32203. /**
  32204. * Gets wether the color grading texture contains BGR values.
  32205. */
  32206. get: function () {
  32207. return this._colorGradingBGR;
  32208. },
  32209. /**
  32210. * Sets wether the color grading texture contains BGR values.
  32211. */
  32212. set: function (value) {
  32213. if (this._colorGradingBGR === value) {
  32214. return;
  32215. }
  32216. this._colorGradingBGR = value;
  32217. this._updateParameters();
  32218. },
  32219. enumerable: true,
  32220. configurable: true
  32221. });
  32222. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32223. /**
  32224. * Gets the Exposure used in the effect.
  32225. */
  32226. get: function () {
  32227. return this._exposure;
  32228. },
  32229. /**
  32230. * Sets the Exposure used in the effect.
  32231. */
  32232. set: function (value) {
  32233. if (this._exposure === value) {
  32234. return;
  32235. }
  32236. this._exposure = value;
  32237. this._updateParameters();
  32238. },
  32239. enumerable: true,
  32240. configurable: true
  32241. });
  32242. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32243. /**
  32244. * Gets wether the tone mapping effect is enabled.
  32245. */
  32246. get: function () {
  32247. return this._toneMappingEnabled;
  32248. },
  32249. /**
  32250. * Sets wether the tone mapping effect is enabled.
  32251. */
  32252. set: function (value) {
  32253. if (this._toneMappingEnabled === value) {
  32254. return;
  32255. }
  32256. this._toneMappingEnabled = value;
  32257. this._updateParameters();
  32258. },
  32259. enumerable: true,
  32260. configurable: true
  32261. });
  32262. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32263. /**
  32264. * Gets the contrast used in the effect.
  32265. */
  32266. get: function () {
  32267. return this._contrast;
  32268. },
  32269. /**
  32270. * Sets the contrast used in the effect.
  32271. */
  32272. set: function (value) {
  32273. if (this._contrast === value) {
  32274. return;
  32275. }
  32276. this._contrast = value;
  32277. this._updateParameters();
  32278. },
  32279. enumerable: true,
  32280. configurable: true
  32281. });
  32282. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32283. /**
  32284. * Gets the vignette blend mode allowing different kind of effect.
  32285. */
  32286. get: function () {
  32287. return this._vignetteBlendMode;
  32288. },
  32289. /**
  32290. * Sets the vignette blend mode allowing different kind of effect.
  32291. */
  32292. set: function (value) {
  32293. if (this._vignetteBlendMode === value) {
  32294. return;
  32295. }
  32296. this._vignetteBlendMode = value;
  32297. this._updateParameters();
  32298. },
  32299. enumerable: true,
  32300. configurable: true
  32301. });
  32302. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32303. /**
  32304. * Gets wether the vignette effect is enabled.
  32305. */
  32306. get: function () {
  32307. return this._vignetteEnabled;
  32308. },
  32309. /**
  32310. * Sets wether the vignette effect is enabled.
  32311. */
  32312. set: function (value) {
  32313. if (this._vignetteEnabled === value) {
  32314. return;
  32315. }
  32316. this._vignetteEnabled = value;
  32317. this._updateParameters();
  32318. },
  32319. enumerable: true,
  32320. configurable: true
  32321. });
  32322. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32323. /**
  32324. * Gets wether the image processing is applied through a post process or not.
  32325. */
  32326. get: function () {
  32327. return this._applyByPostProcess;
  32328. },
  32329. /**
  32330. * Sets wether the image processing is applied through a post process or not.
  32331. */
  32332. set: function (value) {
  32333. if (this._applyByPostProcess === value) {
  32334. return;
  32335. }
  32336. this._applyByPostProcess = value;
  32337. this._updateParameters();
  32338. },
  32339. enumerable: true,
  32340. configurable: true
  32341. });
  32342. /**
  32343. * Method called each time the image processing information changes requires to recompile the effect.
  32344. */
  32345. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32346. this.onUpdateParameters.notifyObservers(this);
  32347. };
  32348. ImageProcessingConfiguration.prototype.getClassName = function () {
  32349. return "ImageProcessingConfiguration";
  32350. };
  32351. /**
  32352. * Prepare the list of uniforms associated with the Image Processing effects.
  32353. * @param uniformsList The list of uniforms used in the effect
  32354. * @param defines the list of defines currently in use
  32355. */
  32356. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32357. if (defines.EXPOSURE) {
  32358. uniforms.push("exposureLinear");
  32359. }
  32360. if (defines.CONTRAST) {
  32361. uniforms.push("contrast");
  32362. }
  32363. if (defines.COLORGRADING) {
  32364. uniforms.push("colorTransformSettings");
  32365. }
  32366. if (defines.VIGNETTE) {
  32367. uniforms.push("vInverseScreenSize");
  32368. uniforms.push("vignetteSettings1");
  32369. uniforms.push("vignetteSettings2");
  32370. }
  32371. if (defines.COLORCURVES) {
  32372. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32373. }
  32374. };
  32375. /**
  32376. * Prepare the list of samplers associated with the Image Processing effects.
  32377. * @param uniformsList The list of uniforms used in the effect
  32378. * @param defines the list of defines currently in use
  32379. */
  32380. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32381. if (defines.COLORGRADING) {
  32382. samplersList.push("txColorTransform");
  32383. }
  32384. };
  32385. /**
  32386. * Prepare the list of defines associated to the shader.
  32387. * @param defines the list of defines to complete
  32388. */
  32389. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32390. if (forPostProcess === void 0) { forPostProcess = false; }
  32391. if (forPostProcess !== this.applyByPostProcess) {
  32392. defines.VIGNETTE = false;
  32393. defines.TONEMAPPING = false;
  32394. defines.CONTRAST = false;
  32395. defines.EXPOSURE = false;
  32396. defines.COLORCURVES = false;
  32397. defines.COLORGRADING = false;
  32398. defines.COLORGRADING3D = false;
  32399. defines.IMAGEPROCESSING = false;
  32400. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32401. return;
  32402. }
  32403. defines.VIGNETTE = this.vignetteEnabled;
  32404. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32405. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32406. defines.TONEMAPPING = this.toneMappingEnabled;
  32407. defines.CONTRAST = (this.contrast !== 1.0);
  32408. defines.EXPOSURE = (this.exposure !== 1.0);
  32409. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32410. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32411. if (defines.COLORGRADING) {
  32412. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32413. }
  32414. else {
  32415. defines.COLORGRADING3D = false;
  32416. }
  32417. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32418. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32419. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32420. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32421. };
  32422. /**
  32423. * Returns true if all the image processing information are ready.
  32424. */
  32425. ImageProcessingConfiguration.prototype.isReady = function () {
  32426. // Color Grading texure can not be none blocking.
  32427. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32428. };
  32429. /**
  32430. * Binds the image processing to the shader.
  32431. * @param effect The effect to bind to
  32432. */
  32433. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32434. if (aspectRatio === void 0) { aspectRatio = 1; }
  32435. // Color Curves
  32436. if (this._colorCurvesEnabled && this.colorCurves) {
  32437. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32438. }
  32439. // Vignette
  32440. if (this._vignetteEnabled) {
  32441. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32442. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32443. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32444. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32445. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32446. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32447. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32448. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32449. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32450. var vignettePower = -2.0 * this.vignetteWeight;
  32451. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32452. }
  32453. // Exposure
  32454. effect.setFloat("exposureLinear", this.exposure);
  32455. // Contrast
  32456. effect.setFloat("contrast", this.contrast);
  32457. // Color transform settings
  32458. if (this.colorGradingTexture) {
  32459. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32460. var textureSize = this.colorGradingTexture.getSize().height;
  32461. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32462. 0.5 / textureSize, // textureOffset
  32463. textureSize, // textureSize
  32464. this.colorGradingTexture.level // weight
  32465. );
  32466. }
  32467. };
  32468. /**
  32469. * Clones the current image processing instance.
  32470. * @return The cloned image processing
  32471. */
  32472. ImageProcessingConfiguration.prototype.clone = function () {
  32473. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32474. };
  32475. /**
  32476. * Serializes the current image processing instance to a json representation.
  32477. * @return a JSON representation
  32478. */
  32479. ImageProcessingConfiguration.prototype.serialize = function () {
  32480. return BABYLON.SerializationHelper.Serialize(this);
  32481. };
  32482. /**
  32483. * Parses the image processing from a json representation.
  32484. * @param source the JSON source to parse
  32485. * @return The parsed image processing
  32486. */
  32487. ImageProcessingConfiguration.Parse = function (source) {
  32488. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32489. };
  32490. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32491. /**
  32492. * Used to apply the vignette as a mix with the pixel color.
  32493. */
  32494. get: function () {
  32495. return this._VIGNETTEMODE_MULTIPLY;
  32496. },
  32497. enumerable: true,
  32498. configurable: true
  32499. });
  32500. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32501. /**
  32502. * Used to apply the vignette as a replacement of the pixel color.
  32503. */
  32504. get: function () {
  32505. return this._VIGNETTEMODE_OPAQUE;
  32506. },
  32507. enumerable: true,
  32508. configurable: true
  32509. });
  32510. // Static constants associated to the image processing.
  32511. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32512. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32513. __decorate([
  32514. BABYLON.serializeAsColorCurves()
  32515. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32516. __decorate([
  32517. BABYLON.serialize()
  32518. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32519. __decorate([
  32520. BABYLON.serializeAsTexture()
  32521. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32522. __decorate([
  32523. BABYLON.serialize()
  32524. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32525. __decorate([
  32526. BABYLON.serialize()
  32527. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32528. __decorate([
  32529. BABYLON.serialize()
  32530. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32531. __decorate([
  32532. BABYLON.serialize()
  32533. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32534. __decorate([
  32535. BABYLON.serialize()
  32536. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32537. __decorate([
  32538. BABYLON.serialize()
  32539. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32540. __decorate([
  32541. BABYLON.serialize()
  32542. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32543. __decorate([
  32544. BABYLON.serialize()
  32545. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32546. __decorate([
  32547. BABYLON.serialize()
  32548. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32549. __decorate([
  32550. BABYLON.serialize()
  32551. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32552. __decorate([
  32553. BABYLON.serializeAsColor4()
  32554. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32555. __decorate([
  32556. BABYLON.serialize()
  32557. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32558. __decorate([
  32559. BABYLON.serialize()
  32560. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32561. __decorate([
  32562. BABYLON.serialize()
  32563. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32564. __decorate([
  32565. BABYLON.serialize()
  32566. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32567. return ImageProcessingConfiguration;
  32568. }());
  32569. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  32570. })(BABYLON || (BABYLON = {}));
  32571. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  32572. var BABYLON;
  32573. (function (BABYLON) {
  32574. /**
  32575. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  32576. * It can help converting any input color in a desired output one. This can then be used to create effects
  32577. * from sepia, black and white to sixties or futuristic rendering...
  32578. *
  32579. * The only supported format is currently 3dl.
  32580. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  32581. */
  32582. var ColorGradingTexture = /** @class */ (function (_super) {
  32583. __extends(ColorGradingTexture, _super);
  32584. /**
  32585. * Instantiates a ColorGradingTexture from the following parameters.
  32586. *
  32587. * @param url The location of the color gradind data (currently only supporting 3dl)
  32588. * @param scene The scene the texture will be used in
  32589. */
  32590. function ColorGradingTexture(url, scene) {
  32591. var _this = _super.call(this, scene) || this;
  32592. if (!url) {
  32593. return _this;
  32594. }
  32595. _this._engine = scene.getEngine();
  32596. _this._textureMatrix = BABYLON.Matrix.Identity();
  32597. _this.name = url;
  32598. _this.url = url;
  32599. _this.hasAlpha = false;
  32600. _this.isCube = false;
  32601. _this.is3D = _this._engine.webGLVersion > 1;
  32602. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32603. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32604. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32605. _this.anisotropicFilteringLevel = 1;
  32606. _this._texture = _this._getFromCache(url, true);
  32607. if (!_this._texture) {
  32608. if (!scene.useDelayedTextureLoading) {
  32609. _this.loadTexture();
  32610. }
  32611. else {
  32612. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32613. }
  32614. }
  32615. return _this;
  32616. }
  32617. /**
  32618. * Returns the texture matrix used in most of the material.
  32619. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  32620. */
  32621. ColorGradingTexture.prototype.getTextureMatrix = function () {
  32622. return this._textureMatrix;
  32623. };
  32624. /**
  32625. * Occurs when the file being loaded is a .3dl LUT file.
  32626. */
  32627. ColorGradingTexture.prototype.load3dlTexture = function () {
  32628. var engine = this._engine;
  32629. var texture;
  32630. if (engine.webGLVersion === 1) {
  32631. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32632. }
  32633. else {
  32634. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32635. }
  32636. this._texture = texture;
  32637. var callback = function (text) {
  32638. var data = null;
  32639. var tempData = null;
  32640. var line;
  32641. var lines = text.split('\n');
  32642. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  32643. var maxColor = 0;
  32644. for (var i = 0; i < lines.length; i++) {
  32645. line = lines[i];
  32646. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  32647. continue;
  32648. if (line.indexOf('#') === 0)
  32649. continue;
  32650. var words = line.split(" ");
  32651. if (size === 0) {
  32652. // Number of space + one
  32653. size = words.length;
  32654. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  32655. tempData = new Float32Array(size * size * size * 4);
  32656. continue;
  32657. }
  32658. if (size != 0) {
  32659. var r = Math.max(parseInt(words[0]), 0);
  32660. var g = Math.max(parseInt(words[1]), 0);
  32661. var b = Math.max(parseInt(words[2]), 0);
  32662. maxColor = Math.max(r, maxColor);
  32663. maxColor = Math.max(g, maxColor);
  32664. maxColor = Math.max(b, maxColor);
  32665. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  32666. if (tempData) {
  32667. tempData[pixelStorageIndex + 0] = r;
  32668. tempData[pixelStorageIndex + 1] = g;
  32669. tempData[pixelStorageIndex + 2] = b;
  32670. }
  32671. pixelIndexSlice++;
  32672. if (pixelIndexSlice % size == 0) {
  32673. pixelIndexH++;
  32674. pixelIndexSlice = 0;
  32675. if (pixelIndexH % size == 0) {
  32676. pixelIndexW++;
  32677. pixelIndexH = 0;
  32678. }
  32679. }
  32680. }
  32681. }
  32682. if (tempData && data) {
  32683. for (var i = 0; i < tempData.length; i++) {
  32684. if (i > 0 && (i + 1) % 4 === 0) {
  32685. data[i] = 255;
  32686. }
  32687. else {
  32688. var value = tempData[i];
  32689. data[i] = (value / maxColor * 255);
  32690. }
  32691. }
  32692. }
  32693. if (texture.is3D) {
  32694. texture.updateSize(size, size, size);
  32695. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32696. }
  32697. else {
  32698. texture.updateSize(size * size, size);
  32699. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32700. }
  32701. };
  32702. BABYLON.Tools.LoadFile(this.url, callback);
  32703. return this._texture;
  32704. };
  32705. /**
  32706. * Starts the loading process of the texture.
  32707. */
  32708. ColorGradingTexture.prototype.loadTexture = function () {
  32709. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  32710. this.load3dlTexture();
  32711. }
  32712. };
  32713. /**
  32714. * Clones the color gradind texture.
  32715. */
  32716. ColorGradingTexture.prototype.clone = function () {
  32717. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  32718. // Base texture
  32719. newTexture.level = this.level;
  32720. return newTexture;
  32721. };
  32722. /**
  32723. * Called during delayed load for textures.
  32724. */
  32725. ColorGradingTexture.prototype.delayLoad = function () {
  32726. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32727. return;
  32728. }
  32729. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32730. this._texture = this._getFromCache(this.url, true);
  32731. if (!this._texture) {
  32732. this.loadTexture();
  32733. }
  32734. };
  32735. /**
  32736. * Parses a color grading texture serialized by Babylon.
  32737. * @param parsedTexture The texture information being parsedTexture
  32738. * @param scene The scene to load the texture in
  32739. * @param rootUrl The root url of the data assets to load
  32740. * @return A color gradind texture
  32741. */
  32742. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32743. var texture = null;
  32744. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  32745. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  32746. texture.name = parsedTexture.name;
  32747. texture.level = parsedTexture.level;
  32748. }
  32749. return texture;
  32750. };
  32751. /**
  32752. * Serializes the LUT texture to json format.
  32753. */
  32754. ColorGradingTexture.prototype.serialize = function () {
  32755. if (!this.name) {
  32756. return null;
  32757. }
  32758. var serializationObject = {};
  32759. serializationObject.name = this.name;
  32760. serializationObject.level = this.level;
  32761. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32762. return serializationObject;
  32763. };
  32764. /**
  32765. * Empty line regex stored for GC.
  32766. */
  32767. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32768. return ColorGradingTexture;
  32769. }(BABYLON.BaseTexture));
  32770. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32771. })(BABYLON || (BABYLON = {}));
  32772. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32773. var BABYLON;
  32774. (function (BABYLON) {
  32775. /**
  32776. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32777. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32778. * 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;
  32779. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32780. */
  32781. var ColorCurves = /** @class */ (function () {
  32782. function ColorCurves() {
  32783. this._dirty = true;
  32784. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32785. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32786. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32787. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32788. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32789. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32790. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32791. this._globalHue = 30;
  32792. this._globalDensity = 0;
  32793. this._globalSaturation = 0;
  32794. this._globalExposure = 0;
  32795. this._highlightsHue = 30;
  32796. this._highlightsDensity = 0;
  32797. this._highlightsSaturation = 0;
  32798. this._highlightsExposure = 0;
  32799. this._midtonesHue = 30;
  32800. this._midtonesDensity = 0;
  32801. this._midtonesSaturation = 0;
  32802. this._midtonesExposure = 0;
  32803. this._shadowsHue = 30;
  32804. this._shadowsDensity = 0;
  32805. this._shadowsSaturation = 0;
  32806. this._shadowsExposure = 0;
  32807. }
  32808. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32809. /**
  32810. * Gets the global Hue value.
  32811. * 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).
  32812. */
  32813. get: function () {
  32814. return this._globalHue;
  32815. },
  32816. /**
  32817. * Sets the global Hue value.
  32818. * 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).
  32819. */
  32820. set: function (value) {
  32821. this._globalHue = value;
  32822. this._dirty = true;
  32823. },
  32824. enumerable: true,
  32825. configurable: true
  32826. });
  32827. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32828. /**
  32829. * Gets the global Density value.
  32830. * 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.
  32831. * Values less than zero provide a filter of opposite hue.
  32832. */
  32833. get: function () {
  32834. return this._globalDensity;
  32835. },
  32836. /**
  32837. * Sets the global Density value.
  32838. * 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.
  32839. * Values less than zero provide a filter of opposite hue.
  32840. */
  32841. set: function (value) {
  32842. this._globalDensity = value;
  32843. this._dirty = true;
  32844. },
  32845. enumerable: true,
  32846. configurable: true
  32847. });
  32848. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32849. /**
  32850. * Gets the global Saturation value.
  32851. * 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.
  32852. */
  32853. get: function () {
  32854. return this._globalSaturation;
  32855. },
  32856. /**
  32857. * Sets the global Saturation value.
  32858. * 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.
  32859. */
  32860. set: function (value) {
  32861. this._globalSaturation = value;
  32862. this._dirty = true;
  32863. },
  32864. enumerable: true,
  32865. configurable: true
  32866. });
  32867. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32868. /**
  32869. * Gets the highlights Hue value.
  32870. * 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).
  32871. */
  32872. get: function () {
  32873. return this._highlightsHue;
  32874. },
  32875. /**
  32876. * Sets the highlights Hue value.
  32877. * 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).
  32878. */
  32879. set: function (value) {
  32880. this._highlightsHue = value;
  32881. this._dirty = true;
  32882. },
  32883. enumerable: true,
  32884. configurable: true
  32885. });
  32886. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32887. /**
  32888. * Gets the highlights Density value.
  32889. * 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.
  32890. * Values less than zero provide a filter of opposite hue.
  32891. */
  32892. get: function () {
  32893. return this._highlightsDensity;
  32894. },
  32895. /**
  32896. * Sets the highlights Density value.
  32897. * 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.
  32898. * Values less than zero provide a filter of opposite hue.
  32899. */
  32900. set: function (value) {
  32901. this._highlightsDensity = value;
  32902. this._dirty = true;
  32903. },
  32904. enumerable: true,
  32905. configurable: true
  32906. });
  32907. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  32908. /**
  32909. * Gets the highlights Saturation value.
  32910. * 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.
  32911. */
  32912. get: function () {
  32913. return this._highlightsSaturation;
  32914. },
  32915. /**
  32916. * Sets the highlights Saturation value.
  32917. * 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.
  32918. */
  32919. set: function (value) {
  32920. this._highlightsSaturation = value;
  32921. this._dirty = true;
  32922. },
  32923. enumerable: true,
  32924. configurable: true
  32925. });
  32926. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  32927. /**
  32928. * Gets the highlights Exposure value.
  32929. * 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.
  32930. */
  32931. get: function () {
  32932. return this._highlightsExposure;
  32933. },
  32934. /**
  32935. * Sets the highlights Exposure value.
  32936. * 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.
  32937. */
  32938. set: function (value) {
  32939. this._highlightsExposure = value;
  32940. this._dirty = true;
  32941. },
  32942. enumerable: true,
  32943. configurable: true
  32944. });
  32945. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  32946. /**
  32947. * Gets the midtones Hue value.
  32948. * 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).
  32949. */
  32950. get: function () {
  32951. return this._midtonesHue;
  32952. },
  32953. /**
  32954. * Sets the midtones Hue value.
  32955. * 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).
  32956. */
  32957. set: function (value) {
  32958. this._midtonesHue = value;
  32959. this._dirty = true;
  32960. },
  32961. enumerable: true,
  32962. configurable: true
  32963. });
  32964. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  32965. /**
  32966. * Gets the midtones Density value.
  32967. * 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.
  32968. * Values less than zero provide a filter of opposite hue.
  32969. */
  32970. get: function () {
  32971. return this._midtonesDensity;
  32972. },
  32973. /**
  32974. * Sets the midtones Density value.
  32975. * 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.
  32976. * Values less than zero provide a filter of opposite hue.
  32977. */
  32978. set: function (value) {
  32979. this._midtonesDensity = value;
  32980. this._dirty = true;
  32981. },
  32982. enumerable: true,
  32983. configurable: true
  32984. });
  32985. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  32986. /**
  32987. * Gets the midtones Saturation value.
  32988. * 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.
  32989. */
  32990. get: function () {
  32991. return this._midtonesSaturation;
  32992. },
  32993. /**
  32994. * Sets the midtones Saturation value.
  32995. * 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.
  32996. */
  32997. set: function (value) {
  32998. this._midtonesSaturation = value;
  32999. this._dirty = true;
  33000. },
  33001. enumerable: true,
  33002. configurable: true
  33003. });
  33004. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33005. /**
  33006. * Gets the midtones Exposure value.
  33007. * 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.
  33008. */
  33009. get: function () {
  33010. return this._midtonesExposure;
  33011. },
  33012. /**
  33013. * Sets the midtones Exposure value.
  33014. * 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.
  33015. */
  33016. set: function (value) {
  33017. this._midtonesExposure = value;
  33018. this._dirty = true;
  33019. },
  33020. enumerable: true,
  33021. configurable: true
  33022. });
  33023. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33024. /**
  33025. * Gets the shadows Hue value.
  33026. * 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).
  33027. */
  33028. get: function () {
  33029. return this._shadowsHue;
  33030. },
  33031. /**
  33032. * Sets the shadows Hue value.
  33033. * 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).
  33034. */
  33035. set: function (value) {
  33036. this._shadowsHue = value;
  33037. this._dirty = true;
  33038. },
  33039. enumerable: true,
  33040. configurable: true
  33041. });
  33042. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33043. /**
  33044. * Gets the shadows Density value.
  33045. * 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.
  33046. * Values less than zero provide a filter of opposite hue.
  33047. */
  33048. get: function () {
  33049. return this._shadowsDensity;
  33050. },
  33051. /**
  33052. * Sets the shadows Density value.
  33053. * 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.
  33054. * Values less than zero provide a filter of opposite hue.
  33055. */
  33056. set: function (value) {
  33057. this._shadowsDensity = value;
  33058. this._dirty = true;
  33059. },
  33060. enumerable: true,
  33061. configurable: true
  33062. });
  33063. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33064. /**
  33065. * Gets the shadows Saturation value.
  33066. * 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.
  33067. */
  33068. get: function () {
  33069. return this._shadowsSaturation;
  33070. },
  33071. /**
  33072. * Sets the shadows Saturation value.
  33073. * 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.
  33074. */
  33075. set: function (value) {
  33076. this._shadowsSaturation = value;
  33077. this._dirty = true;
  33078. },
  33079. enumerable: true,
  33080. configurable: true
  33081. });
  33082. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33083. /**
  33084. * Gets the shadows Exposure value.
  33085. * 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.
  33086. */
  33087. get: function () {
  33088. return this._shadowsExposure;
  33089. },
  33090. /**
  33091. * Sets the shadows Exposure value.
  33092. * 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.
  33093. */
  33094. set: function (value) {
  33095. this._shadowsExposure = value;
  33096. this._dirty = true;
  33097. },
  33098. enumerable: true,
  33099. configurable: true
  33100. });
  33101. ColorCurves.prototype.getClassName = function () {
  33102. return "ColorCurves";
  33103. };
  33104. /**
  33105. * Binds the color curves to the shader.
  33106. * @param colorCurves The color curve to bind
  33107. * @param effect The effect to bind to
  33108. */
  33109. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33110. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33111. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33112. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33113. if (colorCurves._dirty) {
  33114. colorCurves._dirty = false;
  33115. // Fill in global info.
  33116. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33117. // Compute highlights info.
  33118. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33119. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33120. // Compute midtones info.
  33121. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33122. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33123. // Compute shadows info.
  33124. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33125. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33126. // Compute deltas (neutral is midtones).
  33127. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33128. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33129. }
  33130. if (effect) {
  33131. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33132. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33133. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33134. }
  33135. };
  33136. /**
  33137. * Prepare the list of uniforms associated with the ColorCurves effects.
  33138. * @param uniformsList The list of uniforms used in the effect
  33139. */
  33140. ColorCurves.PrepareUniforms = function (uniformsList) {
  33141. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33142. };
  33143. /**
  33144. * Returns color grading data based on a hue, density, saturation and exposure value.
  33145. * @param filterHue The hue of the color filter.
  33146. * @param filterDensity The density of the color filter.
  33147. * @param saturation The saturation.
  33148. * @param exposure The exposure.
  33149. * @param result The result data container.
  33150. */
  33151. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33152. if (hue == null) {
  33153. return;
  33154. }
  33155. hue = ColorCurves.clamp(hue, 0, 360);
  33156. density = ColorCurves.clamp(density, -100, 100);
  33157. saturation = ColorCurves.clamp(saturation, -100, 100);
  33158. exposure = ColorCurves.clamp(exposure, -100, 100);
  33159. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33160. // so that the maximum filter density is only 50% control. This provides fine control
  33161. // for small values and reasonable range.
  33162. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33163. density *= 0.5;
  33164. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33165. if (density < 0) {
  33166. density *= -1;
  33167. hue = (hue + 180) % 360;
  33168. }
  33169. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33170. result.scaleToRef(2, result);
  33171. result.a = 1 + 0.01 * saturation;
  33172. };
  33173. /**
  33174. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33175. * @param value The input slider value in range [-100,100].
  33176. * @returns Adjusted value.
  33177. */
  33178. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33179. value /= 100;
  33180. var x = Math.abs(value);
  33181. x = Math.pow(x, 2);
  33182. if (value < 0) {
  33183. x *= -1;
  33184. }
  33185. x *= 100;
  33186. return x;
  33187. };
  33188. /**
  33189. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33190. * @param hue The hue (H) input.
  33191. * @param saturation The saturation (S) input.
  33192. * @param brightness The brightness (B) input.
  33193. * @result An RGBA color represented as Vector4.
  33194. */
  33195. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33196. var h = ColorCurves.clamp(hue, 0, 360);
  33197. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33198. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33199. if (s === 0) {
  33200. result.r = v;
  33201. result.g = v;
  33202. result.b = v;
  33203. }
  33204. else {
  33205. // sector 0 to 5
  33206. h /= 60;
  33207. var i = Math.floor(h);
  33208. // fractional part of h
  33209. var f = h - i;
  33210. var p = v * (1 - s);
  33211. var q = v * (1 - s * f);
  33212. var t = v * (1 - s * (1 - f));
  33213. switch (i) {
  33214. case 0:
  33215. result.r = v;
  33216. result.g = t;
  33217. result.b = p;
  33218. break;
  33219. case 1:
  33220. result.r = q;
  33221. result.g = v;
  33222. result.b = p;
  33223. break;
  33224. case 2:
  33225. result.r = p;
  33226. result.g = v;
  33227. result.b = t;
  33228. break;
  33229. case 3:
  33230. result.r = p;
  33231. result.g = q;
  33232. result.b = v;
  33233. break;
  33234. case 4:
  33235. result.r = t;
  33236. result.g = p;
  33237. result.b = v;
  33238. break;
  33239. default:// case 5:
  33240. result.r = v;
  33241. result.g = p;
  33242. result.b = q;
  33243. break;
  33244. }
  33245. }
  33246. result.a = 1;
  33247. };
  33248. /**
  33249. * Returns a value clamped between min and max
  33250. * @param value The value to clamp
  33251. * @param min The minimum of value
  33252. * @param max The maximum of value
  33253. * @returns The clamped value.
  33254. */
  33255. ColorCurves.clamp = function (value, min, max) {
  33256. return Math.min(Math.max(value, min), max);
  33257. };
  33258. /**
  33259. * Clones the current color curve instance.
  33260. * @return The cloned curves
  33261. */
  33262. ColorCurves.prototype.clone = function () {
  33263. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33264. };
  33265. /**
  33266. * Serializes the current color curve instance to a json representation.
  33267. * @return a JSON representation
  33268. */
  33269. ColorCurves.prototype.serialize = function () {
  33270. return BABYLON.SerializationHelper.Serialize(this);
  33271. };
  33272. /**
  33273. * Parses the color curve from a json representation.
  33274. * @param source the JSON source to parse
  33275. * @return The parsed curves
  33276. */
  33277. ColorCurves.Parse = function (source) {
  33278. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33279. };
  33280. __decorate([
  33281. BABYLON.serialize()
  33282. ], ColorCurves.prototype, "_globalHue", void 0);
  33283. __decorate([
  33284. BABYLON.serialize()
  33285. ], ColorCurves.prototype, "_globalDensity", void 0);
  33286. __decorate([
  33287. BABYLON.serialize()
  33288. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33289. __decorate([
  33290. BABYLON.serialize()
  33291. ], ColorCurves.prototype, "_globalExposure", void 0);
  33292. __decorate([
  33293. BABYLON.serialize()
  33294. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33295. __decorate([
  33296. BABYLON.serialize()
  33297. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33298. __decorate([
  33299. BABYLON.serialize()
  33300. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33301. __decorate([
  33302. BABYLON.serialize()
  33303. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33304. __decorate([
  33305. BABYLON.serialize()
  33306. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33307. __decorate([
  33308. BABYLON.serialize()
  33309. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33310. __decorate([
  33311. BABYLON.serialize()
  33312. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33313. __decorate([
  33314. BABYLON.serialize()
  33315. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33316. return ColorCurves;
  33317. }());
  33318. BABYLON.ColorCurves = ColorCurves;
  33319. })(BABYLON || (BABYLON = {}));
  33320. //# sourceMappingURL=babylon.colorCurves.js.map
  33321. var BABYLON;
  33322. (function (BABYLON) {
  33323. var StandardMaterialDefines = /** @class */ (function (_super) {
  33324. __extends(StandardMaterialDefines, _super);
  33325. function StandardMaterialDefines() {
  33326. var _this = _super.call(this) || this;
  33327. _this.MAINUV1 = false;
  33328. _this.MAINUV2 = false;
  33329. _this.DIFFUSE = false;
  33330. _this.DIFFUSEDIRECTUV = 0;
  33331. _this.AMBIENT = false;
  33332. _this.AMBIENTDIRECTUV = 0;
  33333. _this.OPACITY = false;
  33334. _this.OPACITYDIRECTUV = 0;
  33335. _this.OPACITYRGB = false;
  33336. _this.REFLECTION = false;
  33337. _this.EMISSIVE = false;
  33338. _this.EMISSIVEDIRECTUV = 0;
  33339. _this.SPECULAR = false;
  33340. _this.SPECULARDIRECTUV = 0;
  33341. _this.BUMP = false;
  33342. _this.BUMPDIRECTUV = 0;
  33343. _this.PARALLAX = false;
  33344. _this.PARALLAXOCCLUSION = false;
  33345. _this.SPECULAROVERALPHA = false;
  33346. _this.CLIPPLANE = false;
  33347. _this.ALPHATEST = false;
  33348. _this.DEPTHPREPASS = false;
  33349. _this.ALPHAFROMDIFFUSE = false;
  33350. _this.POINTSIZE = false;
  33351. _this.FOG = false;
  33352. _this.SPECULARTERM = false;
  33353. _this.DIFFUSEFRESNEL = false;
  33354. _this.OPACITYFRESNEL = false;
  33355. _this.REFLECTIONFRESNEL = false;
  33356. _this.REFRACTIONFRESNEL = false;
  33357. _this.EMISSIVEFRESNEL = false;
  33358. _this.FRESNEL = false;
  33359. _this.NORMAL = false;
  33360. _this.UV1 = false;
  33361. _this.UV2 = false;
  33362. _this.VERTEXCOLOR = false;
  33363. _this.VERTEXALPHA = false;
  33364. _this.NUM_BONE_INFLUENCERS = 0;
  33365. _this.BonesPerMesh = 0;
  33366. _this.INSTANCES = false;
  33367. _this.GLOSSINESS = false;
  33368. _this.ROUGHNESS = false;
  33369. _this.EMISSIVEASILLUMINATION = false;
  33370. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33371. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33372. _this.LIGHTMAP = false;
  33373. _this.LIGHTMAPDIRECTUV = 0;
  33374. _this.USELIGHTMAPASSHADOWMAP = false;
  33375. _this.REFLECTIONMAP_3D = false;
  33376. _this.REFLECTIONMAP_SPHERICAL = false;
  33377. _this.REFLECTIONMAP_PLANAR = false;
  33378. _this.REFLECTIONMAP_CUBIC = false;
  33379. _this.REFLECTIONMAP_PROJECTION = false;
  33380. _this.REFLECTIONMAP_SKYBOX = false;
  33381. _this.REFLECTIONMAP_EXPLICIT = false;
  33382. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33383. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33384. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33385. _this.INVERTCUBICMAP = false;
  33386. _this.LOGARITHMICDEPTH = false;
  33387. _this.REFRACTION = false;
  33388. _this.REFRACTIONMAP_3D = false;
  33389. _this.REFLECTIONOVERALPHA = false;
  33390. _this.TWOSIDEDLIGHTING = false;
  33391. _this.SHADOWFLOAT = false;
  33392. _this.MORPHTARGETS = false;
  33393. _this.MORPHTARGETS_NORMAL = false;
  33394. _this.MORPHTARGETS_TANGENT = false;
  33395. _this.NUM_MORPH_INFLUENCERS = 0;
  33396. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33397. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33398. _this.IMAGEPROCESSING = false;
  33399. _this.VIGNETTE = false;
  33400. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33401. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33402. _this.TONEMAPPING = false;
  33403. _this.CONTRAST = false;
  33404. _this.COLORCURVES = false;
  33405. _this.COLORGRADING = false;
  33406. _this.COLORGRADING3D = false;
  33407. _this.SAMPLER3DGREENDEPTH = false;
  33408. _this.SAMPLER3DBGRMAP = false;
  33409. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33410. _this.EXPOSURE = false;
  33411. _this.rebuild();
  33412. return _this;
  33413. }
  33414. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33415. var modes = [
  33416. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33417. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33418. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33419. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33420. ];
  33421. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33422. var mode = modes_1[_i];
  33423. this[mode] = (mode === modeToEnable);
  33424. }
  33425. };
  33426. return StandardMaterialDefines;
  33427. }(BABYLON.MaterialDefines));
  33428. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33429. var StandardMaterial = /** @class */ (function (_super) {
  33430. __extends(StandardMaterial, _super);
  33431. function StandardMaterial(name, scene) {
  33432. var _this = _super.call(this, name, scene) || this;
  33433. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33434. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33435. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33436. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33437. _this.specularPower = 64;
  33438. _this._useAlphaFromDiffuseTexture = false;
  33439. _this._useEmissiveAsIllumination = false;
  33440. _this._linkEmissiveWithDiffuse = false;
  33441. _this._useSpecularOverAlpha = false;
  33442. _this._useReflectionOverAlpha = false;
  33443. _this._disableLighting = false;
  33444. _this._useParallax = false;
  33445. _this._useParallaxOcclusion = false;
  33446. _this.parallaxScaleBias = 0.05;
  33447. _this._roughness = 0;
  33448. _this.indexOfRefraction = 0.98;
  33449. _this.invertRefractionY = true;
  33450. _this._useLightmapAsShadowmap = false;
  33451. _this._useReflectionFresnelFromSpecular = false;
  33452. _this._useGlossinessFromSpecularMapAlpha = false;
  33453. _this._maxSimultaneousLights = 4;
  33454. /**
  33455. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33456. */
  33457. _this._invertNormalMapX = false;
  33458. /**
  33459. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33460. */
  33461. _this._invertNormalMapY = false;
  33462. /**
  33463. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33464. */
  33465. _this._twoSidedLighting = false;
  33466. _this._renderTargets = new BABYLON.SmartArray(16);
  33467. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33468. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33469. // Setup the default processing configuration to the scene.
  33470. _this._attachImageProcessingConfiguration(null);
  33471. _this.getRenderTargetTextures = function () {
  33472. _this._renderTargets.reset();
  33473. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33474. _this._renderTargets.push(_this._reflectionTexture);
  33475. }
  33476. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33477. _this._renderTargets.push(_this._refractionTexture);
  33478. }
  33479. return _this._renderTargets;
  33480. };
  33481. return _this;
  33482. }
  33483. ;
  33484. ;
  33485. ;
  33486. ;
  33487. ;
  33488. ;
  33489. ;
  33490. ;
  33491. ;
  33492. ;
  33493. ;
  33494. ;
  33495. ;
  33496. ;
  33497. ;
  33498. ;
  33499. ;
  33500. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33501. /**
  33502. * Gets the image processing configuration used either in this material.
  33503. */
  33504. get: function () {
  33505. return this._imageProcessingConfiguration;
  33506. },
  33507. /**
  33508. * Sets the Default image processing configuration used either in the this material.
  33509. *
  33510. * If sets to null, the scene one is in use.
  33511. */
  33512. set: function (value) {
  33513. this._attachImageProcessingConfiguration(value);
  33514. // Ensure the effect will be rebuilt.
  33515. this._markAllSubMeshesAsTexturesDirty();
  33516. },
  33517. enumerable: true,
  33518. configurable: true
  33519. });
  33520. /**
  33521. * Attaches a new image processing configuration to the Standard Material.
  33522. * @param configuration
  33523. */
  33524. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33525. var _this = this;
  33526. if (configuration === this._imageProcessingConfiguration) {
  33527. return;
  33528. }
  33529. // Detaches observer.
  33530. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33531. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33532. }
  33533. // Pick the scene configuration if needed.
  33534. if (!configuration) {
  33535. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33536. }
  33537. else {
  33538. this._imageProcessingConfiguration = configuration;
  33539. }
  33540. // Attaches observer.
  33541. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33542. _this._markAllSubMeshesAsImageProcessingDirty();
  33543. });
  33544. };
  33545. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33546. /**
  33547. * Gets wether the color curves effect is enabled.
  33548. */
  33549. get: function () {
  33550. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33551. },
  33552. /**
  33553. * Sets wether the color curves effect is enabled.
  33554. */
  33555. set: function (value) {
  33556. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33557. },
  33558. enumerable: true,
  33559. configurable: true
  33560. });
  33561. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33562. /**
  33563. * Gets wether the color grading effect is enabled.
  33564. */
  33565. get: function () {
  33566. return this.imageProcessingConfiguration.colorGradingEnabled;
  33567. },
  33568. /**
  33569. * Gets wether the color grading effect is enabled.
  33570. */
  33571. set: function (value) {
  33572. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33573. },
  33574. enumerable: true,
  33575. configurable: true
  33576. });
  33577. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  33578. /**
  33579. * Gets wether tonemapping is enabled or not.
  33580. */
  33581. get: function () {
  33582. return this._imageProcessingConfiguration.toneMappingEnabled;
  33583. },
  33584. /**
  33585. * Sets wether tonemapping is enabled or not
  33586. */
  33587. set: function (value) {
  33588. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33589. },
  33590. enumerable: true,
  33591. configurable: true
  33592. });
  33593. ;
  33594. ;
  33595. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  33596. /**
  33597. * The camera exposure used on this material.
  33598. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33599. * This corresponds to a photographic exposure.
  33600. */
  33601. get: function () {
  33602. return this._imageProcessingConfiguration.exposure;
  33603. },
  33604. /**
  33605. * The camera exposure used on this material.
  33606. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33607. * This corresponds to a photographic exposure.
  33608. */
  33609. set: function (value) {
  33610. this._imageProcessingConfiguration.exposure = value;
  33611. },
  33612. enumerable: true,
  33613. configurable: true
  33614. });
  33615. ;
  33616. ;
  33617. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  33618. /**
  33619. * Gets The camera contrast used on this material.
  33620. */
  33621. get: function () {
  33622. return this._imageProcessingConfiguration.contrast;
  33623. },
  33624. /**
  33625. * Sets The camera contrast used on this material.
  33626. */
  33627. set: function (value) {
  33628. this._imageProcessingConfiguration.contrast = value;
  33629. },
  33630. enumerable: true,
  33631. configurable: true
  33632. });
  33633. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  33634. /**
  33635. * Gets the Color Grading 2D Lookup Texture.
  33636. */
  33637. get: function () {
  33638. return this._imageProcessingConfiguration.colorGradingTexture;
  33639. },
  33640. /**
  33641. * Sets the Color Grading 2D Lookup Texture.
  33642. */
  33643. set: function (value) {
  33644. this._imageProcessingConfiguration.colorGradingTexture = value;
  33645. },
  33646. enumerable: true,
  33647. configurable: true
  33648. });
  33649. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  33650. /**
  33651. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33652. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33653. * 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;
  33654. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33655. */
  33656. get: function () {
  33657. return this._imageProcessingConfiguration.colorCurves;
  33658. },
  33659. /**
  33660. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33661. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33662. * 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;
  33663. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33664. */
  33665. set: function (value) {
  33666. this._imageProcessingConfiguration.colorCurves = value;
  33667. },
  33668. enumerable: true,
  33669. configurable: true
  33670. });
  33671. StandardMaterial.prototype.getClassName = function () {
  33672. return "StandardMaterial";
  33673. };
  33674. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  33675. get: function () {
  33676. return this._useLogarithmicDepth;
  33677. },
  33678. set: function (value) {
  33679. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33680. this._markAllSubMeshesAsMiscDirty();
  33681. },
  33682. enumerable: true,
  33683. configurable: true
  33684. });
  33685. StandardMaterial.prototype.needAlphaBlending = function () {
  33686. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  33687. };
  33688. StandardMaterial.prototype.needAlphaTesting = function () {
  33689. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  33690. };
  33691. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  33692. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  33693. };
  33694. StandardMaterial.prototype.getAlphaTestTexture = function () {
  33695. return this._diffuseTexture;
  33696. };
  33697. /**
  33698. * Child classes can use it to update shaders
  33699. */
  33700. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33701. if (useInstances === void 0) { useInstances = false; }
  33702. if (subMesh.effect && this.isFrozen) {
  33703. if (this._wasPreviouslyReady && subMesh.effect) {
  33704. return true;
  33705. }
  33706. }
  33707. if (!subMesh._materialDefines) {
  33708. subMesh._materialDefines = new StandardMaterialDefines();
  33709. }
  33710. var scene = this.getScene();
  33711. var defines = subMesh._materialDefines;
  33712. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33713. if (defines._renderId === scene.getRenderId()) {
  33714. return true;
  33715. }
  33716. }
  33717. var engine = scene.getEngine();
  33718. // Lights
  33719. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33720. // Textures
  33721. if (defines._areTexturesDirty) {
  33722. defines._needUVs = false;
  33723. defines.MAINUV1 = false;
  33724. defines.MAINUV2 = false;
  33725. if (scene.texturesEnabled) {
  33726. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33727. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  33728. return false;
  33729. }
  33730. else {
  33731. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  33732. }
  33733. }
  33734. else {
  33735. defines.DIFFUSE = false;
  33736. }
  33737. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33738. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33739. return false;
  33740. }
  33741. else {
  33742. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33743. }
  33744. }
  33745. else {
  33746. defines.AMBIENT = false;
  33747. }
  33748. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33749. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33750. return false;
  33751. }
  33752. else {
  33753. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33754. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33755. }
  33756. }
  33757. else {
  33758. defines.OPACITY = false;
  33759. }
  33760. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33761. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  33762. return false;
  33763. }
  33764. else {
  33765. defines._needNormals = true;
  33766. defines.REFLECTION = true;
  33767. defines.ROUGHNESS = (this._roughness > 0);
  33768. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  33769. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  33770. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  33771. switch (this._reflectionTexture.coordinatesMode) {
  33772. case BABYLON.Texture.CUBIC_MODE:
  33773. case BABYLON.Texture.INVCUBIC_MODE:
  33774. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33775. break;
  33776. case BABYLON.Texture.EXPLICIT_MODE:
  33777. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33778. break;
  33779. case BABYLON.Texture.PLANAR_MODE:
  33780. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33781. break;
  33782. case BABYLON.Texture.PROJECTION_MODE:
  33783. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33784. break;
  33785. case BABYLON.Texture.SKYBOX_MODE:
  33786. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33787. break;
  33788. case BABYLON.Texture.SPHERICAL_MODE:
  33789. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33790. break;
  33791. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33792. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33793. break;
  33794. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33795. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33796. break;
  33797. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33798. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33799. break;
  33800. }
  33801. }
  33802. }
  33803. else {
  33804. defines.REFLECTION = false;
  33805. }
  33806. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33807. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33808. return false;
  33809. }
  33810. else {
  33811. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33812. }
  33813. }
  33814. else {
  33815. defines.EMISSIVE = false;
  33816. }
  33817. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33818. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33819. return false;
  33820. }
  33821. else {
  33822. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33823. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33824. }
  33825. }
  33826. else {
  33827. defines.LIGHTMAP = false;
  33828. }
  33829. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33830. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33831. return false;
  33832. }
  33833. else {
  33834. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33835. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33836. }
  33837. }
  33838. else {
  33839. defines.SPECULAR = false;
  33840. }
  33841. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33842. // Bump texure can not be not blocking.
  33843. if (!this._bumpTexture.isReady()) {
  33844. return false;
  33845. }
  33846. else {
  33847. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33848. defines.PARALLAX = this._useParallax;
  33849. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33850. }
  33851. }
  33852. else {
  33853. defines.BUMP = false;
  33854. }
  33855. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33856. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33857. return false;
  33858. }
  33859. else {
  33860. defines._needUVs = true;
  33861. defines.REFRACTION = true;
  33862. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33863. }
  33864. }
  33865. else {
  33866. defines.REFRACTION = false;
  33867. }
  33868. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33869. }
  33870. else {
  33871. defines.DIFFUSE = false;
  33872. defines.AMBIENT = false;
  33873. defines.OPACITY = false;
  33874. defines.REFLECTION = false;
  33875. defines.EMISSIVE = false;
  33876. defines.LIGHTMAP = false;
  33877. defines.BUMP = false;
  33878. defines.REFRACTION = false;
  33879. }
  33880. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33881. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33882. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33883. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33884. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33885. }
  33886. if (defines._areImageProcessingDirty) {
  33887. if (!this._imageProcessingConfiguration.isReady()) {
  33888. return false;
  33889. }
  33890. this._imageProcessingConfiguration.prepareDefines(defines);
  33891. }
  33892. if (defines._areFresnelDirty) {
  33893. if (StandardMaterial.FresnelEnabled) {
  33894. // Fresnel
  33895. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33896. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  33897. this._reflectionFresnelParameters) {
  33898. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  33899. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  33900. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  33901. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  33902. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  33903. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  33904. defines._needNormals = true;
  33905. defines.FRESNEL = true;
  33906. }
  33907. }
  33908. else {
  33909. defines.FRESNEL = false;
  33910. }
  33911. }
  33912. // Misc.
  33913. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  33914. // Attribs
  33915. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  33916. // Values that need to be evaluated on every frame
  33917. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  33918. // Get correct effect
  33919. if (defines.isDirty) {
  33920. defines.markAsProcessed();
  33921. scene.resetCachedMaterial();
  33922. // Fallbacks
  33923. var fallbacks = new BABYLON.EffectFallbacks();
  33924. if (defines.REFLECTION) {
  33925. fallbacks.addFallback(0, "REFLECTION");
  33926. }
  33927. if (defines.SPECULAR) {
  33928. fallbacks.addFallback(0, "SPECULAR");
  33929. }
  33930. if (defines.BUMP) {
  33931. fallbacks.addFallback(0, "BUMP");
  33932. }
  33933. if (defines.PARALLAX) {
  33934. fallbacks.addFallback(1, "PARALLAX");
  33935. }
  33936. if (defines.PARALLAXOCCLUSION) {
  33937. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  33938. }
  33939. if (defines.SPECULAROVERALPHA) {
  33940. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  33941. }
  33942. if (defines.FOG) {
  33943. fallbacks.addFallback(1, "FOG");
  33944. }
  33945. if (defines.POINTSIZE) {
  33946. fallbacks.addFallback(0, "POINTSIZE");
  33947. }
  33948. if (defines.LOGARITHMICDEPTH) {
  33949. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  33950. }
  33951. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  33952. if (defines.SPECULARTERM) {
  33953. fallbacks.addFallback(0, "SPECULARTERM");
  33954. }
  33955. if (defines.DIFFUSEFRESNEL) {
  33956. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  33957. }
  33958. if (defines.OPACITYFRESNEL) {
  33959. fallbacks.addFallback(2, "OPACITYFRESNEL");
  33960. }
  33961. if (defines.REFLECTIONFRESNEL) {
  33962. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  33963. }
  33964. if (defines.EMISSIVEFRESNEL) {
  33965. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  33966. }
  33967. if (defines.FRESNEL) {
  33968. fallbacks.addFallback(4, "FRESNEL");
  33969. }
  33970. //Attributes
  33971. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33972. if (defines.NORMAL) {
  33973. attribs.push(BABYLON.VertexBuffer.NormalKind);
  33974. }
  33975. if (defines.UV1) {
  33976. attribs.push(BABYLON.VertexBuffer.UVKind);
  33977. }
  33978. if (defines.UV2) {
  33979. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33980. }
  33981. if (defines.VERTEXCOLOR) {
  33982. attribs.push(BABYLON.VertexBuffer.ColorKind);
  33983. }
  33984. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  33985. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  33986. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  33987. var shaderName = "default";
  33988. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  33989. "vFogInfos", "vFogColor", "pointSize",
  33990. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  33991. "mBones",
  33992. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  33993. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  33994. "logarithmicDepthConstant", "vTangentSpaceParams"
  33995. ];
  33996. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  33997. var uniformBuffers = ["Material", "Scene"];
  33998. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  33999. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34000. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34001. uniformsNames: uniforms,
  34002. uniformBuffersNames: uniformBuffers,
  34003. samplers: samplers,
  34004. defines: defines,
  34005. maxSimultaneousLights: this._maxSimultaneousLights
  34006. });
  34007. if (this.customShaderNameResolve) {
  34008. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  34009. }
  34010. var join = defines.toString();
  34011. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  34012. attributes: attribs,
  34013. uniformsNames: uniforms,
  34014. uniformBuffersNames: uniformBuffers,
  34015. samplers: samplers,
  34016. defines: join,
  34017. fallbacks: fallbacks,
  34018. onCompiled: this.onCompiled,
  34019. onError: this.onError,
  34020. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34021. }, engine), defines);
  34022. this.buildUniformLayout();
  34023. }
  34024. if (!subMesh.effect || !subMesh.effect.isReady()) {
  34025. return false;
  34026. }
  34027. defines._renderId = scene.getRenderId();
  34028. this._wasPreviouslyReady = true;
  34029. return true;
  34030. };
  34031. StandardMaterial.prototype.buildUniformLayout = function () {
  34032. // Order is important !
  34033. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  34034. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  34035. this._uniformBuffer.addUniform("opacityParts", 4);
  34036. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  34037. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  34038. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  34039. this._uniformBuffer.addUniform("refractionRightColor", 4);
  34040. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  34041. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  34042. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  34043. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  34044. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34045. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34046. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34047. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34048. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  34049. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34050. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  34051. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34052. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34053. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34054. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34055. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34056. this._uniformBuffer.addUniform("specularMatrix", 16);
  34057. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34058. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34059. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34060. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34061. this._uniformBuffer.addUniform("vSpecularColor", 4);
  34062. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34063. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  34064. this._uniformBuffer.addUniform("pointSize", 1);
  34065. this._uniformBuffer.create();
  34066. };
  34067. StandardMaterial.prototype.unbind = function () {
  34068. if (this._activeEffect) {
  34069. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34070. this._activeEffect.setTexture("reflection2DSampler", null);
  34071. }
  34072. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34073. this._activeEffect.setTexture("refraction2DSampler", null);
  34074. }
  34075. }
  34076. _super.prototype.unbind.call(this);
  34077. };
  34078. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34079. var scene = this.getScene();
  34080. var defines = subMesh._materialDefines;
  34081. if (!defines) {
  34082. return;
  34083. }
  34084. var effect = subMesh.effect;
  34085. if (!effect) {
  34086. return;
  34087. }
  34088. this._activeEffect = effect;
  34089. // Matrices
  34090. this.bindOnlyWorldMatrix(world);
  34091. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34092. // Bones
  34093. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34094. if (mustRebind) {
  34095. this._uniformBuffer.bindToEffect(effect, "Material");
  34096. this.bindViewProjection(effect);
  34097. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34098. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34099. // Fresnel
  34100. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34101. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34102. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34103. }
  34104. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34105. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34106. }
  34107. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34108. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34109. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34110. }
  34111. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34112. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34113. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34114. }
  34115. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34116. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34117. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34118. }
  34119. }
  34120. // Textures
  34121. if (scene.texturesEnabled) {
  34122. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34123. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34124. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34125. }
  34126. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34127. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34128. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34129. }
  34130. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34131. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34132. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34133. }
  34134. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34135. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34136. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34137. }
  34138. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34139. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34140. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34141. }
  34142. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34143. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34144. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34145. }
  34146. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34147. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34148. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34149. }
  34150. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34151. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34152. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34153. if (scene._mirroredCameraPosition) {
  34154. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34155. }
  34156. else {
  34157. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34158. }
  34159. }
  34160. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34161. var depth = 1.0;
  34162. if (!this._refractionTexture.isCube) {
  34163. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34164. if (this._refractionTexture.depth) {
  34165. depth = this._refractionTexture.depth;
  34166. }
  34167. }
  34168. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34169. }
  34170. }
  34171. // Point size
  34172. if (this.pointsCloud) {
  34173. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34174. }
  34175. if (defines.SPECULARTERM) {
  34176. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34177. }
  34178. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34179. // Diffuse
  34180. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34181. }
  34182. // Textures
  34183. if (scene.texturesEnabled) {
  34184. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34185. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34186. }
  34187. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34188. effect.setTexture("ambientSampler", this._ambientTexture);
  34189. }
  34190. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34191. effect.setTexture("opacitySampler", this._opacityTexture);
  34192. }
  34193. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34194. if (this._reflectionTexture.isCube) {
  34195. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34196. }
  34197. else {
  34198. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34199. }
  34200. }
  34201. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34202. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34203. }
  34204. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34205. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34206. }
  34207. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34208. effect.setTexture("specularSampler", this._specularTexture);
  34209. }
  34210. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34211. effect.setTexture("bumpSampler", this._bumpTexture);
  34212. }
  34213. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34214. var depth = 1.0;
  34215. if (this._refractionTexture.isCube) {
  34216. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34217. }
  34218. else {
  34219. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34220. }
  34221. }
  34222. }
  34223. // Clip plane
  34224. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34225. // Colors
  34226. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34227. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34228. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34229. }
  34230. if (mustRebind || !this.isFrozen) {
  34231. // Lights
  34232. if (scene.lightsEnabled && !this._disableLighting) {
  34233. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34234. }
  34235. // View
  34236. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34237. this.bindView(effect);
  34238. }
  34239. // Fog
  34240. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34241. // Morph targets
  34242. if (defines.NUM_MORPH_INFLUENCERS) {
  34243. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34244. }
  34245. // Log. depth
  34246. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34247. // image processing
  34248. this._imageProcessingConfiguration.bind(this._activeEffect);
  34249. }
  34250. this._uniformBuffer.update();
  34251. this._afterBind(mesh, this._activeEffect);
  34252. };
  34253. StandardMaterial.prototype.getAnimatables = function () {
  34254. var results = [];
  34255. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34256. results.push(this._diffuseTexture);
  34257. }
  34258. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34259. results.push(this._ambientTexture);
  34260. }
  34261. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34262. results.push(this._opacityTexture);
  34263. }
  34264. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34265. results.push(this._reflectionTexture);
  34266. }
  34267. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34268. results.push(this._emissiveTexture);
  34269. }
  34270. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34271. results.push(this._specularTexture);
  34272. }
  34273. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34274. results.push(this._bumpTexture);
  34275. }
  34276. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34277. results.push(this._lightmapTexture);
  34278. }
  34279. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34280. results.push(this._refractionTexture);
  34281. }
  34282. return results;
  34283. };
  34284. StandardMaterial.prototype.getActiveTextures = function () {
  34285. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34286. if (this._diffuseTexture) {
  34287. activeTextures.push(this._diffuseTexture);
  34288. }
  34289. if (this._ambientTexture) {
  34290. activeTextures.push(this._ambientTexture);
  34291. }
  34292. if (this._opacityTexture) {
  34293. activeTextures.push(this._opacityTexture);
  34294. }
  34295. if (this._reflectionTexture) {
  34296. activeTextures.push(this._reflectionTexture);
  34297. }
  34298. if (this._emissiveTexture) {
  34299. activeTextures.push(this._emissiveTexture);
  34300. }
  34301. if (this._specularTexture) {
  34302. activeTextures.push(this._specularTexture);
  34303. }
  34304. if (this._bumpTexture) {
  34305. activeTextures.push(this._bumpTexture);
  34306. }
  34307. if (this._lightmapTexture) {
  34308. activeTextures.push(this._lightmapTexture);
  34309. }
  34310. if (this._refractionTexture) {
  34311. activeTextures.push(this._refractionTexture);
  34312. }
  34313. return activeTextures;
  34314. };
  34315. StandardMaterial.prototype.hasTexture = function (texture) {
  34316. if (_super.prototype.hasTexture.call(this, texture)) {
  34317. return true;
  34318. }
  34319. if (this._diffuseTexture === texture) {
  34320. return true;
  34321. }
  34322. if (this._ambientTexture === texture) {
  34323. return true;
  34324. }
  34325. if (this._opacityTexture === texture) {
  34326. return true;
  34327. }
  34328. if (this._reflectionTexture === texture) {
  34329. return true;
  34330. }
  34331. if (this._emissiveTexture === texture) {
  34332. return true;
  34333. }
  34334. if (this._specularTexture === texture) {
  34335. return true;
  34336. }
  34337. if (this._bumpTexture === texture) {
  34338. return true;
  34339. }
  34340. if (this._lightmapTexture === texture) {
  34341. return true;
  34342. }
  34343. if (this._refractionTexture === texture) {
  34344. return true;
  34345. }
  34346. return false;
  34347. };
  34348. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34349. if (forceDisposeTextures) {
  34350. if (this._diffuseTexture) {
  34351. this._diffuseTexture.dispose();
  34352. }
  34353. if (this._ambientTexture) {
  34354. this._ambientTexture.dispose();
  34355. }
  34356. if (this._opacityTexture) {
  34357. this._opacityTexture.dispose();
  34358. }
  34359. if (this._reflectionTexture) {
  34360. this._reflectionTexture.dispose();
  34361. }
  34362. if (this._emissiveTexture) {
  34363. this._emissiveTexture.dispose();
  34364. }
  34365. if (this._specularTexture) {
  34366. this._specularTexture.dispose();
  34367. }
  34368. if (this._bumpTexture) {
  34369. this._bumpTexture.dispose();
  34370. }
  34371. if (this._lightmapTexture) {
  34372. this._lightmapTexture.dispose();
  34373. }
  34374. if (this._refractionTexture) {
  34375. this._refractionTexture.dispose();
  34376. }
  34377. }
  34378. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34379. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34380. }
  34381. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34382. };
  34383. StandardMaterial.prototype.clone = function (name) {
  34384. var _this = this;
  34385. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34386. result.name = name;
  34387. result.id = name;
  34388. return result;
  34389. };
  34390. StandardMaterial.prototype.serialize = function () {
  34391. return BABYLON.SerializationHelper.Serialize(this);
  34392. };
  34393. // Statics
  34394. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34395. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34396. };
  34397. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34398. get: function () {
  34399. return StandardMaterial._DiffuseTextureEnabled;
  34400. },
  34401. set: function (value) {
  34402. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34403. return;
  34404. }
  34405. StandardMaterial._DiffuseTextureEnabled = value;
  34406. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34407. },
  34408. enumerable: true,
  34409. configurable: true
  34410. });
  34411. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34412. get: function () {
  34413. return StandardMaterial._AmbientTextureEnabled;
  34414. },
  34415. set: function (value) {
  34416. if (StandardMaterial._AmbientTextureEnabled === value) {
  34417. return;
  34418. }
  34419. StandardMaterial._AmbientTextureEnabled = value;
  34420. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34421. },
  34422. enumerable: true,
  34423. configurable: true
  34424. });
  34425. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34426. get: function () {
  34427. return StandardMaterial._OpacityTextureEnabled;
  34428. },
  34429. set: function (value) {
  34430. if (StandardMaterial._OpacityTextureEnabled === value) {
  34431. return;
  34432. }
  34433. StandardMaterial._OpacityTextureEnabled = value;
  34434. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34435. },
  34436. enumerable: true,
  34437. configurable: true
  34438. });
  34439. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34440. get: function () {
  34441. return StandardMaterial._ReflectionTextureEnabled;
  34442. },
  34443. set: function (value) {
  34444. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34445. return;
  34446. }
  34447. StandardMaterial._ReflectionTextureEnabled = value;
  34448. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34449. },
  34450. enumerable: true,
  34451. configurable: true
  34452. });
  34453. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34454. get: function () {
  34455. return StandardMaterial._EmissiveTextureEnabled;
  34456. },
  34457. set: function (value) {
  34458. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34459. return;
  34460. }
  34461. StandardMaterial._EmissiveTextureEnabled = value;
  34462. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34463. },
  34464. enumerable: true,
  34465. configurable: true
  34466. });
  34467. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34468. get: function () {
  34469. return StandardMaterial._SpecularTextureEnabled;
  34470. },
  34471. set: function (value) {
  34472. if (StandardMaterial._SpecularTextureEnabled === value) {
  34473. return;
  34474. }
  34475. StandardMaterial._SpecularTextureEnabled = value;
  34476. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34477. },
  34478. enumerable: true,
  34479. configurable: true
  34480. });
  34481. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34482. get: function () {
  34483. return StandardMaterial._BumpTextureEnabled;
  34484. },
  34485. set: function (value) {
  34486. if (StandardMaterial._BumpTextureEnabled === value) {
  34487. return;
  34488. }
  34489. StandardMaterial._BumpTextureEnabled = value;
  34490. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34491. },
  34492. enumerable: true,
  34493. configurable: true
  34494. });
  34495. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34496. get: function () {
  34497. return StandardMaterial._LightmapTextureEnabled;
  34498. },
  34499. set: function (value) {
  34500. if (StandardMaterial._LightmapTextureEnabled === value) {
  34501. return;
  34502. }
  34503. StandardMaterial._LightmapTextureEnabled = value;
  34504. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34505. },
  34506. enumerable: true,
  34507. configurable: true
  34508. });
  34509. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34510. get: function () {
  34511. return StandardMaterial._RefractionTextureEnabled;
  34512. },
  34513. set: function (value) {
  34514. if (StandardMaterial._RefractionTextureEnabled === value) {
  34515. return;
  34516. }
  34517. StandardMaterial._RefractionTextureEnabled = value;
  34518. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34519. },
  34520. enumerable: true,
  34521. configurable: true
  34522. });
  34523. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34524. get: function () {
  34525. return StandardMaterial._ColorGradingTextureEnabled;
  34526. },
  34527. set: function (value) {
  34528. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34529. return;
  34530. }
  34531. StandardMaterial._ColorGradingTextureEnabled = value;
  34532. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34533. },
  34534. enumerable: true,
  34535. configurable: true
  34536. });
  34537. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34538. get: function () {
  34539. return StandardMaterial._FresnelEnabled;
  34540. },
  34541. set: function (value) {
  34542. if (StandardMaterial._FresnelEnabled === value) {
  34543. return;
  34544. }
  34545. StandardMaterial._FresnelEnabled = value;
  34546. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34547. },
  34548. enumerable: true,
  34549. configurable: true
  34550. });
  34551. // Flags used to enable or disable a type of texture for all Standard Materials
  34552. StandardMaterial._DiffuseTextureEnabled = true;
  34553. StandardMaterial._AmbientTextureEnabled = true;
  34554. StandardMaterial._OpacityTextureEnabled = true;
  34555. StandardMaterial._ReflectionTextureEnabled = true;
  34556. StandardMaterial._EmissiveTextureEnabled = true;
  34557. StandardMaterial._SpecularTextureEnabled = true;
  34558. StandardMaterial._BumpTextureEnabled = true;
  34559. StandardMaterial._LightmapTextureEnabled = true;
  34560. StandardMaterial._RefractionTextureEnabled = true;
  34561. StandardMaterial._ColorGradingTextureEnabled = true;
  34562. StandardMaterial._FresnelEnabled = true;
  34563. __decorate([
  34564. BABYLON.serializeAsTexture("diffuseTexture")
  34565. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34566. __decorate([
  34567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34568. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34569. __decorate([
  34570. BABYLON.serializeAsTexture("ambientTexture")
  34571. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  34572. __decorate([
  34573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34574. ], StandardMaterial.prototype, "ambientTexture", void 0);
  34575. __decorate([
  34576. BABYLON.serializeAsTexture("opacityTexture")
  34577. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  34578. __decorate([
  34579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34580. ], StandardMaterial.prototype, "opacityTexture", void 0);
  34581. __decorate([
  34582. BABYLON.serializeAsTexture("reflectionTexture")
  34583. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  34584. __decorate([
  34585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34586. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  34587. __decorate([
  34588. BABYLON.serializeAsTexture("emissiveTexture")
  34589. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  34590. __decorate([
  34591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34592. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  34593. __decorate([
  34594. BABYLON.serializeAsTexture("specularTexture")
  34595. ], StandardMaterial.prototype, "_specularTexture", void 0);
  34596. __decorate([
  34597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34598. ], StandardMaterial.prototype, "specularTexture", void 0);
  34599. __decorate([
  34600. BABYLON.serializeAsTexture("bumpTexture")
  34601. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  34602. __decorate([
  34603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34604. ], StandardMaterial.prototype, "bumpTexture", void 0);
  34605. __decorate([
  34606. BABYLON.serializeAsTexture("lightmapTexture")
  34607. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  34608. __decorate([
  34609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34610. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  34611. __decorate([
  34612. BABYLON.serializeAsTexture("refractionTexture")
  34613. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  34614. __decorate([
  34615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34616. ], StandardMaterial.prototype, "refractionTexture", void 0);
  34617. __decorate([
  34618. BABYLON.serializeAsColor3("ambient")
  34619. ], StandardMaterial.prototype, "ambientColor", void 0);
  34620. __decorate([
  34621. BABYLON.serializeAsColor3("diffuse")
  34622. ], StandardMaterial.prototype, "diffuseColor", void 0);
  34623. __decorate([
  34624. BABYLON.serializeAsColor3("specular")
  34625. ], StandardMaterial.prototype, "specularColor", void 0);
  34626. __decorate([
  34627. BABYLON.serializeAsColor3("emissive")
  34628. ], StandardMaterial.prototype, "emissiveColor", void 0);
  34629. __decorate([
  34630. BABYLON.serialize()
  34631. ], StandardMaterial.prototype, "specularPower", void 0);
  34632. __decorate([
  34633. BABYLON.serialize("useAlphaFromDiffuseTexture")
  34634. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  34635. __decorate([
  34636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34637. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  34638. __decorate([
  34639. BABYLON.serialize("useEmissiveAsIllumination")
  34640. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  34641. __decorate([
  34642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34643. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  34644. __decorate([
  34645. BABYLON.serialize("linkEmissiveWithDiffuse")
  34646. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  34647. __decorate([
  34648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34649. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  34650. __decorate([
  34651. BABYLON.serialize("useSpecularOverAlpha")
  34652. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  34653. __decorate([
  34654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34655. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  34656. __decorate([
  34657. BABYLON.serialize("useReflectionOverAlpha")
  34658. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  34659. __decorate([
  34660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34661. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  34662. __decorate([
  34663. BABYLON.serialize("disableLighting")
  34664. ], StandardMaterial.prototype, "_disableLighting", void 0);
  34665. __decorate([
  34666. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34667. ], StandardMaterial.prototype, "disableLighting", void 0);
  34668. __decorate([
  34669. BABYLON.serialize("useParallax")
  34670. ], StandardMaterial.prototype, "_useParallax", void 0);
  34671. __decorate([
  34672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34673. ], StandardMaterial.prototype, "useParallax", void 0);
  34674. __decorate([
  34675. BABYLON.serialize("useParallaxOcclusion")
  34676. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  34677. __decorate([
  34678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34679. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  34680. __decorate([
  34681. BABYLON.serialize()
  34682. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  34683. __decorate([
  34684. BABYLON.serialize("roughness")
  34685. ], StandardMaterial.prototype, "_roughness", void 0);
  34686. __decorate([
  34687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34688. ], StandardMaterial.prototype, "roughness", void 0);
  34689. __decorate([
  34690. BABYLON.serialize()
  34691. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  34692. __decorate([
  34693. BABYLON.serialize()
  34694. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  34695. __decorate([
  34696. BABYLON.serialize("useLightmapAsShadowmap")
  34697. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  34698. __decorate([
  34699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34700. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34701. __decorate([
  34702. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  34703. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  34704. __decorate([
  34705. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34706. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  34707. __decorate([
  34708. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  34709. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  34710. __decorate([
  34711. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34712. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  34713. __decorate([
  34714. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  34715. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  34716. __decorate([
  34717. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34718. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  34719. __decorate([
  34720. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  34721. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  34722. __decorate([
  34723. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34724. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  34725. __decorate([
  34726. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  34727. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  34728. __decorate([
  34729. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34730. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  34731. __decorate([
  34732. BABYLON.serialize("useReflectionFresnelFromSpecular")
  34733. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  34734. __decorate([
  34735. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34736. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  34737. __decorate([
  34738. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  34739. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  34740. __decorate([
  34741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34742. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  34743. __decorate([
  34744. BABYLON.serialize("maxSimultaneousLights")
  34745. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  34746. __decorate([
  34747. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34748. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  34749. __decorate([
  34750. BABYLON.serialize("invertNormalMapX")
  34751. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  34752. __decorate([
  34753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34754. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  34755. __decorate([
  34756. BABYLON.serialize("invertNormalMapY")
  34757. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  34758. __decorate([
  34759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34760. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  34761. __decorate([
  34762. BABYLON.serialize("twoSidedLighting")
  34763. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  34764. __decorate([
  34765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34766. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  34767. __decorate([
  34768. BABYLON.serialize()
  34769. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  34770. return StandardMaterial;
  34771. }(BABYLON.PushMaterial));
  34772. BABYLON.StandardMaterial = StandardMaterial;
  34773. })(BABYLON || (BABYLON = {}));
  34774. //# sourceMappingURL=babylon.standardMaterial.js.map
  34775. var BABYLON;
  34776. (function (BABYLON) {
  34777. var PBRMaterialDefines = /** @class */ (function (_super) {
  34778. __extends(PBRMaterialDefines, _super);
  34779. function PBRMaterialDefines() {
  34780. var _this = _super.call(this) || this;
  34781. _this.PBR = true;
  34782. _this.MAINUV1 = false;
  34783. _this.MAINUV2 = false;
  34784. _this.UV1 = false;
  34785. _this.UV2 = false;
  34786. _this.ALBEDO = false;
  34787. _this.ALBEDODIRECTUV = 0;
  34788. _this.VERTEXCOLOR = false;
  34789. _this.AMBIENT = false;
  34790. _this.AMBIENTDIRECTUV = 0;
  34791. _this.AMBIENTINGRAYSCALE = false;
  34792. _this.OPACITY = false;
  34793. _this.VERTEXALPHA = false;
  34794. _this.OPACITYDIRECTUV = 0;
  34795. _this.OPACITYRGB = false;
  34796. _this.ALPHATEST = false;
  34797. _this.DEPTHPREPASS = false;
  34798. _this.ALPHABLEND = false;
  34799. _this.ALPHAFROMALBEDO = false;
  34800. _this.ALPHATESTVALUE = 0.5;
  34801. _this.SPECULAROVERALPHA = false;
  34802. _this.RADIANCEOVERALPHA = false;
  34803. _this.ALPHAFRESNEL = false;
  34804. _this.PREMULTIPLYALPHA = false;
  34805. _this.EMISSIVE = false;
  34806. _this.EMISSIVEDIRECTUV = 0;
  34807. _this.REFLECTIVITY = false;
  34808. _this.REFLECTIVITYDIRECTUV = 0;
  34809. _this.SPECULARTERM = false;
  34810. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34811. _this.MICROSURFACEAUTOMATIC = false;
  34812. _this.LODBASEDMICROSFURACE = false;
  34813. _this.MICROSURFACEMAP = false;
  34814. _this.MICROSURFACEMAPDIRECTUV = 0;
  34815. _this.METALLICWORKFLOW = false;
  34816. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34817. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34818. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34819. _this.AOSTOREINMETALMAPRED = false;
  34820. _this.ENVIRONMENTBRDF = false;
  34821. _this.NORMAL = false;
  34822. _this.TANGENT = false;
  34823. _this.BUMP = false;
  34824. _this.BUMPDIRECTUV = 0;
  34825. _this.PARALLAX = false;
  34826. _this.PARALLAXOCCLUSION = false;
  34827. _this.NORMALXYSCALE = true;
  34828. _this.LIGHTMAP = false;
  34829. _this.LIGHTMAPDIRECTUV = 0;
  34830. _this.USELIGHTMAPASSHADOWMAP = false;
  34831. _this.REFLECTION = false;
  34832. _this.REFLECTIONMAP_3D = false;
  34833. _this.REFLECTIONMAP_SPHERICAL = false;
  34834. _this.REFLECTIONMAP_PLANAR = false;
  34835. _this.REFLECTIONMAP_CUBIC = false;
  34836. _this.REFLECTIONMAP_PROJECTION = false;
  34837. _this.REFLECTIONMAP_SKYBOX = false;
  34838. _this.REFLECTIONMAP_EXPLICIT = false;
  34839. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34840. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34841. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34842. _this.INVERTCUBICMAP = false;
  34843. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34844. _this.USESPHERICALINVERTEX = false;
  34845. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34846. _this.LODINREFLECTIONALPHA = false;
  34847. _this.GAMMAREFLECTION = false;
  34848. _this.REFRACTION = false;
  34849. _this.REFRACTIONMAP_3D = false;
  34850. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34851. _this.LODINREFRACTIONALPHA = false;
  34852. _this.GAMMAREFRACTION = false;
  34853. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34854. _this.INSTANCES = false;
  34855. _this.NUM_BONE_INFLUENCERS = 0;
  34856. _this.BonesPerMesh = 0;
  34857. _this.NONUNIFORMSCALING = false;
  34858. _this.MORPHTARGETS = false;
  34859. _this.MORPHTARGETS_NORMAL = false;
  34860. _this.MORPHTARGETS_TANGENT = false;
  34861. _this.NUM_MORPH_INFLUENCERS = 0;
  34862. _this.IMAGEPROCESSING = false;
  34863. _this.VIGNETTE = false;
  34864. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34865. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34866. _this.TONEMAPPING = false;
  34867. _this.CONTRAST = false;
  34868. _this.COLORCURVES = false;
  34869. _this.COLORGRADING = false;
  34870. _this.COLORGRADING3D = false;
  34871. _this.SAMPLER3DGREENDEPTH = false;
  34872. _this.SAMPLER3DBGRMAP = false;
  34873. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34874. _this.EXPOSURE = false;
  34875. _this.USEPHYSICALLIGHTFALLOFF = false;
  34876. _this.TWOSIDEDLIGHTING = false;
  34877. _this.SHADOWFLOAT = false;
  34878. _this.CLIPPLANE = false;
  34879. _this.POINTSIZE = false;
  34880. _this.FOG = false;
  34881. _this.LOGARITHMICDEPTH = false;
  34882. _this.FORCENORMALFORWARD = false;
  34883. _this.rebuild();
  34884. return _this;
  34885. }
  34886. PBRMaterialDefines.prototype.reset = function () {
  34887. _super.prototype.reset.call(this);
  34888. this.ALPHATESTVALUE = 0.5;
  34889. this.PBR = true;
  34890. };
  34891. return PBRMaterialDefines;
  34892. }(BABYLON.MaterialDefines));
  34893. /**
  34894. * The Physically based material base class of BJS.
  34895. *
  34896. * This offers the main features of a standard PBR material.
  34897. * For more information, please refer to the documentation :
  34898. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34899. */
  34900. var PBRBaseMaterial = /** @class */ (function (_super) {
  34901. __extends(PBRBaseMaterial, _super);
  34902. /**
  34903. * Instantiates a new PBRMaterial instance.
  34904. *
  34905. * @param name The material name
  34906. * @param scene The scene the material will be use in.
  34907. */
  34908. function PBRBaseMaterial(name, scene) {
  34909. var _this = _super.call(this, name, scene) || this;
  34910. /**
  34911. * Intensity of the direct lights e.g. the four lights available in your scene.
  34912. * This impacts both the direct diffuse and specular highlights.
  34913. */
  34914. _this._directIntensity = 1.0;
  34915. /**
  34916. * Intensity of the emissive part of the material.
  34917. * This helps controlling the emissive effect without modifying the emissive color.
  34918. */
  34919. _this._emissiveIntensity = 1.0;
  34920. /**
  34921. * Intensity of the environment e.g. how much the environment will light the object
  34922. * either through harmonics for rough material or through the refelction for shiny ones.
  34923. */
  34924. _this._environmentIntensity = 1.0;
  34925. /**
  34926. * This is a special control allowing the reduction of the specular highlights coming from the
  34927. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34928. */
  34929. _this._specularIntensity = 1.0;
  34930. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34931. /**
  34932. * Debug Control allowing disabling the bump map on this material.
  34933. */
  34934. _this._disableBumpMap = false;
  34935. /**
  34936. * AKA Occlusion Texture Intensity in other nomenclature.
  34937. */
  34938. _this._ambientTextureStrength = 1.0;
  34939. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34940. /**
  34941. * AKA Diffuse Color in other nomenclature.
  34942. */
  34943. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34944. /**
  34945. * AKA Specular Color in other nomenclature.
  34946. */
  34947. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34948. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  34949. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34950. /**
  34951. * AKA Glossiness in other nomenclature.
  34952. */
  34953. _this._microSurface = 0.9;
  34954. /**
  34955. * source material index of refraction (IOR)' / 'destination material IOR.
  34956. */
  34957. _this._indexOfRefraction = 0.66;
  34958. /**
  34959. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34960. */
  34961. _this._invertRefractionY = false;
  34962. /**
  34963. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34964. * Materials half opaque for instance using refraction could benefit from this control.
  34965. */
  34966. _this._linkRefractionWithTransparency = false;
  34967. _this._useLightmapAsShadowmap = false;
  34968. /**
  34969. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  34970. */
  34971. _this._useAlphaFromAlbedoTexture = false;
  34972. /**
  34973. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34974. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34975. */
  34976. _this._useSpecularOverAlpha = true;
  34977. /**
  34978. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34979. */
  34980. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34981. /**
  34982. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34983. */
  34984. _this._useRoughnessFromMetallicTextureAlpha = true;
  34985. /**
  34986. * Specifies if the metallic texture contains the roughness information in its green channel.
  34987. */
  34988. _this._useRoughnessFromMetallicTextureGreen = false;
  34989. /**
  34990. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34991. */
  34992. _this._useMetallnessFromMetallicTextureBlue = false;
  34993. /**
  34994. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34995. */
  34996. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34997. /**
  34998. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34999. */
  35000. _this._useAmbientInGrayScale = false;
  35001. /**
  35002. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35003. * The material will try to infer what glossiness each pixel should be.
  35004. */
  35005. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  35006. /**
  35007. * BJS is using an harcoded light falloff based on a manually sets up range.
  35008. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35009. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35010. */
  35011. _this._usePhysicalLightFalloff = true;
  35012. /**
  35013. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35014. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35015. */
  35016. _this._useRadianceOverAlpha = true;
  35017. /**
  35018. * Allows using the bump map in parallax mode.
  35019. */
  35020. _this._useParallax = false;
  35021. /**
  35022. * Allows using the bump map in parallax occlusion mode.
  35023. */
  35024. _this._useParallaxOcclusion = false;
  35025. /**
  35026. * Controls the scale bias of the parallax mode.
  35027. */
  35028. _this._parallaxScaleBias = 0.05;
  35029. /**
  35030. * If sets to true, disables all the lights affecting the material.
  35031. */
  35032. _this._disableLighting = false;
  35033. /**
  35034. * Number of Simultaneous lights allowed on the material.
  35035. */
  35036. _this._maxSimultaneousLights = 4;
  35037. /**
  35038. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  35039. */
  35040. _this._invertNormalMapX = false;
  35041. /**
  35042. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  35043. */
  35044. _this._invertNormalMapY = false;
  35045. /**
  35046. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35047. */
  35048. _this._twoSidedLighting = false;
  35049. /**
  35050. * Defines the alpha limits in alpha test mode.
  35051. */
  35052. _this._alphaCutOff = 0.4;
  35053. /**
  35054. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35055. */
  35056. _this._forceAlphaTest = false;
  35057. /**
  35058. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35059. * And/Or occlude the blended part.
  35060. */
  35061. _this._useAlphaFresnel = false;
  35062. /**
  35063. * The transparency mode of the material.
  35064. */
  35065. _this._transparencyMode = null;
  35066. /**
  35067. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  35068. * from cos thetav and roughness:
  35069. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  35070. */
  35071. _this._environmentBRDFTexture = null;
  35072. /**
  35073. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35074. */
  35075. _this._forceIrradianceInFragment = false;
  35076. /**
  35077. * Force normal to face away from face.
  35078. * (Temporary internal fix to remove before 3.1)
  35079. */
  35080. _this._forceNormalForward = false;
  35081. _this._renderTargets = new BABYLON.SmartArray(16);
  35082. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35083. // Setup the default processing configuration to the scene.
  35084. _this._attachImageProcessingConfiguration(null);
  35085. _this.getRenderTargetTextures = function () {
  35086. _this._renderTargets.reset();
  35087. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35088. _this._renderTargets.push(_this._reflectionTexture);
  35089. }
  35090. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35091. _this._renderTargets.push(_this._refractionTexture);
  35092. }
  35093. return _this._renderTargets;
  35094. };
  35095. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35096. return _this;
  35097. }
  35098. /**
  35099. * Attaches a new image processing configuration to the PBR Material.
  35100. * @param configuration
  35101. */
  35102. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35103. var _this = this;
  35104. if (configuration === this._imageProcessingConfiguration) {
  35105. return;
  35106. }
  35107. // Detaches observer.
  35108. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35109. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35110. }
  35111. // Pick the scene configuration if needed.
  35112. if (!configuration) {
  35113. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35114. }
  35115. else {
  35116. this._imageProcessingConfiguration = configuration;
  35117. }
  35118. // Attaches observer.
  35119. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35120. _this._markAllSubMeshesAsImageProcessingDirty();
  35121. });
  35122. };
  35123. PBRBaseMaterial.prototype.getClassName = function () {
  35124. return "PBRBaseMaterial";
  35125. };
  35126. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35127. get: function () {
  35128. return this._useLogarithmicDepth;
  35129. },
  35130. set: function (value) {
  35131. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35132. },
  35133. enumerable: true,
  35134. configurable: true
  35135. });
  35136. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  35137. /**
  35138. * Gets the current transparency mode.
  35139. */
  35140. get: function () {
  35141. return this._transparencyMode;
  35142. },
  35143. /**
  35144. * Sets the transparency mode of the material.
  35145. */
  35146. set: function (value) {
  35147. if (this._transparencyMode === value) {
  35148. return;
  35149. }
  35150. this._transparencyMode = value;
  35151. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  35152. this._markAllSubMeshesAsTexturesDirty();
  35153. },
  35154. enumerable: true,
  35155. configurable: true
  35156. });
  35157. /**
  35158. * Specifies whether or not the meshes using this material should be rendered in alpha blend mode.
  35159. */
  35160. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35161. if (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35162. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST) {
  35163. return false;
  35164. }
  35165. return _super.prototype.needAlphaBlending.call(this);
  35166. };
  35167. /**
  35168. * Specifies whether or not the meshes using this material should be rendered in alpha blend mode.
  35169. */
  35170. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  35171. if (this._linkRefractionWithTransparency) {
  35172. return false;
  35173. }
  35174. if (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35175. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST) {
  35176. return false;
  35177. }
  35178. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35179. };
  35180. /**
  35181. * Specifies whether or not the meshes using this material should be rendered in alpha test mode.
  35182. */
  35183. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35184. if (this._forceAlphaTest) {
  35185. return true;
  35186. }
  35187. if (this._linkRefractionWithTransparency) {
  35188. return false;
  35189. }
  35190. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35191. };
  35192. /**
  35193. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  35194. */
  35195. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35196. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35197. };
  35198. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35199. return this._albedoTexture;
  35200. };
  35201. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35202. var _this = this;
  35203. if (subMesh.effect && this.isFrozen) {
  35204. if (this._wasPreviouslyReady) {
  35205. return true;
  35206. }
  35207. }
  35208. if (!subMesh._materialDefines) {
  35209. subMesh._materialDefines = new PBRMaterialDefines();
  35210. }
  35211. var scene = this.getScene();
  35212. var defines = subMesh._materialDefines;
  35213. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35214. if (defines._renderId === scene.getRenderId()) {
  35215. return true;
  35216. }
  35217. }
  35218. var engine = scene.getEngine();
  35219. // Lights
  35220. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35221. defines._needNormals = true;
  35222. // Textures
  35223. if (defines._areTexturesDirty) {
  35224. defines._needUVs = false;
  35225. if (scene.texturesEnabled) {
  35226. if (scene.getEngine().getCaps().textureLOD) {
  35227. defines.LODBASEDMICROSFURACE = true;
  35228. }
  35229. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35230. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35231. return false;
  35232. }
  35233. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35234. }
  35235. else {
  35236. defines.ALBEDO = false;
  35237. }
  35238. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35239. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35240. return false;
  35241. }
  35242. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35243. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35244. }
  35245. else {
  35246. defines.AMBIENT = false;
  35247. }
  35248. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35249. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35250. return false;
  35251. }
  35252. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35253. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35254. }
  35255. else {
  35256. defines.OPACITY = false;
  35257. }
  35258. var reflectionTexture = this._getReflectionTexture();
  35259. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35260. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35261. return false;
  35262. }
  35263. defines.REFLECTION = true;
  35264. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35265. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35266. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35267. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35268. defines.INVERTCUBICMAP = true;
  35269. }
  35270. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35271. switch (reflectionTexture.coordinatesMode) {
  35272. case BABYLON.Texture.CUBIC_MODE:
  35273. case BABYLON.Texture.INVCUBIC_MODE:
  35274. defines.REFLECTIONMAP_CUBIC = true;
  35275. break;
  35276. case BABYLON.Texture.EXPLICIT_MODE:
  35277. defines.REFLECTIONMAP_EXPLICIT = true;
  35278. break;
  35279. case BABYLON.Texture.PLANAR_MODE:
  35280. defines.REFLECTIONMAP_PLANAR = true;
  35281. break;
  35282. case BABYLON.Texture.PROJECTION_MODE:
  35283. defines.REFLECTIONMAP_PROJECTION = true;
  35284. break;
  35285. case BABYLON.Texture.SKYBOX_MODE:
  35286. defines.REFLECTIONMAP_SKYBOX = true;
  35287. break;
  35288. case BABYLON.Texture.SPHERICAL_MODE:
  35289. defines.REFLECTIONMAP_SPHERICAL = true;
  35290. break;
  35291. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35292. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35293. break;
  35294. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35295. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35296. break;
  35297. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35298. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35299. break;
  35300. }
  35301. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35302. if (reflectionTexture.sphericalPolynomial) {
  35303. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35304. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35305. defines.USESPHERICALINVERTEX = false;
  35306. }
  35307. else {
  35308. defines.USESPHERICALINVERTEX = true;
  35309. }
  35310. }
  35311. }
  35312. }
  35313. else {
  35314. defines.REFLECTION = false;
  35315. defines.REFLECTIONMAP_3D = false;
  35316. defines.REFLECTIONMAP_SPHERICAL = false;
  35317. defines.REFLECTIONMAP_PLANAR = false;
  35318. defines.REFLECTIONMAP_CUBIC = false;
  35319. defines.REFLECTIONMAP_PROJECTION = false;
  35320. defines.REFLECTIONMAP_SKYBOX = false;
  35321. defines.REFLECTIONMAP_EXPLICIT = false;
  35322. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35323. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35324. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35325. defines.INVERTCUBICMAP = false;
  35326. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35327. defines.USESPHERICALINVERTEX = false;
  35328. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35329. defines.LODINREFLECTIONALPHA = false;
  35330. defines.GAMMAREFLECTION = false;
  35331. }
  35332. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35333. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35334. return false;
  35335. }
  35336. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35337. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35338. }
  35339. else {
  35340. defines.LIGHTMAP = false;
  35341. }
  35342. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35343. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35344. return false;
  35345. }
  35346. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35347. }
  35348. else {
  35349. defines.EMISSIVE = false;
  35350. }
  35351. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35352. if (this._metallicTexture) {
  35353. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35354. return false;
  35355. }
  35356. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35357. defines.METALLICWORKFLOW = true;
  35358. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35359. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35360. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35361. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35362. }
  35363. else if (this._reflectivityTexture) {
  35364. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35365. return false;
  35366. }
  35367. defines.METALLICWORKFLOW = false;
  35368. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35369. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35370. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35371. }
  35372. else {
  35373. defines.METALLICWORKFLOW = false;
  35374. defines.REFLECTIVITY = false;
  35375. }
  35376. if (this._microSurfaceTexture) {
  35377. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35378. return false;
  35379. }
  35380. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35381. }
  35382. else {
  35383. defines.MICROSURFACEMAP = false;
  35384. }
  35385. }
  35386. else {
  35387. defines.REFLECTIVITY = false;
  35388. defines.MICROSURFACEMAP = false;
  35389. }
  35390. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35391. // Bump texure can not be none blocking.
  35392. if (!this._bumpTexture.isReady()) {
  35393. return false;
  35394. }
  35395. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35396. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35397. defines.PARALLAX = true;
  35398. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35399. }
  35400. else {
  35401. defines.PARALLAX = false;
  35402. }
  35403. }
  35404. else {
  35405. defines.BUMP = false;
  35406. }
  35407. var refractionTexture = this._getRefractionTexture();
  35408. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35409. if (!refractionTexture.isReadyOrNotBlocking()) {
  35410. return false;
  35411. }
  35412. defines.REFRACTION = true;
  35413. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35414. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35415. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35416. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35417. if (this._linkRefractionWithTransparency) {
  35418. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35419. }
  35420. }
  35421. else {
  35422. defines.REFRACTION = false;
  35423. }
  35424. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35425. // This is blocking.
  35426. if (!this._environmentBRDFTexture.isReady()) {
  35427. return false;
  35428. }
  35429. defines.ENVIRONMENTBRDF = true;
  35430. }
  35431. else {
  35432. defines.ENVIRONMENTBRDF = false;
  35433. }
  35434. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35435. defines.ALPHAFROMALBEDO = true;
  35436. }
  35437. else {
  35438. defines.ALPHAFROMALBEDO = false;
  35439. }
  35440. }
  35441. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35442. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35443. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35444. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35445. defines.METALLICWORKFLOW = true;
  35446. }
  35447. else {
  35448. defines.METALLICWORKFLOW = false;
  35449. }
  35450. if (!this.backFaceCulling && this._twoSidedLighting) {
  35451. defines.TWOSIDEDLIGHTING = true;
  35452. }
  35453. else {
  35454. defines.TWOSIDEDLIGHTING = false;
  35455. }
  35456. defines.ALPHATESTVALUE = this._alphaCutOff;
  35457. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35458. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  35459. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35460. }
  35461. if (defines._areImageProcessingDirty) {
  35462. if (!this._imageProcessingConfiguration.isReady()) {
  35463. return false;
  35464. }
  35465. this._imageProcessingConfiguration.prepareDefines(defines);
  35466. }
  35467. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35468. // Misc.
  35469. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35470. // Values that need to be evaluated on every frame
  35471. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35472. // Attribs
  35473. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE)) {
  35474. if (mesh) {
  35475. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35476. mesh.createNormals(true);
  35477. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35478. }
  35479. }
  35480. }
  35481. // Get correct effect
  35482. if (defines.isDirty) {
  35483. defines.markAsProcessed();
  35484. scene.resetCachedMaterial();
  35485. // Fallbacks
  35486. var fallbacks = new BABYLON.EffectFallbacks();
  35487. var fallbackRank = 0;
  35488. if (defines.USESPHERICALINVERTEX) {
  35489. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  35490. }
  35491. if (defines.FOG) {
  35492. fallbacks.addFallback(fallbackRank, "FOG");
  35493. }
  35494. if (defines.POINTSIZE) {
  35495. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  35496. }
  35497. if (defines.LOGARITHMICDEPTH) {
  35498. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  35499. }
  35500. if (defines.PARALLAX) {
  35501. fallbacks.addFallback(fallbackRank, "PARALLAX");
  35502. }
  35503. if (defines.PARALLAXOCCLUSION) {
  35504. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  35505. }
  35506. if (defines.ENVIRONMENTBRDF) {
  35507. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  35508. }
  35509. if (defines.TANGENT) {
  35510. fallbacks.addFallback(fallbackRank++, "TANGENT");
  35511. }
  35512. if (defines.BUMP) {
  35513. fallbacks.addFallback(fallbackRank++, "BUMP");
  35514. }
  35515. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  35516. if (defines.SPECULARTERM) {
  35517. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  35518. }
  35519. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35520. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  35521. }
  35522. if (defines.LIGHTMAP) {
  35523. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  35524. }
  35525. if (defines.NORMAL) {
  35526. fallbacks.addFallback(fallbackRank++, "NORMAL");
  35527. }
  35528. if (defines.AMBIENT) {
  35529. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  35530. }
  35531. if (defines.EMISSIVE) {
  35532. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  35533. }
  35534. if (defines.VERTEXCOLOR) {
  35535. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  35536. }
  35537. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35538. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  35539. }
  35540. if (defines.MORPHTARGETS) {
  35541. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  35542. }
  35543. //Attributes
  35544. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35545. if (defines.NORMAL) {
  35546. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35547. }
  35548. if (defines.TANGENT) {
  35549. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35550. }
  35551. if (defines.UV1) {
  35552. attribs.push(BABYLON.VertexBuffer.UVKind);
  35553. }
  35554. if (defines.UV2) {
  35555. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35556. }
  35557. if (defines.VERTEXCOLOR) {
  35558. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35559. }
  35560. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35561. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35562. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35563. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35564. "vFogInfos", "vFogColor", "pointSize",
  35565. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35566. "mBones",
  35567. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35568. "vLightingIntensity",
  35569. "logarithmicDepthConstant",
  35570. "vSphericalX", "vSphericalY", "vSphericalZ",
  35571. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35572. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35573. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  35574. "vTangentSpaceParams"
  35575. ];
  35576. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35577. "bumpSampler", "lightmapSampler", "opacitySampler",
  35578. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35579. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35580. "microSurfaceSampler", "environmentBrdfSampler"];
  35581. var uniformBuffers = ["Material", "Scene"];
  35582. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35583. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35584. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35585. uniformsNames: uniforms,
  35586. uniformBuffersNames: uniformBuffers,
  35587. samplers: samplers,
  35588. defines: defines,
  35589. maxSimultaneousLights: this._maxSimultaneousLights
  35590. });
  35591. var onCompiled = function (effect) {
  35592. if (_this.onCompiled) {
  35593. _this.onCompiled(effect);
  35594. }
  35595. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35596. };
  35597. var join = defines.toString();
  35598. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35599. attributes: attribs,
  35600. uniformsNames: uniforms,
  35601. uniformBuffersNames: uniformBuffers,
  35602. samplers: samplers,
  35603. defines: join,
  35604. fallbacks: fallbacks,
  35605. onCompiled: onCompiled,
  35606. onError: this.onError,
  35607. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35608. }, engine), defines);
  35609. this.buildUniformLayout();
  35610. }
  35611. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35612. return false;
  35613. }
  35614. defines._renderId = scene.getRenderId();
  35615. this._wasPreviouslyReady = true;
  35616. return true;
  35617. };
  35618. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35619. // Order is important !
  35620. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35621. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35622. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35623. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35624. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35625. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35626. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35627. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35628. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35629. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35630. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35631. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35632. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35633. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35634. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35635. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35636. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35637. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35638. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35639. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35640. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35641. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35642. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35643. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35644. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35645. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35646. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35647. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35648. this._uniformBuffer.addUniform("pointSize", 1);
  35649. this._uniformBuffer.create();
  35650. };
  35651. PBRBaseMaterial.prototype.unbind = function () {
  35652. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35653. this._uniformBuffer.setTexture("reflectionSampler", null);
  35654. }
  35655. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35656. this._uniformBuffer.setTexture("refractionSampler", null);
  35657. }
  35658. _super.prototype.unbind.call(this);
  35659. };
  35660. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35661. this._activeEffect.setMatrix("world", world);
  35662. };
  35663. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35664. var scene = this.getScene();
  35665. var defines = subMesh._materialDefines;
  35666. if (!defines) {
  35667. return;
  35668. }
  35669. var effect = subMesh.effect;
  35670. if (!effect) {
  35671. return;
  35672. }
  35673. this._activeEffect = effect;
  35674. // Matrices
  35675. this.bindOnlyWorldMatrix(world);
  35676. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35677. // Bones
  35678. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35679. var reflectionTexture = null;
  35680. if (mustRebind) {
  35681. this._uniformBuffer.bindToEffect(effect, "Material");
  35682. this.bindViewProjection(effect);
  35683. reflectionTexture = this._getReflectionTexture();
  35684. var refractionTexture = this._getRefractionTexture();
  35685. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35686. // Texture uniforms
  35687. if (scene.texturesEnabled) {
  35688. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35689. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35690. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35691. }
  35692. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35693. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35694. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35695. }
  35696. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35697. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35698. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35699. }
  35700. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35701. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35702. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35703. var polynomials = reflectionTexture.sphericalPolynomial;
  35704. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  35705. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35706. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35707. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35708. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35709. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35710. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35711. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35712. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35713. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35714. }
  35715. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35716. }
  35717. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35718. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35719. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35720. }
  35721. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35722. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35723. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35724. }
  35725. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35726. if (this._metallicTexture) {
  35727. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35728. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35729. }
  35730. else if (this._reflectivityTexture) {
  35731. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35732. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35733. }
  35734. if (this._microSurfaceTexture) {
  35735. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35736. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35737. }
  35738. }
  35739. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35740. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35741. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35742. if (scene._mirroredCameraPosition) {
  35743. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35744. }
  35745. else {
  35746. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35747. }
  35748. }
  35749. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35750. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35751. var depth = 1.0;
  35752. if (!refractionTexture.isCube) {
  35753. if (refractionTexture.depth) {
  35754. depth = refractionTexture.depth;
  35755. }
  35756. }
  35757. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35758. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35759. }
  35760. }
  35761. // Point size
  35762. if (this.pointsCloud) {
  35763. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35764. }
  35765. // Colors
  35766. if (defines.METALLICWORKFLOW) {
  35767. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35768. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35769. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35770. }
  35771. else {
  35772. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35773. }
  35774. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35775. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35776. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35777. // Misc
  35778. this._lightingInfos.x = this._directIntensity;
  35779. this._lightingInfos.y = this._emissiveIntensity;
  35780. this._lightingInfos.z = this._environmentIntensity;
  35781. this._lightingInfos.w = this._specularIntensity;
  35782. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35783. }
  35784. // Textures
  35785. if (scene.texturesEnabled) {
  35786. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35787. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35788. }
  35789. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35790. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35791. }
  35792. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35793. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35794. }
  35795. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35796. if (defines.LODBASEDMICROSFURACE) {
  35797. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35798. }
  35799. else {
  35800. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35801. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35802. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35803. }
  35804. }
  35805. if (defines.ENVIRONMENTBRDF) {
  35806. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35807. }
  35808. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35809. if (defines.LODBASEDMICROSFURACE) {
  35810. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35811. }
  35812. else {
  35813. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35814. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35815. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35816. }
  35817. }
  35818. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35819. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35820. }
  35821. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35822. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35823. }
  35824. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35825. if (this._metallicTexture) {
  35826. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35827. }
  35828. else if (this._reflectivityTexture) {
  35829. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35830. }
  35831. if (this._microSurfaceTexture) {
  35832. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35833. }
  35834. }
  35835. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35836. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35837. }
  35838. }
  35839. // Clip plane
  35840. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35841. // Colors
  35842. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35843. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35844. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  35845. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  35846. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35847. }
  35848. if (mustRebind || !this.isFrozen) {
  35849. // Lights
  35850. if (scene.lightsEnabled && !this._disableLighting) {
  35851. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35852. }
  35853. // View
  35854. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35855. this.bindView(effect);
  35856. }
  35857. // Fog
  35858. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35859. // Morph targets
  35860. if (defines.NUM_MORPH_INFLUENCERS) {
  35861. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35862. }
  35863. // image processing
  35864. this._imageProcessingConfiguration.bind(this._activeEffect);
  35865. // Log. depth
  35866. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35867. }
  35868. this._uniformBuffer.update();
  35869. this._afterBind(mesh);
  35870. };
  35871. PBRBaseMaterial.prototype.getAnimatables = function () {
  35872. var results = [];
  35873. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35874. results.push(this._albedoTexture);
  35875. }
  35876. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35877. results.push(this._ambientTexture);
  35878. }
  35879. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35880. results.push(this._opacityTexture);
  35881. }
  35882. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35883. results.push(this._reflectionTexture);
  35884. }
  35885. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35886. results.push(this._emissiveTexture);
  35887. }
  35888. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35889. results.push(this._metallicTexture);
  35890. }
  35891. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35892. results.push(this._reflectivityTexture);
  35893. }
  35894. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35895. results.push(this._bumpTexture);
  35896. }
  35897. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35898. results.push(this._lightmapTexture);
  35899. }
  35900. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35901. results.push(this._refractionTexture);
  35902. }
  35903. return results;
  35904. };
  35905. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  35906. if (this._reflectionTexture) {
  35907. return this._reflectionTexture;
  35908. }
  35909. return this.getScene().environmentTexture;
  35910. };
  35911. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  35912. if (this._refractionTexture) {
  35913. return this._refractionTexture;
  35914. }
  35915. if (this._linkRefractionWithTransparency) {
  35916. return this.getScene().environmentTexture;
  35917. }
  35918. return null;
  35919. };
  35920. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35921. if (forceDisposeTextures) {
  35922. if (this._albedoTexture) {
  35923. this._albedoTexture.dispose();
  35924. }
  35925. if (this._ambientTexture) {
  35926. this._ambientTexture.dispose();
  35927. }
  35928. if (this._opacityTexture) {
  35929. this._opacityTexture.dispose();
  35930. }
  35931. if (this._reflectionTexture) {
  35932. this._reflectionTexture.dispose();
  35933. }
  35934. if (this._environmentBRDFTexture) {
  35935. this._environmentBRDFTexture.dispose();
  35936. }
  35937. if (this._emissiveTexture) {
  35938. this._emissiveTexture.dispose();
  35939. }
  35940. if (this._metallicTexture) {
  35941. this._metallicTexture.dispose();
  35942. }
  35943. if (this._reflectivityTexture) {
  35944. this._reflectivityTexture.dispose();
  35945. }
  35946. if (this._bumpTexture) {
  35947. this._bumpTexture.dispose();
  35948. }
  35949. if (this._lightmapTexture) {
  35950. this._lightmapTexture.dispose();
  35951. }
  35952. if (this._refractionTexture) {
  35953. this._refractionTexture.dispose();
  35954. }
  35955. }
  35956. this._renderTargets.dispose();
  35957. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35958. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35959. }
  35960. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35961. };
  35962. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35963. __decorate([
  35964. BABYLON.serializeAsImageProcessingConfiguration()
  35965. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35966. __decorate([
  35967. BABYLON.serialize()
  35968. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35969. __decorate([
  35970. BABYLON.serialize()
  35971. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  35972. return PBRBaseMaterial;
  35973. }(BABYLON.PushMaterial));
  35974. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35975. })(BABYLON || (BABYLON = {}));
  35976. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35977. var BABYLON;
  35978. (function (BABYLON) {
  35979. var Internals;
  35980. (function (Internals) {
  35981. /**
  35982. * The Physically based simple base material of BJS.
  35983. *
  35984. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35985. * It is used as the base class for both the specGloss and metalRough conventions.
  35986. */
  35987. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  35988. __extends(PBRBaseSimpleMaterial, _super);
  35989. /**
  35990. * Instantiates a new PBRMaterial instance.
  35991. *
  35992. * @param name The material name
  35993. * @param scene The scene the material will be use in.
  35994. */
  35995. function PBRBaseSimpleMaterial(name, scene) {
  35996. var _this = _super.call(this, name, scene) || this;
  35997. /**
  35998. * Number of Simultaneous lights allowed on the material.
  35999. */
  36000. _this.maxSimultaneousLights = 4;
  36001. /**
  36002. * If sets to true, disables all the lights affecting the material.
  36003. */
  36004. _this.disableLighting = false;
  36005. /**
  36006. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36007. */
  36008. _this.invertNormalMapX = false;
  36009. /**
  36010. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36011. */
  36012. _this.invertNormalMapY = false;
  36013. /**
  36014. * Emissivie color used to self-illuminate the model.
  36015. */
  36016. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36017. /**
  36018. * Occlusion Channel Strenght.
  36019. */
  36020. _this.occlusionStrength = 1.0;
  36021. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36022. _this._useAlphaFromAlbedoTexture = true;
  36023. _this._useAmbientInGrayScale = true;
  36024. return _this;
  36025. }
  36026. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  36027. /**
  36028. * Gets the current double sided mode.
  36029. */
  36030. get: function () {
  36031. return this._twoSidedLighting;
  36032. },
  36033. /**
  36034. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36035. */
  36036. set: function (value) {
  36037. if (this._twoSidedLighting === value) {
  36038. return;
  36039. }
  36040. this._twoSidedLighting = value;
  36041. this.backFaceCulling = !value;
  36042. this._markAllSubMeshesAsTexturesDirty();
  36043. },
  36044. enumerable: true,
  36045. configurable: true
  36046. });
  36047. /**
  36048. * Return the active textures of the material.
  36049. */
  36050. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  36051. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36052. if (this.environmentTexture) {
  36053. activeTextures.push(this.environmentTexture);
  36054. }
  36055. if (this.normalTexture) {
  36056. activeTextures.push(this.normalTexture);
  36057. }
  36058. if (this.emissiveTexture) {
  36059. activeTextures.push(this.emissiveTexture);
  36060. }
  36061. if (this.occlusionTexture) {
  36062. activeTextures.push(this.occlusionTexture);
  36063. }
  36064. return activeTextures;
  36065. };
  36066. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  36067. return "PBRBaseSimpleMaterial";
  36068. };
  36069. __decorate([
  36070. BABYLON.serialize(),
  36071. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36072. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  36073. __decorate([
  36074. BABYLON.serialize(),
  36075. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36076. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  36077. __decorate([
  36078. BABYLON.serializeAsTexture(),
  36079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  36080. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  36081. __decorate([
  36082. BABYLON.serialize(),
  36083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36084. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36085. __decorate([
  36086. BABYLON.serialize(),
  36087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36088. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36089. __decorate([
  36090. BABYLON.serializeAsTexture(),
  36091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36092. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36093. __decorate([
  36094. BABYLON.serializeAsColor3("emissive"),
  36095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36096. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36097. __decorate([
  36098. BABYLON.serializeAsTexture(),
  36099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36100. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36101. __decorate([
  36102. BABYLON.serialize(),
  36103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36104. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36105. __decorate([
  36106. BABYLON.serializeAsTexture(),
  36107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36108. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36109. __decorate([
  36110. BABYLON.serialize(),
  36111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36112. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36113. __decorate([
  36114. BABYLON.serialize()
  36115. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36116. return PBRBaseSimpleMaterial;
  36117. }(BABYLON.PBRBaseMaterial));
  36118. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36119. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36120. })(BABYLON || (BABYLON = {}));
  36121. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36122. var BABYLON;
  36123. (function (BABYLON) {
  36124. /**
  36125. * The Physically based material of BJS.
  36126. *
  36127. * This offers the main features of a standard PBR material.
  36128. * For more information, please refer to the documentation :
  36129. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36130. */
  36131. var PBRMaterial = /** @class */ (function (_super) {
  36132. __extends(PBRMaterial, _super);
  36133. /**
  36134. * Instantiates a new PBRMaterial instance.
  36135. *
  36136. * @param name The material name
  36137. * @param scene The scene the material will be use in.
  36138. */
  36139. function PBRMaterial(name, scene) {
  36140. var _this = _super.call(this, name, scene) || this;
  36141. /**
  36142. * Intensity of the direct lights e.g. the four lights available in your scene.
  36143. * This impacts both the direct diffuse and specular highlights.
  36144. */
  36145. _this.directIntensity = 1.0;
  36146. /**
  36147. * Intensity of the emissive part of the material.
  36148. * This helps controlling the emissive effect without modifying the emissive color.
  36149. */
  36150. _this.emissiveIntensity = 1.0;
  36151. /**
  36152. * Intensity of the environment e.g. how much the environment will light the object
  36153. * either through harmonics for rough material or through the refelction for shiny ones.
  36154. */
  36155. _this.environmentIntensity = 1.0;
  36156. /**
  36157. * This is a special control allowing the reduction of the specular highlights coming from the
  36158. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36159. */
  36160. _this.specularIntensity = 1.0;
  36161. /**
  36162. * Debug Control allowing disabling the bump map on this material.
  36163. */
  36164. _this.disableBumpMap = false;
  36165. /**
  36166. * AKA Occlusion Texture Intensity in other nomenclature.
  36167. */
  36168. _this.ambientTextureStrength = 1.0;
  36169. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36170. /**
  36171. * AKA Diffuse Color in other nomenclature.
  36172. */
  36173. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36174. /**
  36175. * AKA Specular Color in other nomenclature.
  36176. */
  36177. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36178. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36179. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36180. /**
  36181. * AKA Glossiness in other nomenclature.
  36182. */
  36183. _this.microSurface = 1.0;
  36184. /**
  36185. * source material index of refraction (IOR)' / 'destination material IOR.
  36186. */
  36187. _this.indexOfRefraction = 0.66;
  36188. /**
  36189. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36190. */
  36191. _this.invertRefractionY = false;
  36192. /**
  36193. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36194. * Materials half opaque for instance using refraction could benefit from this control.
  36195. */
  36196. _this.linkRefractionWithTransparency = false;
  36197. _this.useLightmapAsShadowmap = false;
  36198. /**
  36199. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36200. */
  36201. _this.useAlphaFromAlbedoTexture = false;
  36202. /**
  36203. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36204. */
  36205. _this.forceAlphaTest = false;
  36206. /**
  36207. * Defines the alpha limits in alpha test mode.
  36208. */
  36209. _this.alphaCutOff = 0.4;
  36210. /**
  36211. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36212. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36213. */
  36214. _this.useSpecularOverAlpha = true;
  36215. /**
  36216. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36217. */
  36218. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36219. /**
  36220. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36221. */
  36222. _this.useRoughnessFromMetallicTextureAlpha = true;
  36223. /**
  36224. * Specifies if the metallic texture contains the roughness information in its green channel.
  36225. */
  36226. _this.useRoughnessFromMetallicTextureGreen = false;
  36227. /**
  36228. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36229. */
  36230. _this.useMetallnessFromMetallicTextureBlue = false;
  36231. /**
  36232. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36233. */
  36234. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36235. /**
  36236. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36237. */
  36238. _this.useAmbientInGrayScale = false;
  36239. /**
  36240. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36241. * The material will try to infer what glossiness each pixel should be.
  36242. */
  36243. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36244. /**
  36245. * BJS is using an harcoded light falloff based on a manually sets up range.
  36246. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36247. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36248. */
  36249. _this.usePhysicalLightFalloff = true;
  36250. /**
  36251. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36252. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36253. */
  36254. _this.useRadianceOverAlpha = true;
  36255. /**
  36256. * Allows using the bump map in parallax mode.
  36257. */
  36258. _this.useParallax = false;
  36259. /**
  36260. * Allows using the bump map in parallax occlusion mode.
  36261. */
  36262. _this.useParallaxOcclusion = false;
  36263. /**
  36264. * Controls the scale bias of the parallax mode.
  36265. */
  36266. _this.parallaxScaleBias = 0.05;
  36267. /**
  36268. * If sets to true, disables all the lights affecting the material.
  36269. */
  36270. _this.disableLighting = false;
  36271. /**
  36272. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36273. */
  36274. _this.forceIrradianceInFragment = false;
  36275. /**
  36276. * Number of Simultaneous lights allowed on the material.
  36277. */
  36278. _this.maxSimultaneousLights = 4;
  36279. /**
  36280. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36281. */
  36282. _this.invertNormalMapX = false;
  36283. /**
  36284. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36285. */
  36286. _this.invertNormalMapY = false;
  36287. /**
  36288. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36289. */
  36290. _this.twoSidedLighting = false;
  36291. /**
  36292. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36293. * And/Or occlude the blended part.
  36294. */
  36295. _this.useAlphaFresnel = false;
  36296. /**
  36297. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36298. * And/Or occlude the blended part.
  36299. */
  36300. _this.environmentBRDFTexture = null;
  36301. /**
  36302. * Force normal to face away from face.
  36303. * (Temporary internal fix to remove before 3.1)
  36304. */
  36305. _this.forceNormalForward = false;
  36306. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36307. return _this;
  36308. }
  36309. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36310. /**
  36311. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36312. */
  36313. get: function () {
  36314. return this._PBRMATERIAL_OPAQUE;
  36315. },
  36316. enumerable: true,
  36317. configurable: true
  36318. });
  36319. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36320. /**
  36321. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36322. */
  36323. get: function () {
  36324. return this._PBRMATERIAL_ALPHATEST;
  36325. },
  36326. enumerable: true,
  36327. configurable: true
  36328. });
  36329. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36330. /**
  36331. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36332. */
  36333. get: function () {
  36334. return this._PBRMATERIAL_ALPHABLEND;
  36335. },
  36336. enumerable: true,
  36337. configurable: true
  36338. });
  36339. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36340. /**
  36341. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36342. * They are also discarded below the alpha cutoff threshold to improve performances.
  36343. */
  36344. get: function () {
  36345. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36346. },
  36347. enumerable: true,
  36348. configurable: true
  36349. });
  36350. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36351. /**
  36352. * Gets the image processing configuration used either in this material.
  36353. */
  36354. get: function () {
  36355. return this._imageProcessingConfiguration;
  36356. },
  36357. /**
  36358. * Sets the Default image processing configuration used either in the this material.
  36359. *
  36360. * If sets to null, the scene one is in use.
  36361. */
  36362. set: function (value) {
  36363. this._attachImageProcessingConfiguration(value);
  36364. // Ensure the effect will be rebuilt.
  36365. this._markAllSubMeshesAsTexturesDirty();
  36366. },
  36367. enumerable: true,
  36368. configurable: true
  36369. });
  36370. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36371. /**
  36372. * Gets wether the color curves effect is enabled.
  36373. */
  36374. get: function () {
  36375. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36376. },
  36377. /**
  36378. * Sets wether the color curves effect is enabled.
  36379. */
  36380. set: function (value) {
  36381. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36382. },
  36383. enumerable: true,
  36384. configurable: true
  36385. });
  36386. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36387. /**
  36388. * Gets wether the color grading effect is enabled.
  36389. */
  36390. get: function () {
  36391. return this.imageProcessingConfiguration.colorGradingEnabled;
  36392. },
  36393. /**
  36394. * Gets wether the color grading effect is enabled.
  36395. */
  36396. set: function (value) {
  36397. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36398. },
  36399. enumerable: true,
  36400. configurable: true
  36401. });
  36402. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36403. /**
  36404. * Gets wether tonemapping is enabled or not.
  36405. */
  36406. get: function () {
  36407. return this._imageProcessingConfiguration.toneMappingEnabled;
  36408. },
  36409. /**
  36410. * Sets wether tonemapping is enabled or not
  36411. */
  36412. set: function (value) {
  36413. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36414. },
  36415. enumerable: true,
  36416. configurable: true
  36417. });
  36418. ;
  36419. ;
  36420. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36421. /**
  36422. * The camera exposure used on this material.
  36423. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36424. * This corresponds to a photographic exposure.
  36425. */
  36426. get: function () {
  36427. return this._imageProcessingConfiguration.exposure;
  36428. },
  36429. /**
  36430. * The camera exposure used on this material.
  36431. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36432. * This corresponds to a photographic exposure.
  36433. */
  36434. set: function (value) {
  36435. this._imageProcessingConfiguration.exposure = value;
  36436. },
  36437. enumerable: true,
  36438. configurable: true
  36439. });
  36440. ;
  36441. ;
  36442. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36443. /**
  36444. * Gets The camera contrast used on this material.
  36445. */
  36446. get: function () {
  36447. return this._imageProcessingConfiguration.contrast;
  36448. },
  36449. /**
  36450. * Sets The camera contrast used on this material.
  36451. */
  36452. set: function (value) {
  36453. this._imageProcessingConfiguration.contrast = value;
  36454. },
  36455. enumerable: true,
  36456. configurable: true
  36457. });
  36458. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36459. /**
  36460. * Gets the Color Grading 2D Lookup Texture.
  36461. */
  36462. get: function () {
  36463. return this._imageProcessingConfiguration.colorGradingTexture;
  36464. },
  36465. /**
  36466. * Sets the Color Grading 2D Lookup Texture.
  36467. */
  36468. set: function (value) {
  36469. this._imageProcessingConfiguration.colorGradingTexture = value;
  36470. },
  36471. enumerable: true,
  36472. configurable: true
  36473. });
  36474. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36475. /**
  36476. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36477. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36478. * 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;
  36479. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36480. */
  36481. get: function () {
  36482. return this._imageProcessingConfiguration.colorCurves;
  36483. },
  36484. /**
  36485. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36486. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36487. * 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;
  36488. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36489. */
  36490. set: function (value) {
  36491. this._imageProcessingConfiguration.colorCurves = value;
  36492. },
  36493. enumerable: true,
  36494. configurable: true
  36495. });
  36496. PBRMaterial.prototype.getClassName = function () {
  36497. return "PBRMaterial";
  36498. };
  36499. PBRMaterial.prototype.getActiveTextures = function () {
  36500. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36501. if (this._albedoTexture) {
  36502. activeTextures.push(this._albedoTexture);
  36503. }
  36504. if (this._ambientTexture) {
  36505. activeTextures.push(this._ambientTexture);
  36506. }
  36507. if (this._opacityTexture) {
  36508. activeTextures.push(this._opacityTexture);
  36509. }
  36510. if (this._reflectionTexture) {
  36511. activeTextures.push(this._reflectionTexture);
  36512. }
  36513. if (this._emissiveTexture) {
  36514. activeTextures.push(this._emissiveTexture);
  36515. }
  36516. if (this._reflectivityTexture) {
  36517. activeTextures.push(this._reflectivityTexture);
  36518. }
  36519. if (this._metallicTexture) {
  36520. activeTextures.push(this._metallicTexture);
  36521. }
  36522. if (this._microSurfaceTexture) {
  36523. activeTextures.push(this._microSurfaceTexture);
  36524. }
  36525. if (this._bumpTexture) {
  36526. activeTextures.push(this._bumpTexture);
  36527. }
  36528. if (this._lightmapTexture) {
  36529. activeTextures.push(this._lightmapTexture);
  36530. }
  36531. if (this._refractionTexture) {
  36532. activeTextures.push(this._refractionTexture);
  36533. }
  36534. return activeTextures;
  36535. };
  36536. PBRMaterial.prototype.hasTexture = function (texture) {
  36537. if (_super.prototype.hasTexture.call(this, texture)) {
  36538. return true;
  36539. }
  36540. if (this._albedoTexture === texture) {
  36541. return true;
  36542. }
  36543. if (this._ambientTexture === texture) {
  36544. return true;
  36545. }
  36546. if (this._opacityTexture === texture) {
  36547. return true;
  36548. }
  36549. if (this._reflectionTexture === texture) {
  36550. return true;
  36551. }
  36552. if (this._reflectivityTexture === texture) {
  36553. return true;
  36554. }
  36555. if (this._metallicTexture === texture) {
  36556. return true;
  36557. }
  36558. if (this._microSurfaceTexture === texture) {
  36559. return true;
  36560. }
  36561. if (this._bumpTexture === texture) {
  36562. return true;
  36563. }
  36564. if (this._lightmapTexture === texture) {
  36565. return true;
  36566. }
  36567. if (this._refractionTexture === texture) {
  36568. return true;
  36569. }
  36570. return false;
  36571. };
  36572. PBRMaterial.prototype.clone = function (name) {
  36573. var _this = this;
  36574. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36575. clone.id = name;
  36576. clone.name = name;
  36577. return clone;
  36578. };
  36579. PBRMaterial.prototype.serialize = function () {
  36580. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36581. serializationObject.customType = "BABYLON.PBRMaterial";
  36582. return serializationObject;
  36583. };
  36584. // Statics
  36585. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36586. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36587. };
  36588. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36589. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36590. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36591. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36592. __decorate([
  36593. BABYLON.serialize(),
  36594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36595. ], PBRMaterial.prototype, "directIntensity", void 0);
  36596. __decorate([
  36597. BABYLON.serialize(),
  36598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36599. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36600. __decorate([
  36601. BABYLON.serialize(),
  36602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36603. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36604. __decorate([
  36605. BABYLON.serialize(),
  36606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36607. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36608. __decorate([
  36609. BABYLON.serialize(),
  36610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36611. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36612. __decorate([
  36613. BABYLON.serializeAsTexture(),
  36614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36615. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36616. __decorate([
  36617. BABYLON.serializeAsTexture(),
  36618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36619. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36620. __decorate([
  36621. BABYLON.serialize(),
  36622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36623. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36624. __decorate([
  36625. BABYLON.serializeAsTexture(),
  36626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36627. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36628. __decorate([
  36629. BABYLON.serializeAsTexture(),
  36630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36631. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36632. __decorate([
  36633. BABYLON.serializeAsTexture(),
  36634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36635. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36636. __decorate([
  36637. BABYLON.serializeAsTexture(),
  36638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36639. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36640. __decorate([
  36641. BABYLON.serializeAsTexture(),
  36642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36643. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36644. __decorate([
  36645. BABYLON.serialize(),
  36646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36647. ], PBRMaterial.prototype, "metallic", void 0);
  36648. __decorate([
  36649. BABYLON.serialize(),
  36650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36651. ], PBRMaterial.prototype, "roughness", void 0);
  36652. __decorate([
  36653. BABYLON.serializeAsTexture(),
  36654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36655. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36656. __decorate([
  36657. BABYLON.serializeAsTexture(),
  36658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36659. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36660. __decorate([
  36661. BABYLON.serializeAsTexture(),
  36662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36663. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36664. __decorate([
  36665. BABYLON.serializeAsTexture(),
  36666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36667. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36668. __decorate([
  36669. BABYLON.serializeAsColor3("ambient"),
  36670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36671. ], PBRMaterial.prototype, "ambientColor", void 0);
  36672. __decorate([
  36673. BABYLON.serializeAsColor3("albedo"),
  36674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36675. ], PBRMaterial.prototype, "albedoColor", void 0);
  36676. __decorate([
  36677. BABYLON.serializeAsColor3("reflectivity"),
  36678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36679. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36680. __decorate([
  36681. BABYLON.serializeAsColor3("reflection"),
  36682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36683. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36684. __decorate([
  36685. BABYLON.serializeAsColor3("emissive"),
  36686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36687. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36688. __decorate([
  36689. BABYLON.serialize(),
  36690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36691. ], PBRMaterial.prototype, "microSurface", void 0);
  36692. __decorate([
  36693. BABYLON.serialize(),
  36694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36695. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36696. __decorate([
  36697. BABYLON.serialize(),
  36698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36699. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36700. __decorate([
  36701. BABYLON.serialize(),
  36702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36703. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36704. __decorate([
  36705. BABYLON.serialize(),
  36706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36707. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36708. __decorate([
  36709. BABYLON.serialize(),
  36710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36711. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36712. __decorate([
  36713. BABYLON.serialize(),
  36714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36715. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  36716. __decorate([
  36717. BABYLON.serialize(),
  36718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36719. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  36720. __decorate([
  36721. BABYLON.serialize(),
  36722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36723. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36724. __decorate([
  36725. BABYLON.serialize(),
  36726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36727. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36728. __decorate([
  36729. BABYLON.serialize(),
  36730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36731. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36732. __decorate([
  36733. BABYLON.serialize(),
  36734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36735. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36736. __decorate([
  36737. BABYLON.serialize(),
  36738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36739. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36740. __decorate([
  36741. BABYLON.serialize(),
  36742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36743. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36744. __decorate([
  36745. BABYLON.serialize(),
  36746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36747. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36748. __decorate([
  36749. BABYLON.serialize(),
  36750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36751. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36752. __decorate([
  36753. BABYLON.serialize(),
  36754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36755. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36756. __decorate([
  36757. BABYLON.serialize(),
  36758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36759. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36760. __decorate([
  36761. BABYLON.serialize(),
  36762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36763. ], PBRMaterial.prototype, "useParallax", void 0);
  36764. __decorate([
  36765. BABYLON.serialize(),
  36766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36767. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36768. __decorate([
  36769. BABYLON.serialize(),
  36770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36771. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36772. __decorate([
  36773. BABYLON.serialize(),
  36774. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36775. ], PBRMaterial.prototype, "disableLighting", void 0);
  36776. __decorate([
  36777. BABYLON.serialize(),
  36778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36779. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  36780. __decorate([
  36781. BABYLON.serialize(),
  36782. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36783. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36784. __decorate([
  36785. BABYLON.serialize(),
  36786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36787. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36788. __decorate([
  36789. BABYLON.serialize(),
  36790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36791. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36792. __decorate([
  36793. BABYLON.serialize(),
  36794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36795. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36796. __decorate([
  36797. BABYLON.serialize(),
  36798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36799. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36800. __decorate([
  36801. BABYLON.serializeAsTexture(),
  36802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36803. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36804. __decorate([
  36805. BABYLON.serialize(),
  36806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36807. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36808. return PBRMaterial;
  36809. }(BABYLON.PBRBaseMaterial));
  36810. BABYLON.PBRMaterial = PBRMaterial;
  36811. })(BABYLON || (BABYLON = {}));
  36812. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36813. var BABYLON;
  36814. (function (BABYLON) {
  36815. /**
  36816. * The PBR material of BJS following the metal roughness convention.
  36817. *
  36818. * This fits to the PBR convention in the GLTF definition:
  36819. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36820. */
  36821. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36822. __extends(PBRMetallicRoughnessMaterial, _super);
  36823. /**
  36824. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36825. *
  36826. * @param name The material name
  36827. * @param scene The scene the material will be use in.
  36828. */
  36829. function PBRMetallicRoughnessMaterial(name, scene) {
  36830. var _this = _super.call(this, name, scene) || this;
  36831. _this._useRoughnessFromMetallicTextureAlpha = false;
  36832. _this._useRoughnessFromMetallicTextureGreen = true;
  36833. _this._useMetallnessFromMetallicTextureBlue = true;
  36834. return _this;
  36835. }
  36836. /**
  36837. * Return the currrent class name of the material.
  36838. */
  36839. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36840. return "PBRMetallicRoughnessMaterial";
  36841. };
  36842. /**
  36843. * Return the active textures of the material.
  36844. */
  36845. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36846. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36847. if (this.baseTexture) {
  36848. activeTextures.push(this.baseTexture);
  36849. }
  36850. if (this.metallicRoughnessTexture) {
  36851. activeTextures.push(this.metallicRoughnessTexture);
  36852. }
  36853. return activeTextures;
  36854. };
  36855. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36856. if (_super.prototype.hasTexture.call(this, texture)) {
  36857. return true;
  36858. }
  36859. if (this.baseTexture === texture) {
  36860. return true;
  36861. }
  36862. if (this.metallicRoughnessTexture === texture) {
  36863. return true;
  36864. }
  36865. return false;
  36866. };
  36867. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36868. var _this = this;
  36869. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36870. clone.id = name;
  36871. clone.name = name;
  36872. return clone;
  36873. };
  36874. /**
  36875. * Serialize the material to a parsable JSON object.
  36876. */
  36877. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36878. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36879. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36880. return serializationObject;
  36881. };
  36882. /**
  36883. * Parses a JSON object correponding to the serialize function.
  36884. */
  36885. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36886. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36887. };
  36888. __decorate([
  36889. BABYLON.serializeAsColor3(),
  36890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36891. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36892. __decorate([
  36893. BABYLON.serializeAsTexture(),
  36894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36895. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36896. __decorate([
  36897. BABYLON.serialize(),
  36898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36899. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36900. __decorate([
  36901. BABYLON.serialize(),
  36902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36903. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36904. __decorate([
  36905. BABYLON.serializeAsTexture(),
  36906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36907. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36908. return PBRMetallicRoughnessMaterial;
  36909. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36910. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36911. })(BABYLON || (BABYLON = {}));
  36912. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36913. var BABYLON;
  36914. (function (BABYLON) {
  36915. /**
  36916. * The PBR material of BJS following the specular glossiness convention.
  36917. *
  36918. * This fits to the PBR convention in the GLTF definition:
  36919. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36920. */
  36921. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  36922. __extends(PBRSpecularGlossinessMaterial, _super);
  36923. /**
  36924. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36925. *
  36926. * @param name The material name
  36927. * @param scene The scene the material will be use in.
  36928. */
  36929. function PBRSpecularGlossinessMaterial(name, scene) {
  36930. var _this = _super.call(this, name, scene) || this;
  36931. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36932. return _this;
  36933. }
  36934. /**
  36935. * Return the currrent class name of the material.
  36936. */
  36937. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36938. return "PBRSpecularGlossinessMaterial";
  36939. };
  36940. /**
  36941. * Return the active textures of the material.
  36942. */
  36943. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36944. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36945. if (this.diffuseTexture) {
  36946. activeTextures.push(this.diffuseTexture);
  36947. }
  36948. if (this.specularGlossinessTexture) {
  36949. activeTextures.push(this.specularGlossinessTexture);
  36950. }
  36951. return activeTextures;
  36952. };
  36953. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  36954. if (_super.prototype.hasTexture.call(this, texture)) {
  36955. return true;
  36956. }
  36957. if (this.diffuseTexture === texture) {
  36958. return true;
  36959. }
  36960. if (this.specularGlossinessTexture === texture) {
  36961. return true;
  36962. }
  36963. return false;
  36964. };
  36965. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36966. var _this = this;
  36967. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36968. clone.id = name;
  36969. clone.name = name;
  36970. return clone;
  36971. };
  36972. /**
  36973. * Serialize the material to a parsable JSON object.
  36974. */
  36975. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36976. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36977. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36978. return serializationObject;
  36979. };
  36980. /**
  36981. * Parses a JSON object correponding to the serialize function.
  36982. */
  36983. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36984. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36985. };
  36986. __decorate([
  36987. BABYLON.serializeAsColor3("diffuse"),
  36988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36989. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36990. __decorate([
  36991. BABYLON.serializeAsTexture(),
  36992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36993. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36994. __decorate([
  36995. BABYLON.serializeAsColor3("specular"),
  36996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36997. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36998. __decorate([
  36999. BABYLON.serialize(),
  37000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  37001. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  37002. __decorate([
  37003. BABYLON.serializeAsTexture(),
  37004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  37005. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  37006. return PBRSpecularGlossinessMaterial;
  37007. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37008. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  37009. })(BABYLON || (BABYLON = {}));
  37010. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  37011. var BABYLON;
  37012. (function (BABYLON) {
  37013. BABYLON.CameraInputTypes = {};
  37014. var CameraInputsManager = /** @class */ (function () {
  37015. function CameraInputsManager(camera) {
  37016. this.attached = {};
  37017. this.camera = camera;
  37018. this.checkInputs = function () { };
  37019. }
  37020. CameraInputsManager.prototype.add = function (input) {
  37021. var type = input.getSimpleName();
  37022. if (this.attached[type]) {
  37023. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  37024. return;
  37025. }
  37026. this.attached[type] = input;
  37027. input.camera = this.camera;
  37028. //for checkInputs, we are dynamically creating a function
  37029. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  37030. if (input.checkInputs) {
  37031. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37032. }
  37033. if (this.attachedElement) {
  37034. input.attachControl(this.attachedElement);
  37035. }
  37036. };
  37037. CameraInputsManager.prototype.remove = function (inputToRemove) {
  37038. for (var cam in this.attached) {
  37039. var input = this.attached[cam];
  37040. if (input === inputToRemove) {
  37041. input.detachControl(this.attachedElement);
  37042. input.camera = null;
  37043. delete this.attached[cam];
  37044. this.rebuildInputCheck();
  37045. }
  37046. }
  37047. };
  37048. CameraInputsManager.prototype.removeByType = function (inputType) {
  37049. for (var cam in this.attached) {
  37050. var input = this.attached[cam];
  37051. if (input.getClassName() === inputType) {
  37052. input.detachControl(this.attachedElement);
  37053. input.camera = null;
  37054. delete this.attached[cam];
  37055. this.rebuildInputCheck();
  37056. }
  37057. }
  37058. };
  37059. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  37060. var current = this.checkInputs;
  37061. return function () {
  37062. current();
  37063. fn();
  37064. };
  37065. };
  37066. CameraInputsManager.prototype.attachInput = function (input) {
  37067. if (this.attachedElement) {
  37068. input.attachControl(this.attachedElement, this.noPreventDefault);
  37069. }
  37070. };
  37071. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  37072. if (noPreventDefault === void 0) { noPreventDefault = false; }
  37073. if (this.attachedElement) {
  37074. return;
  37075. }
  37076. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37077. this.attachedElement = element;
  37078. this.noPreventDefault = noPreventDefault;
  37079. for (var cam in this.attached) {
  37080. this.attached[cam].attachControl(element, noPreventDefault);
  37081. }
  37082. };
  37083. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37084. if (disconnect === void 0) { disconnect = false; }
  37085. if (this.attachedElement !== element) {
  37086. return;
  37087. }
  37088. for (var cam in this.attached) {
  37089. this.attached[cam].detachControl(element);
  37090. if (disconnect) {
  37091. this.attached[cam].camera = null;
  37092. }
  37093. }
  37094. this.attachedElement = null;
  37095. };
  37096. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37097. this.checkInputs = function () { };
  37098. for (var cam in this.attached) {
  37099. var input = this.attached[cam];
  37100. if (input.checkInputs) {
  37101. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37102. }
  37103. }
  37104. };
  37105. CameraInputsManager.prototype.clear = function () {
  37106. if (this.attachedElement) {
  37107. this.detachElement(this.attachedElement, true);
  37108. }
  37109. this.attached = {};
  37110. this.attachedElement = null;
  37111. this.checkInputs = function () { };
  37112. };
  37113. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37114. var inputs = {};
  37115. for (var cam in this.attached) {
  37116. var input = this.attached[cam];
  37117. var res = BABYLON.SerializationHelper.Serialize(input);
  37118. inputs[input.getClassName()] = res;
  37119. }
  37120. serializedCamera.inputsmgr = inputs;
  37121. };
  37122. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37123. var parsedInputs = parsedCamera.inputsmgr;
  37124. if (parsedInputs) {
  37125. this.clear();
  37126. for (var n in parsedInputs) {
  37127. var construct = BABYLON.CameraInputTypes[n];
  37128. if (construct) {
  37129. var parsedinput = parsedInputs[n];
  37130. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37131. this.add(input);
  37132. }
  37133. }
  37134. }
  37135. else {
  37136. //2016-03-08 this part is for managing backward compatibility
  37137. for (var n in this.attached) {
  37138. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37139. if (construct) {
  37140. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37141. this.remove(this.attached[n]);
  37142. this.add(input);
  37143. }
  37144. }
  37145. }
  37146. };
  37147. return CameraInputsManager;
  37148. }());
  37149. BABYLON.CameraInputsManager = CameraInputsManager;
  37150. })(BABYLON || (BABYLON = {}));
  37151. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37152. var BABYLON;
  37153. (function (BABYLON) {
  37154. var FreeCameraMouseInput = /** @class */ (function () {
  37155. function FreeCameraMouseInput(touchEnabled) {
  37156. if (touchEnabled === void 0) { touchEnabled = true; }
  37157. this.touchEnabled = touchEnabled;
  37158. this.buttons = [0, 1, 2];
  37159. this.angularSensibility = 2000.0;
  37160. this.previousPosition = null;
  37161. }
  37162. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37163. var _this = this;
  37164. var engine = this.camera.getEngine();
  37165. if (!this._pointerInput) {
  37166. this._pointerInput = function (p, s) {
  37167. var evt = p.event;
  37168. if (engine.isInVRExclusivePointerMode) {
  37169. return;
  37170. }
  37171. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37172. return;
  37173. }
  37174. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37175. return;
  37176. }
  37177. var srcElement = (evt.srcElement || evt.target);
  37178. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37179. try {
  37180. srcElement.setPointerCapture(evt.pointerId);
  37181. }
  37182. catch (e) {
  37183. //Nothing to do with the error. Execution will continue.
  37184. }
  37185. _this.previousPosition = {
  37186. x: evt.clientX,
  37187. y: evt.clientY
  37188. };
  37189. if (!noPreventDefault) {
  37190. evt.preventDefault();
  37191. element.focus();
  37192. }
  37193. }
  37194. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37195. try {
  37196. srcElement.releasePointerCapture(evt.pointerId);
  37197. }
  37198. catch (e) {
  37199. //Nothing to do with the error.
  37200. }
  37201. _this.previousPosition = null;
  37202. if (!noPreventDefault) {
  37203. evt.preventDefault();
  37204. }
  37205. }
  37206. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37207. if (!_this.previousPosition || engine.isPointerLock) {
  37208. return;
  37209. }
  37210. var offsetX = evt.clientX - _this.previousPosition.x;
  37211. var offsetY = evt.clientY - _this.previousPosition.y;
  37212. if (_this.camera.getScene().useRightHandedSystem) {
  37213. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37214. }
  37215. else {
  37216. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37217. }
  37218. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37219. _this.previousPosition = {
  37220. x: evt.clientX,
  37221. y: evt.clientY
  37222. };
  37223. if (!noPreventDefault) {
  37224. evt.preventDefault();
  37225. }
  37226. }
  37227. };
  37228. }
  37229. this._onMouseMove = function (evt) {
  37230. if (!engine.isPointerLock) {
  37231. return;
  37232. }
  37233. if (engine.isInVRExclusivePointerMode) {
  37234. return;
  37235. }
  37236. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37237. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37238. if (_this.camera.getScene().useRightHandedSystem) {
  37239. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37240. }
  37241. else {
  37242. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37243. }
  37244. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37245. _this.previousPosition = null;
  37246. if (!noPreventDefault) {
  37247. evt.preventDefault();
  37248. }
  37249. };
  37250. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37251. element.addEventListener("mousemove", this._onMouseMove, false);
  37252. };
  37253. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37254. if (this._observer && element) {
  37255. this.camera.getScene().onPointerObservable.remove(this._observer);
  37256. if (this._onMouseMove) {
  37257. element.removeEventListener("mousemove", this._onMouseMove);
  37258. }
  37259. this._observer = null;
  37260. this._onMouseMove = null;
  37261. this.previousPosition = null;
  37262. }
  37263. };
  37264. FreeCameraMouseInput.prototype.getClassName = function () {
  37265. return "FreeCameraMouseInput";
  37266. };
  37267. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37268. return "mouse";
  37269. };
  37270. __decorate([
  37271. BABYLON.serialize()
  37272. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37273. __decorate([
  37274. BABYLON.serialize()
  37275. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37276. return FreeCameraMouseInput;
  37277. }());
  37278. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37279. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37280. })(BABYLON || (BABYLON = {}));
  37281. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37282. var BABYLON;
  37283. (function (BABYLON) {
  37284. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37285. function FreeCameraKeyboardMoveInput() {
  37286. this._keys = new Array();
  37287. this.keysUp = [38];
  37288. this.keysDown = [40];
  37289. this.keysLeft = [37];
  37290. this.keysRight = [39];
  37291. }
  37292. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37293. var _this = this;
  37294. if (this._onCanvasBlurObserver) {
  37295. return;
  37296. }
  37297. this._scene = this.camera.getScene();
  37298. this._engine = this._scene.getEngine();
  37299. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37300. _this._keys = [];
  37301. });
  37302. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37303. var evt = info.event;
  37304. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37305. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37306. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37307. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37308. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37309. var index = _this._keys.indexOf(evt.keyCode);
  37310. if (index === -1) {
  37311. _this._keys.push(evt.keyCode);
  37312. }
  37313. if (!noPreventDefault) {
  37314. evt.preventDefault();
  37315. }
  37316. }
  37317. }
  37318. else {
  37319. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37320. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37321. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37322. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37323. var index = _this._keys.indexOf(evt.keyCode);
  37324. if (index >= 0) {
  37325. _this._keys.splice(index, 1);
  37326. }
  37327. if (!noPreventDefault) {
  37328. evt.preventDefault();
  37329. }
  37330. }
  37331. }
  37332. });
  37333. };
  37334. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37335. if (this._scene) {
  37336. if (this._onKeyboardObserver) {
  37337. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37338. }
  37339. if (this._onCanvasBlurObserver) {
  37340. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37341. }
  37342. this._onKeyboardObserver = null;
  37343. this._onCanvasBlurObserver = null;
  37344. }
  37345. this._keys = [];
  37346. };
  37347. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37348. if (this._onKeyboardObserver) {
  37349. var camera = this.camera;
  37350. // Keyboard
  37351. for (var index = 0; index < this._keys.length; index++) {
  37352. var keyCode = this._keys[index];
  37353. var speed = camera._computeLocalCameraSpeed();
  37354. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37355. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37356. }
  37357. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37358. camera._localDirection.copyFromFloats(0, 0, speed);
  37359. }
  37360. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37361. camera._localDirection.copyFromFloats(speed, 0, 0);
  37362. }
  37363. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37364. camera._localDirection.copyFromFloats(0, 0, -speed);
  37365. }
  37366. if (camera.getScene().useRightHandedSystem) {
  37367. camera._localDirection.z *= -1;
  37368. }
  37369. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37370. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37371. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37372. }
  37373. }
  37374. };
  37375. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37376. return "FreeCameraKeyboardMoveInput";
  37377. };
  37378. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37379. this._keys = [];
  37380. };
  37381. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37382. return "keyboard";
  37383. };
  37384. __decorate([
  37385. BABYLON.serialize()
  37386. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37387. __decorate([
  37388. BABYLON.serialize()
  37389. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37390. __decorate([
  37391. BABYLON.serialize()
  37392. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37393. __decorate([
  37394. BABYLON.serialize()
  37395. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37396. return FreeCameraKeyboardMoveInput;
  37397. }());
  37398. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37399. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37400. })(BABYLON || (BABYLON = {}));
  37401. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37402. var BABYLON;
  37403. (function (BABYLON) {
  37404. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37405. __extends(FreeCameraInputsManager, _super);
  37406. function FreeCameraInputsManager(camera) {
  37407. return _super.call(this, camera) || this;
  37408. }
  37409. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37410. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37411. return this;
  37412. };
  37413. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37414. if (touchEnabled === void 0) { touchEnabled = true; }
  37415. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37416. return this;
  37417. };
  37418. FreeCameraInputsManager.prototype.addGamepad = function () {
  37419. this.add(new BABYLON.FreeCameraGamepadInput());
  37420. return this;
  37421. };
  37422. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37423. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37424. return this;
  37425. };
  37426. FreeCameraInputsManager.prototype.addTouch = function () {
  37427. this.add(new BABYLON.FreeCameraTouchInput());
  37428. return this;
  37429. };
  37430. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37431. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37432. return this;
  37433. };
  37434. return FreeCameraInputsManager;
  37435. }(BABYLON.CameraInputsManager));
  37436. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37437. })(BABYLON || (BABYLON = {}));
  37438. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37439. var BABYLON;
  37440. (function (BABYLON) {
  37441. var TargetCamera = /** @class */ (function (_super) {
  37442. __extends(TargetCamera, _super);
  37443. function TargetCamera(name, position, scene) {
  37444. var _this = _super.call(this, name, position, scene) || this;
  37445. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37446. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37447. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37448. _this.speed = 2.0;
  37449. _this.noRotationConstraint = false;
  37450. _this.lockedTarget = null;
  37451. _this._currentTarget = BABYLON.Vector3.Zero();
  37452. _this._viewMatrix = BABYLON.Matrix.Zero();
  37453. _this._camMatrix = BABYLON.Matrix.Zero();
  37454. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37455. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37456. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37457. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37458. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37459. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37460. _this._tempMatrix = BABYLON.Matrix.Zero();
  37461. return _this;
  37462. }
  37463. TargetCamera.prototype.getFrontPosition = function (distance) {
  37464. var direction = this.getTarget().subtract(this.position);
  37465. direction.normalize();
  37466. direction.scaleInPlace(distance);
  37467. return this.globalPosition.add(direction);
  37468. };
  37469. TargetCamera.prototype._getLockedTargetPosition = function () {
  37470. if (!this.lockedTarget) {
  37471. return null;
  37472. }
  37473. if (this.lockedTarget.absolutePosition) {
  37474. this.lockedTarget.computeWorldMatrix();
  37475. }
  37476. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37477. };
  37478. TargetCamera.prototype.storeState = function () {
  37479. this._storedPosition = this.position.clone();
  37480. this._storedRotation = this.rotation.clone();
  37481. if (this.rotationQuaternion) {
  37482. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37483. }
  37484. return _super.prototype.storeState.call(this);
  37485. };
  37486. /**
  37487. * Restored camera state. You must call storeState() first
  37488. */
  37489. TargetCamera.prototype._restoreStateValues = function () {
  37490. if (!_super.prototype._restoreStateValues.call(this)) {
  37491. return false;
  37492. }
  37493. this.position = this._storedPosition.clone();
  37494. this.rotation = this._storedRotation.clone();
  37495. if (this.rotationQuaternion) {
  37496. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37497. }
  37498. this.cameraDirection.copyFromFloats(0, 0, 0);
  37499. this.cameraRotation.copyFromFloats(0, 0);
  37500. return true;
  37501. };
  37502. // Cache
  37503. TargetCamera.prototype._initCache = function () {
  37504. _super.prototype._initCache.call(this);
  37505. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37506. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37507. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37508. };
  37509. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37510. if (!ignoreParentClass) {
  37511. _super.prototype._updateCache.call(this);
  37512. }
  37513. var lockedTargetPosition = this._getLockedTargetPosition();
  37514. if (!lockedTargetPosition) {
  37515. this._cache.lockedTarget = null;
  37516. }
  37517. else {
  37518. if (!this._cache.lockedTarget) {
  37519. this._cache.lockedTarget = lockedTargetPosition.clone();
  37520. }
  37521. else {
  37522. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37523. }
  37524. }
  37525. this._cache.rotation.copyFrom(this.rotation);
  37526. if (this.rotationQuaternion)
  37527. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37528. };
  37529. // Synchronized
  37530. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37531. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37532. return false;
  37533. }
  37534. var lockedTargetPosition = this._getLockedTargetPosition();
  37535. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37536. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37537. };
  37538. // Methods
  37539. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37540. var engine = this.getEngine();
  37541. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37542. };
  37543. // Target
  37544. TargetCamera.prototype.setTarget = function (target) {
  37545. this.upVector.normalize();
  37546. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37547. this._camMatrix.invert();
  37548. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37549. var vDir = target.subtract(this.position);
  37550. if (vDir.x >= 0.0) {
  37551. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37552. }
  37553. else {
  37554. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37555. }
  37556. this.rotation.z = 0;
  37557. if (isNaN(this.rotation.x)) {
  37558. this.rotation.x = 0;
  37559. }
  37560. if (isNaN(this.rotation.y)) {
  37561. this.rotation.y = 0;
  37562. }
  37563. if (isNaN(this.rotation.z)) {
  37564. this.rotation.z = 0;
  37565. }
  37566. if (this.rotationQuaternion) {
  37567. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37568. }
  37569. };
  37570. /**
  37571. * Return the current target position of the camera. This value is expressed in local space.
  37572. */
  37573. TargetCamera.prototype.getTarget = function () {
  37574. return this._currentTarget;
  37575. };
  37576. TargetCamera.prototype._decideIfNeedsToMove = function () {
  37577. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37578. };
  37579. TargetCamera.prototype._updatePosition = function () {
  37580. if (this.parent) {
  37581. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  37582. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  37583. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  37584. return;
  37585. }
  37586. this.position.addInPlace(this.cameraDirection);
  37587. };
  37588. TargetCamera.prototype._checkInputs = function () {
  37589. var needToMove = this._decideIfNeedsToMove();
  37590. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  37591. // Move
  37592. if (needToMove) {
  37593. this._updatePosition();
  37594. }
  37595. // Rotate
  37596. if (needToRotate) {
  37597. this.rotation.x += this.cameraRotation.x;
  37598. this.rotation.y += this.cameraRotation.y;
  37599. //rotate, if quaternion is set and rotation was used
  37600. if (this.rotationQuaternion) {
  37601. var len = this.rotation.lengthSquared();
  37602. if (len) {
  37603. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37604. }
  37605. }
  37606. if (!this.noRotationConstraint) {
  37607. var limit = (Math.PI / 2) * 0.95;
  37608. if (this.rotation.x > limit)
  37609. this.rotation.x = limit;
  37610. if (this.rotation.x < -limit)
  37611. this.rotation.x = -limit;
  37612. }
  37613. }
  37614. // Inertia
  37615. if (needToMove) {
  37616. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  37617. this.cameraDirection.x = 0;
  37618. }
  37619. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  37620. this.cameraDirection.y = 0;
  37621. }
  37622. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  37623. this.cameraDirection.z = 0;
  37624. }
  37625. this.cameraDirection.scaleInPlace(this.inertia);
  37626. }
  37627. if (needToRotate) {
  37628. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  37629. this.cameraRotation.x = 0;
  37630. }
  37631. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  37632. this.cameraRotation.y = 0;
  37633. }
  37634. this.cameraRotation.scaleInPlace(this.inertia);
  37635. }
  37636. _super.prototype._checkInputs.call(this);
  37637. };
  37638. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  37639. if (this.rotationQuaternion) {
  37640. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  37641. }
  37642. else {
  37643. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  37644. }
  37645. //update the up vector!
  37646. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  37647. };
  37648. TargetCamera.prototype._getViewMatrix = function () {
  37649. if (!this.lockedTarget) {
  37650. // Compute
  37651. this._updateCameraRotationMatrix();
  37652. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  37653. // Computing target and final matrix
  37654. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  37655. }
  37656. else {
  37657. var targetPosition = this._getLockedTargetPosition();
  37658. if (targetPosition) {
  37659. this._currentTarget.copyFrom(targetPosition);
  37660. }
  37661. }
  37662. if (this.getScene().useRightHandedSystem) {
  37663. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37664. }
  37665. else {
  37666. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37667. }
  37668. return this._viewMatrix;
  37669. };
  37670. /**
  37671. * @override
  37672. * Override Camera.createRigCamera
  37673. */
  37674. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37675. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  37676. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  37677. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  37678. if (!this.rotationQuaternion) {
  37679. this.rotationQuaternion = new BABYLON.Quaternion();
  37680. }
  37681. rigCamera._cameraRigParams = {};
  37682. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  37683. }
  37684. return rigCamera;
  37685. }
  37686. return null;
  37687. };
  37688. /**
  37689. * @override
  37690. * Override Camera._updateRigCameras
  37691. */
  37692. TargetCamera.prototype._updateRigCameras = function () {
  37693. var camLeft = this._rigCameras[0];
  37694. var camRight = this._rigCameras[1];
  37695. switch (this.cameraRigMode) {
  37696. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37697. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37698. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37699. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37700. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  37701. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  37702. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  37703. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  37704. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  37705. camLeft.setTarget(this.getTarget());
  37706. camRight.setTarget(this.getTarget());
  37707. break;
  37708. case BABYLON.Camera.RIG_MODE_VR:
  37709. if (camLeft.rotationQuaternion) {
  37710. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37711. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37712. }
  37713. else {
  37714. camLeft.rotation.copyFrom(this.rotation);
  37715. camRight.rotation.copyFrom(this.rotation);
  37716. }
  37717. camLeft.position.copyFrom(this.position);
  37718. camRight.position.copyFrom(this.position);
  37719. break;
  37720. }
  37721. _super.prototype._updateRigCameras.call(this);
  37722. };
  37723. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  37724. if (!this._rigCamTransformMatrix) {
  37725. this._rigCamTransformMatrix = new BABYLON.Matrix();
  37726. }
  37727. var target = this.getTarget();
  37728. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  37729. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  37730. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  37731. };
  37732. TargetCamera.prototype.getClassName = function () {
  37733. return "TargetCamera";
  37734. };
  37735. __decorate([
  37736. BABYLON.serializeAsVector3()
  37737. ], TargetCamera.prototype, "rotation", void 0);
  37738. __decorate([
  37739. BABYLON.serialize()
  37740. ], TargetCamera.prototype, "speed", void 0);
  37741. __decorate([
  37742. BABYLON.serializeAsMeshReference("lockedTargetId")
  37743. ], TargetCamera.prototype, "lockedTarget", void 0);
  37744. return TargetCamera;
  37745. }(BABYLON.Camera));
  37746. BABYLON.TargetCamera = TargetCamera;
  37747. })(BABYLON || (BABYLON = {}));
  37748. //# sourceMappingURL=babylon.targetCamera.js.map
  37749. var BABYLON;
  37750. (function (BABYLON) {
  37751. var FreeCamera = /** @class */ (function (_super) {
  37752. __extends(FreeCamera, _super);
  37753. function FreeCamera(name, position, scene) {
  37754. var _this = _super.call(this, name, position, scene) || this;
  37755. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  37756. _this.checkCollisions = false;
  37757. _this.applyGravity = false;
  37758. _this._needMoveForGravity = false;
  37759. _this._oldPosition = BABYLON.Vector3.Zero();
  37760. _this._diffPosition = BABYLON.Vector3.Zero();
  37761. _this._newPosition = BABYLON.Vector3.Zero();
  37762. // Collisions
  37763. _this._collisionMask = -1;
  37764. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37765. if (collidedMesh === void 0) { collidedMesh = null; }
  37766. //TODO move this to the collision coordinator!
  37767. if (_this.getScene().workerCollisions)
  37768. newPosition.multiplyInPlace(_this._collider.radius);
  37769. var updatePosition = function (newPos) {
  37770. _this._newPosition.copyFrom(newPos);
  37771. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  37772. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  37773. _this.position.addInPlace(_this._diffPosition);
  37774. if (_this.onCollide && collidedMesh) {
  37775. _this.onCollide(collidedMesh);
  37776. }
  37777. }
  37778. };
  37779. updatePosition(newPosition);
  37780. };
  37781. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  37782. _this.inputs.addKeyboard().addMouse();
  37783. return _this;
  37784. }
  37785. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  37786. //-- begin properties for backward compatibility for inputs
  37787. get: function () {
  37788. var mouse = this.inputs.attached["mouse"];
  37789. if (mouse)
  37790. return mouse.angularSensibility;
  37791. return 0;
  37792. },
  37793. set: function (value) {
  37794. var mouse = this.inputs.attached["mouse"];
  37795. if (mouse)
  37796. mouse.angularSensibility = value;
  37797. },
  37798. enumerable: true,
  37799. configurable: true
  37800. });
  37801. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37802. get: function () {
  37803. var keyboard = this.inputs.attached["keyboard"];
  37804. if (keyboard)
  37805. return keyboard.keysUp;
  37806. return [];
  37807. },
  37808. set: function (value) {
  37809. var keyboard = this.inputs.attached["keyboard"];
  37810. if (keyboard)
  37811. keyboard.keysUp = value;
  37812. },
  37813. enumerable: true,
  37814. configurable: true
  37815. });
  37816. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37817. get: function () {
  37818. var keyboard = this.inputs.attached["keyboard"];
  37819. if (keyboard)
  37820. return keyboard.keysDown;
  37821. return [];
  37822. },
  37823. set: function (value) {
  37824. var keyboard = this.inputs.attached["keyboard"];
  37825. if (keyboard)
  37826. keyboard.keysDown = value;
  37827. },
  37828. enumerable: true,
  37829. configurable: true
  37830. });
  37831. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37832. get: function () {
  37833. var keyboard = this.inputs.attached["keyboard"];
  37834. if (keyboard)
  37835. return keyboard.keysLeft;
  37836. return [];
  37837. },
  37838. set: function (value) {
  37839. var keyboard = this.inputs.attached["keyboard"];
  37840. if (keyboard)
  37841. keyboard.keysLeft = value;
  37842. },
  37843. enumerable: true,
  37844. configurable: true
  37845. });
  37846. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37847. get: function () {
  37848. var keyboard = this.inputs.attached["keyboard"];
  37849. if (keyboard)
  37850. return keyboard.keysRight;
  37851. return [];
  37852. },
  37853. set: function (value) {
  37854. var keyboard = this.inputs.attached["keyboard"];
  37855. if (keyboard)
  37856. keyboard.keysRight = value;
  37857. },
  37858. enumerable: true,
  37859. configurable: true
  37860. });
  37861. // Controls
  37862. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37863. this.inputs.attachElement(element, noPreventDefault);
  37864. };
  37865. FreeCamera.prototype.detachControl = function (element) {
  37866. this.inputs.detachElement(element);
  37867. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37868. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37869. };
  37870. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37871. get: function () {
  37872. return this._collisionMask;
  37873. },
  37874. set: function (mask) {
  37875. this._collisionMask = !isNaN(mask) ? mask : -1;
  37876. },
  37877. enumerable: true,
  37878. configurable: true
  37879. });
  37880. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37881. var globalPosition;
  37882. if (this.parent) {
  37883. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37884. }
  37885. else {
  37886. globalPosition = this.position;
  37887. }
  37888. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37889. if (!this._collider) {
  37890. this._collider = new BABYLON.Collider();
  37891. }
  37892. this._collider.radius = this.ellipsoid;
  37893. this._collider.collisionMask = this._collisionMask;
  37894. //no need for clone, as long as gravity is not on.
  37895. var actualDisplacement = displacement;
  37896. //add gravity to the direction to prevent the dual-collision checking
  37897. if (this.applyGravity) {
  37898. //this prevents mending with cameraDirection, a global variable of the free camera class.
  37899. actualDisplacement = displacement.add(this.getScene().gravity);
  37900. }
  37901. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37902. };
  37903. FreeCamera.prototype._checkInputs = function () {
  37904. if (!this._localDirection) {
  37905. this._localDirection = BABYLON.Vector3.Zero();
  37906. this._transformedDirection = BABYLON.Vector3.Zero();
  37907. }
  37908. this.inputs.checkInputs();
  37909. _super.prototype._checkInputs.call(this);
  37910. };
  37911. FreeCamera.prototype._decideIfNeedsToMove = function () {
  37912. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37913. };
  37914. FreeCamera.prototype._updatePosition = function () {
  37915. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  37916. this._collideWithWorld(this.cameraDirection);
  37917. }
  37918. else {
  37919. _super.prototype._updatePosition.call(this);
  37920. }
  37921. };
  37922. FreeCamera.prototype.dispose = function () {
  37923. this.inputs.clear();
  37924. _super.prototype.dispose.call(this);
  37925. };
  37926. FreeCamera.prototype.getClassName = function () {
  37927. return "FreeCamera";
  37928. };
  37929. __decorate([
  37930. BABYLON.serializeAsVector3()
  37931. ], FreeCamera.prototype, "ellipsoid", void 0);
  37932. __decorate([
  37933. BABYLON.serialize()
  37934. ], FreeCamera.prototype, "checkCollisions", void 0);
  37935. __decorate([
  37936. BABYLON.serialize()
  37937. ], FreeCamera.prototype, "applyGravity", void 0);
  37938. return FreeCamera;
  37939. }(BABYLON.TargetCamera));
  37940. BABYLON.FreeCamera = FreeCamera;
  37941. })(BABYLON || (BABYLON = {}));
  37942. //# sourceMappingURL=babylon.freeCamera.js.map
  37943. var BABYLON;
  37944. (function (BABYLON) {
  37945. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  37946. function ArcRotateCameraKeyboardMoveInput() {
  37947. this._keys = new Array();
  37948. this.keysUp = [38];
  37949. this.keysDown = [40];
  37950. this.keysLeft = [37];
  37951. this.keysRight = [39];
  37952. this.keysReset = [220];
  37953. this.panningSensibility = 50.0;
  37954. this.zoomingSensibility = 25.0;
  37955. this.useAltToZoom = true;
  37956. }
  37957. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37958. var _this = this;
  37959. if (this._onCanvasBlurObserver) {
  37960. return;
  37961. }
  37962. this._scene = this.camera.getScene();
  37963. this._engine = this._scene.getEngine();
  37964. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37965. _this._keys = [];
  37966. });
  37967. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37968. var evt = info.event;
  37969. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37970. _this._ctrlPressed = evt.ctrlKey;
  37971. _this._altPressed = evt.altKey;
  37972. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37973. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37974. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37975. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37976. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37977. var index = _this._keys.indexOf(evt.keyCode);
  37978. if (index === -1) {
  37979. _this._keys.push(evt.keyCode);
  37980. }
  37981. if (evt.preventDefault) {
  37982. if (!noPreventDefault) {
  37983. evt.preventDefault();
  37984. }
  37985. }
  37986. }
  37987. }
  37988. else {
  37989. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37990. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37991. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37992. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37993. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37994. var index = _this._keys.indexOf(evt.keyCode);
  37995. if (index >= 0) {
  37996. _this._keys.splice(index, 1);
  37997. }
  37998. if (evt.preventDefault) {
  37999. if (!noPreventDefault) {
  38000. evt.preventDefault();
  38001. }
  38002. }
  38003. }
  38004. }
  38005. });
  38006. };
  38007. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38008. if (this._scene) {
  38009. if (this._onKeyboardObserver) {
  38010. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38011. }
  38012. if (this._onCanvasBlurObserver) {
  38013. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38014. }
  38015. this._onKeyboardObserver = null;
  38016. this._onCanvasBlurObserver = null;
  38017. }
  38018. this._keys = [];
  38019. };
  38020. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38021. if (this._onKeyboardObserver) {
  38022. var camera = this.camera;
  38023. for (var index = 0; index < this._keys.length; index++) {
  38024. var keyCode = this._keys[index];
  38025. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38026. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38027. camera.inertialPanningX -= 1 / this.panningSensibility;
  38028. }
  38029. else {
  38030. camera.inertialAlphaOffset -= 0.01;
  38031. }
  38032. }
  38033. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38034. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38035. camera.inertialPanningY += 1 / this.panningSensibility;
  38036. }
  38037. else if (this._altPressed && this.useAltToZoom) {
  38038. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  38039. }
  38040. else {
  38041. camera.inertialBetaOffset -= 0.01;
  38042. }
  38043. }
  38044. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38045. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38046. camera.inertialPanningX += 1 / this.panningSensibility;
  38047. }
  38048. else {
  38049. camera.inertialAlphaOffset += 0.01;
  38050. }
  38051. }
  38052. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38053. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38054. camera.inertialPanningY -= 1 / this.panningSensibility;
  38055. }
  38056. else if (this._altPressed && this.useAltToZoom) {
  38057. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  38058. }
  38059. else {
  38060. camera.inertialBetaOffset += 0.01;
  38061. }
  38062. }
  38063. else if (this.keysReset.indexOf(keyCode) !== -1) {
  38064. camera.restoreState();
  38065. }
  38066. }
  38067. }
  38068. };
  38069. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  38070. return "ArcRotateCameraKeyboardMoveInput";
  38071. };
  38072. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38073. return "keyboard";
  38074. };
  38075. __decorate([
  38076. BABYLON.serialize()
  38077. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38078. __decorate([
  38079. BABYLON.serialize()
  38080. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38081. __decorate([
  38082. BABYLON.serialize()
  38083. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38084. __decorate([
  38085. BABYLON.serialize()
  38086. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38087. __decorate([
  38088. BABYLON.serialize()
  38089. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38090. __decorate([
  38091. BABYLON.serialize()
  38092. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38093. __decorate([
  38094. BABYLON.serialize()
  38095. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38096. __decorate([
  38097. BABYLON.serialize()
  38098. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38099. return ArcRotateCameraKeyboardMoveInput;
  38100. }());
  38101. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38102. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38103. })(BABYLON || (BABYLON = {}));
  38104. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38105. var BABYLON;
  38106. (function (BABYLON) {
  38107. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38108. function ArcRotateCameraMouseWheelInput() {
  38109. this.wheelPrecision = 3.0;
  38110. /**
  38111. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38112. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38113. */
  38114. this.wheelDeltaPercentage = 0;
  38115. }
  38116. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38117. var _this = this;
  38118. this._wheel = function (p, s) {
  38119. //sanity check - this should be a PointerWheel event.
  38120. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38121. return;
  38122. var event = p.event;
  38123. var delta = 0;
  38124. if (event.wheelDelta) {
  38125. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38126. }
  38127. else if (event.detail) {
  38128. delta = -event.detail / _this.wheelPrecision;
  38129. }
  38130. if (delta)
  38131. _this.camera.inertialRadiusOffset += delta;
  38132. if (event.preventDefault) {
  38133. if (!noPreventDefault) {
  38134. event.preventDefault();
  38135. }
  38136. }
  38137. };
  38138. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38139. };
  38140. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38141. if (this._observer && element) {
  38142. this.camera.getScene().onPointerObservable.remove(this._observer);
  38143. this._observer = null;
  38144. this._wheel = null;
  38145. }
  38146. };
  38147. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38148. return "ArcRotateCameraMouseWheelInput";
  38149. };
  38150. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38151. return "mousewheel";
  38152. };
  38153. __decorate([
  38154. BABYLON.serialize()
  38155. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38156. __decorate([
  38157. BABYLON.serialize()
  38158. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38159. return ArcRotateCameraMouseWheelInput;
  38160. }());
  38161. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38162. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38163. })(BABYLON || (BABYLON = {}));
  38164. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38165. var BABYLON;
  38166. (function (BABYLON) {
  38167. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38168. function ArcRotateCameraPointersInput() {
  38169. this.buttons = [0, 1, 2];
  38170. this.angularSensibilityX = 1000.0;
  38171. this.angularSensibilityY = 1000.0;
  38172. this.pinchPrecision = 12.0;
  38173. /**
  38174. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38175. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38176. */
  38177. this.pinchDeltaPercentage = 0;
  38178. this.panningSensibility = 1000.0;
  38179. this.multiTouchPanning = true;
  38180. this.multiTouchPanAndZoom = true;
  38181. this._isPanClick = false;
  38182. this.pinchInwards = true;
  38183. }
  38184. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38185. var _this = this;
  38186. var engine = this.camera.getEngine();
  38187. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38188. var pointA = null;
  38189. var pointB = null;
  38190. var previousPinchSquaredDistance = 0;
  38191. var initialDistance = 0;
  38192. var twoFingerActivityCount = 0;
  38193. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38194. this._pointerInput = function (p, s) {
  38195. var evt = p.event;
  38196. var isTouch = p.event.pointerType === "touch";
  38197. if (engine.isInVRExclusivePointerMode) {
  38198. return;
  38199. }
  38200. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38201. return;
  38202. }
  38203. var srcElement = (evt.srcElement || evt.target);
  38204. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38205. try {
  38206. srcElement.setPointerCapture(evt.pointerId);
  38207. }
  38208. catch (e) {
  38209. //Nothing to do with the error. Execution will continue.
  38210. }
  38211. // Manage panning with pan button click
  38212. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38213. // manage pointers
  38214. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38215. if (pointA === null) {
  38216. pointA = cacheSoloPointer;
  38217. }
  38218. else if (pointB === null) {
  38219. pointB = cacheSoloPointer;
  38220. }
  38221. if (!noPreventDefault) {
  38222. evt.preventDefault();
  38223. element.focus();
  38224. }
  38225. }
  38226. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38227. _this.camera.restoreState();
  38228. }
  38229. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38230. try {
  38231. srcElement.releasePointerCapture(evt.pointerId);
  38232. }
  38233. catch (e) {
  38234. //Nothing to do with the error.
  38235. }
  38236. cacheSoloPointer = null;
  38237. previousPinchSquaredDistance = 0;
  38238. previousMultiTouchPanPosition.isPaning = false;
  38239. previousMultiTouchPanPosition.isPinching = false;
  38240. twoFingerActivityCount = 0;
  38241. initialDistance = 0;
  38242. if (!isTouch) {
  38243. pointB = null; // Mouse and pen are mono pointer
  38244. }
  38245. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38246. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38247. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38248. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38249. if (engine.badOS) {
  38250. pointA = pointB = null;
  38251. }
  38252. else {
  38253. //only remove the impacted pointer in case of multitouch allowing on most
  38254. //platforms switching from rotate to zoom and pan seamlessly.
  38255. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38256. pointA = pointB;
  38257. pointB = null;
  38258. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38259. }
  38260. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38261. pointB = null;
  38262. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38263. }
  38264. else {
  38265. pointA = pointB = null;
  38266. }
  38267. }
  38268. if (!noPreventDefault) {
  38269. evt.preventDefault();
  38270. }
  38271. }
  38272. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38273. if (!noPreventDefault) {
  38274. evt.preventDefault();
  38275. }
  38276. // One button down
  38277. if (pointA && pointB === null && cacheSoloPointer) {
  38278. if (_this.panningSensibility !== 0 &&
  38279. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38280. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38281. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38282. }
  38283. else {
  38284. var offsetX = evt.clientX - cacheSoloPointer.x;
  38285. var offsetY = evt.clientY - cacheSoloPointer.y;
  38286. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38287. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38288. }
  38289. cacheSoloPointer.x = evt.clientX;
  38290. cacheSoloPointer.y = evt.clientY;
  38291. }
  38292. else if (pointA && pointB) {
  38293. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38294. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38295. ed.x = evt.clientX;
  38296. ed.y = evt.clientY;
  38297. var direction = _this.pinchInwards ? 1 : -1;
  38298. var distX = pointA.x - pointB.x;
  38299. var distY = pointA.y - pointB.y;
  38300. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38301. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38302. if (previousPinchSquaredDistance === 0) {
  38303. initialDistance = pinchDistance;
  38304. previousPinchSquaredDistance = pinchSquaredDistance;
  38305. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38306. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38307. return;
  38308. }
  38309. if (_this.multiTouchPanAndZoom) {
  38310. if (_this.pinchDeltaPercentage) {
  38311. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38312. }
  38313. else {
  38314. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38315. (_this.pinchPrecision *
  38316. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38317. direction);
  38318. }
  38319. if (_this.panningSensibility !== 0) {
  38320. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38321. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38322. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38323. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38324. previousMultiTouchPanPosition.x = pointersCenterX;
  38325. previousMultiTouchPanPosition.y = pointersCenterY;
  38326. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38327. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38328. }
  38329. }
  38330. else {
  38331. twoFingerActivityCount++;
  38332. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38333. if (_this.pinchDeltaPercentage) {
  38334. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38335. }
  38336. else {
  38337. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38338. (_this.pinchPrecision *
  38339. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38340. direction);
  38341. }
  38342. previousMultiTouchPanPosition.isPaning = false;
  38343. previousMultiTouchPanPosition.isPinching = true;
  38344. }
  38345. else {
  38346. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38347. if (!previousMultiTouchPanPosition.isPaning) {
  38348. previousMultiTouchPanPosition.isPaning = true;
  38349. previousMultiTouchPanPosition.isPinching = false;
  38350. previousMultiTouchPanPosition.x = ed.x;
  38351. previousMultiTouchPanPosition.y = ed.y;
  38352. return;
  38353. }
  38354. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38355. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38356. }
  38357. }
  38358. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38359. previousMultiTouchPanPosition.x = ed.x;
  38360. previousMultiTouchPanPosition.y = ed.y;
  38361. }
  38362. }
  38363. previousPinchSquaredDistance = pinchSquaredDistance;
  38364. }
  38365. }
  38366. };
  38367. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38368. this._onContextMenu = function (evt) {
  38369. evt.preventDefault();
  38370. };
  38371. if (!this.camera._useCtrlForPanning) {
  38372. element.addEventListener("contextmenu", this._onContextMenu, false);
  38373. }
  38374. this._onLostFocus = function () {
  38375. //this._keys = [];
  38376. pointA = pointB = null;
  38377. previousPinchSquaredDistance = 0;
  38378. previousMultiTouchPanPosition.isPaning = false;
  38379. previousMultiTouchPanPosition.isPinching = false;
  38380. twoFingerActivityCount = 0;
  38381. cacheSoloPointer = null;
  38382. initialDistance = 0;
  38383. };
  38384. this._onMouseMove = function (evt) {
  38385. if (!engine.isPointerLock) {
  38386. return;
  38387. }
  38388. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38389. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38390. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38391. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38392. if (!noPreventDefault) {
  38393. evt.preventDefault();
  38394. }
  38395. };
  38396. this._onGestureStart = function (e) {
  38397. if (window.MSGesture === undefined) {
  38398. return;
  38399. }
  38400. if (!_this._MSGestureHandler) {
  38401. _this._MSGestureHandler = new MSGesture();
  38402. _this._MSGestureHandler.target = element;
  38403. }
  38404. _this._MSGestureHandler.addPointer(e.pointerId);
  38405. };
  38406. this._onGesture = function (e) {
  38407. _this.camera.radius *= e.scale;
  38408. if (e.preventDefault) {
  38409. if (!noPreventDefault) {
  38410. e.stopPropagation();
  38411. e.preventDefault();
  38412. }
  38413. }
  38414. };
  38415. element.addEventListener("mousemove", this._onMouseMove, false);
  38416. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38417. element.addEventListener("MSGestureChange", this._onGesture, false);
  38418. BABYLON.Tools.RegisterTopRootEvents([
  38419. { name: "blur", handler: this._onLostFocus }
  38420. ]);
  38421. };
  38422. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38423. if (this._onLostFocus) {
  38424. BABYLON.Tools.UnregisterTopRootEvents([
  38425. { name: "blur", handler: this._onLostFocus }
  38426. ]);
  38427. }
  38428. if (element && this._observer) {
  38429. this.camera.getScene().onPointerObservable.remove(this._observer);
  38430. this._observer = null;
  38431. if (this._onContextMenu) {
  38432. element.removeEventListener("contextmenu", this._onContextMenu);
  38433. }
  38434. if (this._onMouseMove) {
  38435. element.removeEventListener("mousemove", this._onMouseMove);
  38436. }
  38437. if (this._onGestureStart) {
  38438. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38439. }
  38440. if (this._onGesture) {
  38441. element.removeEventListener("MSGestureChange", this._onGesture);
  38442. }
  38443. this._isPanClick = false;
  38444. this.pinchInwards = true;
  38445. this._onMouseMove = null;
  38446. this._onGestureStart = null;
  38447. this._onGesture = null;
  38448. this._MSGestureHandler = null;
  38449. this._onLostFocus = null;
  38450. this._onContextMenu = null;
  38451. }
  38452. };
  38453. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38454. return "ArcRotateCameraPointersInput";
  38455. };
  38456. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38457. return "pointers";
  38458. };
  38459. __decorate([
  38460. BABYLON.serialize()
  38461. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38462. __decorate([
  38463. BABYLON.serialize()
  38464. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38465. __decorate([
  38466. BABYLON.serialize()
  38467. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38468. __decorate([
  38469. BABYLON.serialize()
  38470. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38471. __decorate([
  38472. BABYLON.serialize()
  38473. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38474. __decorate([
  38475. BABYLON.serialize()
  38476. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38477. __decorate([
  38478. BABYLON.serialize()
  38479. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38480. __decorate([
  38481. BABYLON.serialize()
  38482. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38483. return ArcRotateCameraPointersInput;
  38484. }());
  38485. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38486. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38487. })(BABYLON || (BABYLON = {}));
  38488. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38489. var BABYLON;
  38490. (function (BABYLON) {
  38491. var ArcRotateCamera = /** @class */ (function (_super) {
  38492. __extends(ArcRotateCamera, _super);
  38493. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38494. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38495. _this.inertialAlphaOffset = 0;
  38496. _this.inertialBetaOffset = 0;
  38497. _this.inertialRadiusOffset = 0;
  38498. _this.lowerAlphaLimit = null;
  38499. _this.upperAlphaLimit = null;
  38500. _this.lowerBetaLimit = 0.01;
  38501. _this.upperBetaLimit = Math.PI;
  38502. _this.lowerRadiusLimit = null;
  38503. _this.upperRadiusLimit = null;
  38504. _this.inertialPanningX = 0;
  38505. _this.inertialPanningY = 0;
  38506. _this.pinchToPanMaxDistance = 20;
  38507. _this.panningDistanceLimit = null;
  38508. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38509. _this.panningInertia = 0.9;
  38510. //-- end properties for backward compatibility for inputs
  38511. _this.zoomOnFactor = 1;
  38512. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38513. _this.allowUpsideDown = true;
  38514. _this._viewMatrix = new BABYLON.Matrix();
  38515. // Panning
  38516. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38517. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38518. _this.checkCollisions = false;
  38519. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38520. _this._previousPosition = BABYLON.Vector3.Zero();
  38521. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38522. _this._newPosition = BABYLON.Vector3.Zero();
  38523. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38524. if (collidedMesh === void 0) { collidedMesh = null; }
  38525. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38526. newPosition.multiplyInPlace(_this._collider.radius);
  38527. }
  38528. if (!collidedMesh) {
  38529. _this._previousPosition.copyFrom(_this.position);
  38530. }
  38531. else {
  38532. _this.setPosition(newPosition);
  38533. if (_this.onCollide) {
  38534. _this.onCollide(collidedMesh);
  38535. }
  38536. }
  38537. // Recompute because of constraints
  38538. var cosa = Math.cos(_this.alpha);
  38539. var sina = Math.sin(_this.alpha);
  38540. var cosb = Math.cos(_this.beta);
  38541. var sinb = Math.sin(_this.beta);
  38542. if (sinb === 0) {
  38543. sinb = 0.0001;
  38544. }
  38545. var target = _this._getTargetPosition();
  38546. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38547. _this.position.copyFrom(_this._newPosition);
  38548. var up = _this.upVector;
  38549. if (_this.allowUpsideDown && _this.beta < 0) {
  38550. up = up.clone();
  38551. up = up.negate();
  38552. }
  38553. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38554. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38555. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38556. _this._collisionTriggered = false;
  38557. };
  38558. _this._target = BABYLON.Vector3.Zero();
  38559. if (target) {
  38560. _this.setTarget(target);
  38561. }
  38562. _this.alpha = alpha;
  38563. _this.beta = beta;
  38564. _this.radius = radius;
  38565. _this.getViewMatrix();
  38566. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  38567. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  38568. return _this;
  38569. }
  38570. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  38571. get: function () {
  38572. return this._target;
  38573. },
  38574. set: function (value) {
  38575. this.setTarget(value);
  38576. },
  38577. enumerable: true,
  38578. configurable: true
  38579. });
  38580. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  38581. //-- begin properties for backward compatibility for inputs
  38582. get: function () {
  38583. var pointers = this.inputs.attached["pointers"];
  38584. if (pointers)
  38585. return pointers.angularSensibilityX;
  38586. return 0;
  38587. },
  38588. set: function (value) {
  38589. var pointers = this.inputs.attached["pointers"];
  38590. if (pointers) {
  38591. pointers.angularSensibilityX = value;
  38592. }
  38593. },
  38594. enumerable: true,
  38595. configurable: true
  38596. });
  38597. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  38598. get: function () {
  38599. var pointers = this.inputs.attached["pointers"];
  38600. if (pointers)
  38601. return pointers.angularSensibilityY;
  38602. return 0;
  38603. },
  38604. set: function (value) {
  38605. var pointers = this.inputs.attached["pointers"];
  38606. if (pointers) {
  38607. pointers.angularSensibilityY = value;
  38608. }
  38609. },
  38610. enumerable: true,
  38611. configurable: true
  38612. });
  38613. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  38614. get: function () {
  38615. var pointers = this.inputs.attached["pointers"];
  38616. if (pointers)
  38617. return pointers.pinchPrecision;
  38618. return 0;
  38619. },
  38620. set: function (value) {
  38621. var pointers = this.inputs.attached["pointers"];
  38622. if (pointers) {
  38623. pointers.pinchPrecision = value;
  38624. }
  38625. },
  38626. enumerable: true,
  38627. configurable: true
  38628. });
  38629. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  38630. get: function () {
  38631. var pointers = this.inputs.attached["pointers"];
  38632. if (pointers)
  38633. return pointers.pinchDeltaPercentage;
  38634. return 0;
  38635. },
  38636. set: function (value) {
  38637. var pointers = this.inputs.attached["pointers"];
  38638. if (pointers) {
  38639. pointers.pinchDeltaPercentage = value;
  38640. }
  38641. },
  38642. enumerable: true,
  38643. configurable: true
  38644. });
  38645. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  38646. get: function () {
  38647. var pointers = this.inputs.attached["pointers"];
  38648. if (pointers)
  38649. return pointers.panningSensibility;
  38650. return 0;
  38651. },
  38652. set: function (value) {
  38653. var pointers = this.inputs.attached["pointers"];
  38654. if (pointers) {
  38655. pointers.panningSensibility = value;
  38656. }
  38657. },
  38658. enumerable: true,
  38659. configurable: true
  38660. });
  38661. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  38662. get: function () {
  38663. var keyboard = this.inputs.attached["keyboard"];
  38664. if (keyboard)
  38665. return keyboard.keysUp;
  38666. return [];
  38667. },
  38668. set: function (value) {
  38669. var keyboard = this.inputs.attached["keyboard"];
  38670. if (keyboard)
  38671. keyboard.keysUp = value;
  38672. },
  38673. enumerable: true,
  38674. configurable: true
  38675. });
  38676. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  38677. get: function () {
  38678. var keyboard = this.inputs.attached["keyboard"];
  38679. if (keyboard)
  38680. return keyboard.keysDown;
  38681. return [];
  38682. },
  38683. set: function (value) {
  38684. var keyboard = this.inputs.attached["keyboard"];
  38685. if (keyboard)
  38686. keyboard.keysDown = value;
  38687. },
  38688. enumerable: true,
  38689. configurable: true
  38690. });
  38691. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  38692. get: function () {
  38693. var keyboard = this.inputs.attached["keyboard"];
  38694. if (keyboard)
  38695. return keyboard.keysLeft;
  38696. return [];
  38697. },
  38698. set: function (value) {
  38699. var keyboard = this.inputs.attached["keyboard"];
  38700. if (keyboard)
  38701. keyboard.keysLeft = value;
  38702. },
  38703. enumerable: true,
  38704. configurable: true
  38705. });
  38706. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  38707. get: function () {
  38708. var keyboard = this.inputs.attached["keyboard"];
  38709. if (keyboard)
  38710. return keyboard.keysRight;
  38711. return [];
  38712. },
  38713. set: function (value) {
  38714. var keyboard = this.inputs.attached["keyboard"];
  38715. if (keyboard)
  38716. keyboard.keysRight = value;
  38717. },
  38718. enumerable: true,
  38719. configurable: true
  38720. });
  38721. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  38722. get: function () {
  38723. var mousewheel = this.inputs.attached["mousewheel"];
  38724. if (mousewheel)
  38725. return mousewheel.wheelPrecision;
  38726. return 0;
  38727. },
  38728. set: function (value) {
  38729. var mousewheel = this.inputs.attached["mousewheel"];
  38730. if (mousewheel)
  38731. mousewheel.wheelPrecision = value;
  38732. },
  38733. enumerable: true,
  38734. configurable: true
  38735. });
  38736. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  38737. get: function () {
  38738. var mousewheel = this.inputs.attached["mousewheel"];
  38739. if (mousewheel)
  38740. return mousewheel.wheelDeltaPercentage;
  38741. return 0;
  38742. },
  38743. set: function (value) {
  38744. var mousewheel = this.inputs.attached["mousewheel"];
  38745. if (mousewheel)
  38746. mousewheel.wheelDeltaPercentage = value;
  38747. },
  38748. enumerable: true,
  38749. configurable: true
  38750. });
  38751. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  38752. get: function () {
  38753. return this._bouncingBehavior;
  38754. },
  38755. enumerable: true,
  38756. configurable: true
  38757. });
  38758. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  38759. get: function () {
  38760. return this._bouncingBehavior != null;
  38761. },
  38762. set: function (value) {
  38763. if (value === this.useBouncingBehavior) {
  38764. return;
  38765. }
  38766. if (value) {
  38767. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  38768. this.addBehavior(this._bouncingBehavior);
  38769. }
  38770. else if (this._bouncingBehavior) {
  38771. this.removeBehavior(this._bouncingBehavior);
  38772. this._bouncingBehavior = null;
  38773. }
  38774. },
  38775. enumerable: true,
  38776. configurable: true
  38777. });
  38778. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  38779. get: function () {
  38780. return this._framingBehavior;
  38781. },
  38782. enumerable: true,
  38783. configurable: true
  38784. });
  38785. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  38786. get: function () {
  38787. return this._framingBehavior != null;
  38788. },
  38789. set: function (value) {
  38790. if (value === this.useFramingBehavior) {
  38791. return;
  38792. }
  38793. if (value) {
  38794. this._framingBehavior = new BABYLON.FramingBehavior();
  38795. this.addBehavior(this._framingBehavior);
  38796. }
  38797. else if (this._framingBehavior) {
  38798. this.removeBehavior(this._framingBehavior);
  38799. this._framingBehavior = null;
  38800. }
  38801. },
  38802. enumerable: true,
  38803. configurable: true
  38804. });
  38805. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38806. get: function () {
  38807. return this._autoRotationBehavior;
  38808. },
  38809. enumerable: true,
  38810. configurable: true
  38811. });
  38812. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38813. get: function () {
  38814. return this._autoRotationBehavior != null;
  38815. },
  38816. set: function (value) {
  38817. if (value === this.useAutoRotationBehavior) {
  38818. return;
  38819. }
  38820. if (value) {
  38821. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38822. this.addBehavior(this._autoRotationBehavior);
  38823. }
  38824. else if (this._autoRotationBehavior) {
  38825. this.removeBehavior(this._autoRotationBehavior);
  38826. this._autoRotationBehavior = null;
  38827. }
  38828. },
  38829. enumerable: true,
  38830. configurable: true
  38831. });
  38832. // Cache
  38833. ArcRotateCamera.prototype._initCache = function () {
  38834. _super.prototype._initCache.call(this);
  38835. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38836. this._cache.alpha = undefined;
  38837. this._cache.beta = undefined;
  38838. this._cache.radius = undefined;
  38839. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38840. };
  38841. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38842. if (!ignoreParentClass) {
  38843. _super.prototype._updateCache.call(this);
  38844. }
  38845. this._cache._target.copyFrom(this._getTargetPosition());
  38846. this._cache.alpha = this.alpha;
  38847. this._cache.beta = this.beta;
  38848. this._cache.radius = this.radius;
  38849. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38850. };
  38851. ArcRotateCamera.prototype._getTargetPosition = function () {
  38852. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38853. var pos = this._targetHost.getAbsolutePosition();
  38854. if (this._targetBoundingCenter) {
  38855. pos.addToRef(this._targetBoundingCenter, this._target);
  38856. }
  38857. else {
  38858. this._target.copyFrom(pos);
  38859. }
  38860. }
  38861. var lockedTargetPosition = this._getLockedTargetPosition();
  38862. if (lockedTargetPosition) {
  38863. return lockedTargetPosition;
  38864. }
  38865. return this._target;
  38866. };
  38867. ArcRotateCamera.prototype.storeState = function () {
  38868. this._storedAlpha = this.alpha;
  38869. this._storedBeta = this.beta;
  38870. this._storedRadius = this.radius;
  38871. this._storedTarget = this._getTargetPosition().clone();
  38872. return _super.prototype.storeState.call(this);
  38873. };
  38874. /**
  38875. * Restored camera state. You must call storeState() first
  38876. */
  38877. ArcRotateCamera.prototype._restoreStateValues = function () {
  38878. if (!_super.prototype._restoreStateValues.call(this)) {
  38879. return false;
  38880. }
  38881. this.alpha = this._storedAlpha;
  38882. this.beta = this._storedBeta;
  38883. this.radius = this._storedRadius;
  38884. this.setTarget(this._storedTarget.clone());
  38885. this.inertialAlphaOffset = 0;
  38886. this.inertialBetaOffset = 0;
  38887. this.inertialRadiusOffset = 0;
  38888. this.inertialPanningX = 0;
  38889. this.inertialPanningY = 0;
  38890. return true;
  38891. };
  38892. // Synchronized
  38893. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38894. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38895. return false;
  38896. return this._cache._target.equals(this._getTargetPosition())
  38897. && this._cache.alpha === this.alpha
  38898. && this._cache.beta === this.beta
  38899. && this._cache.radius === this.radius
  38900. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  38901. };
  38902. // Methods
  38903. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  38904. var _this = this;
  38905. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  38906. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  38907. this._useCtrlForPanning = useCtrlForPanning;
  38908. this._panningMouseButton = panningMouseButton;
  38909. this.inputs.attachElement(element, noPreventDefault);
  38910. this._reset = function () {
  38911. _this.inertialAlphaOffset = 0;
  38912. _this.inertialBetaOffset = 0;
  38913. _this.inertialRadiusOffset = 0;
  38914. _this.inertialPanningX = 0;
  38915. _this.inertialPanningY = 0;
  38916. };
  38917. };
  38918. ArcRotateCamera.prototype.detachControl = function (element) {
  38919. this.inputs.detachElement(element);
  38920. if (this._reset) {
  38921. this._reset();
  38922. }
  38923. };
  38924. ArcRotateCamera.prototype._checkInputs = function () {
  38925. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  38926. if (this._collisionTriggered) {
  38927. return;
  38928. }
  38929. this.inputs.checkInputs();
  38930. // Inertia
  38931. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  38932. if (this.getScene().useRightHandedSystem) {
  38933. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38934. }
  38935. else {
  38936. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38937. }
  38938. this.beta += this.inertialBetaOffset;
  38939. this.radius -= this.inertialRadiusOffset;
  38940. this.inertialAlphaOffset *= this.inertia;
  38941. this.inertialBetaOffset *= this.inertia;
  38942. this.inertialRadiusOffset *= this.inertia;
  38943. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  38944. this.inertialAlphaOffset = 0;
  38945. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  38946. this.inertialBetaOffset = 0;
  38947. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  38948. this.inertialRadiusOffset = 0;
  38949. }
  38950. // Panning inertia
  38951. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  38952. if (!this._localDirection) {
  38953. this._localDirection = BABYLON.Vector3.Zero();
  38954. this._transformedDirection = BABYLON.Vector3.Zero();
  38955. }
  38956. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  38957. this._localDirection.multiplyInPlace(this.panningAxis);
  38958. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  38959. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  38960. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  38961. if (!this.panningAxis.y) {
  38962. this._transformedDirection.y = 0;
  38963. }
  38964. if (!this._targetHost) {
  38965. if (this.panningDistanceLimit) {
  38966. this._transformedDirection.addInPlace(this._target);
  38967. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  38968. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  38969. this._target.copyFrom(this._transformedDirection);
  38970. }
  38971. }
  38972. else {
  38973. this._target.addInPlace(this._transformedDirection);
  38974. }
  38975. }
  38976. this.inertialPanningX *= this.panningInertia;
  38977. this.inertialPanningY *= this.panningInertia;
  38978. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  38979. this.inertialPanningX = 0;
  38980. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  38981. this.inertialPanningY = 0;
  38982. }
  38983. // Limits
  38984. this._checkLimits();
  38985. _super.prototype._checkInputs.call(this);
  38986. };
  38987. ArcRotateCamera.prototype._checkLimits = function () {
  38988. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  38989. if (this.allowUpsideDown && this.beta > Math.PI) {
  38990. this.beta = this.beta - (2 * Math.PI);
  38991. }
  38992. }
  38993. else {
  38994. if (this.beta < this.lowerBetaLimit) {
  38995. this.beta = this.lowerBetaLimit;
  38996. }
  38997. }
  38998. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  38999. if (this.allowUpsideDown && this.beta < -Math.PI) {
  39000. this.beta = this.beta + (2 * Math.PI);
  39001. }
  39002. }
  39003. else {
  39004. if (this.beta > this.upperBetaLimit) {
  39005. this.beta = this.upperBetaLimit;
  39006. }
  39007. }
  39008. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  39009. this.alpha = this.lowerAlphaLimit;
  39010. }
  39011. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  39012. this.alpha = this.upperAlphaLimit;
  39013. }
  39014. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  39015. this.radius = this.lowerRadiusLimit;
  39016. }
  39017. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  39018. this.radius = this.upperRadiusLimit;
  39019. }
  39020. };
  39021. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  39022. var radiusv3 = this.position.subtract(this._getTargetPosition());
  39023. this.radius = radiusv3.length();
  39024. if (this.radius === 0) {
  39025. this.radius = 0.0001; // Just to avoid division by zero
  39026. }
  39027. // Alpha
  39028. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  39029. if (radiusv3.z < 0) {
  39030. this.alpha = 2 * Math.PI - this.alpha;
  39031. }
  39032. // Beta
  39033. this.beta = Math.acos(radiusv3.y / this.radius);
  39034. this._checkLimits();
  39035. };
  39036. ArcRotateCamera.prototype.setPosition = function (position) {
  39037. if (this.position.equals(position)) {
  39038. return;
  39039. }
  39040. this.position.copyFrom(position);
  39041. this.rebuildAnglesAndRadius();
  39042. };
  39043. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  39044. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  39045. if (allowSamePosition === void 0) { allowSamePosition = false; }
  39046. if (target.getBoundingInfo) {
  39047. if (toBoundingCenter) {
  39048. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  39049. }
  39050. else {
  39051. this._targetBoundingCenter = null;
  39052. }
  39053. this._targetHost = target;
  39054. this._target = this._getTargetPosition();
  39055. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  39056. }
  39057. else {
  39058. var newTarget = target;
  39059. var currentTarget = this._getTargetPosition();
  39060. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  39061. return;
  39062. }
  39063. this._targetHost = null;
  39064. this._target = newTarget;
  39065. this._targetBoundingCenter = null;
  39066. this.onMeshTargetChangedObservable.notifyObservers(null);
  39067. }
  39068. this.rebuildAnglesAndRadius();
  39069. };
  39070. ArcRotateCamera.prototype._getViewMatrix = function () {
  39071. // Compute
  39072. var cosa = Math.cos(this.alpha);
  39073. var sina = Math.sin(this.alpha);
  39074. var cosb = Math.cos(this.beta);
  39075. var sinb = Math.sin(this.beta);
  39076. if (sinb === 0) {
  39077. sinb = 0.0001;
  39078. }
  39079. var target = this._getTargetPosition();
  39080. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  39081. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  39082. if (!this._collider) {
  39083. this._collider = new BABYLON.Collider();
  39084. }
  39085. this._collider.radius = this.collisionRadius;
  39086. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39087. this._collisionTriggered = true;
  39088. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39089. }
  39090. else {
  39091. this.position.copyFrom(this._newPosition);
  39092. var up = this.upVector;
  39093. if (this.allowUpsideDown && sinb < 0) {
  39094. up = up.clone();
  39095. up = up.negate();
  39096. }
  39097. if (this.getScene().useRightHandedSystem) {
  39098. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39099. }
  39100. else {
  39101. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39102. }
  39103. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39104. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39105. }
  39106. this._currentTarget = target;
  39107. return this._viewMatrix;
  39108. };
  39109. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39110. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39111. meshes = meshes || this.getScene().meshes;
  39112. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39113. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39114. this.radius = distance * this.zoomOnFactor;
  39115. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39116. };
  39117. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39118. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39119. var meshesOrMinMaxVector;
  39120. var distance;
  39121. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39122. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39123. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39124. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39125. }
  39126. else {
  39127. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39128. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39129. distance = minMaxVectorAndDistance.distance;
  39130. }
  39131. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39132. if (!doNotUpdateMaxZ) {
  39133. this.maxZ = distance * 2;
  39134. }
  39135. };
  39136. /**
  39137. * @override
  39138. * Override Camera.createRigCamera
  39139. */
  39140. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39141. var alphaShift = 0;
  39142. switch (this.cameraRigMode) {
  39143. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39144. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39145. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39146. case BABYLON.Camera.RIG_MODE_VR:
  39147. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39148. break;
  39149. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39150. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39151. break;
  39152. }
  39153. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39154. rigCam._cameraRigParams = {};
  39155. return rigCam;
  39156. };
  39157. /**
  39158. * @override
  39159. * Override Camera._updateRigCameras
  39160. */
  39161. ArcRotateCamera.prototype._updateRigCameras = function () {
  39162. var camLeft = this._rigCameras[0];
  39163. var camRight = this._rigCameras[1];
  39164. camLeft.beta = camRight.beta = this.beta;
  39165. camLeft.radius = camRight.radius = this.radius;
  39166. switch (this.cameraRigMode) {
  39167. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39168. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39169. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39170. case BABYLON.Camera.RIG_MODE_VR:
  39171. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39172. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39173. break;
  39174. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39175. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39176. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39177. break;
  39178. }
  39179. _super.prototype._updateRigCameras.call(this);
  39180. };
  39181. ArcRotateCamera.prototype.dispose = function () {
  39182. this.inputs.clear();
  39183. _super.prototype.dispose.call(this);
  39184. };
  39185. ArcRotateCamera.prototype.getClassName = function () {
  39186. return "ArcRotateCamera";
  39187. };
  39188. __decorate([
  39189. BABYLON.serialize()
  39190. ], ArcRotateCamera.prototype, "alpha", void 0);
  39191. __decorate([
  39192. BABYLON.serialize()
  39193. ], ArcRotateCamera.prototype, "beta", void 0);
  39194. __decorate([
  39195. BABYLON.serialize()
  39196. ], ArcRotateCamera.prototype, "radius", void 0);
  39197. __decorate([
  39198. BABYLON.serializeAsVector3("target")
  39199. ], ArcRotateCamera.prototype, "_target", void 0);
  39200. __decorate([
  39201. BABYLON.serialize()
  39202. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39203. __decorate([
  39204. BABYLON.serialize()
  39205. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39206. __decorate([
  39207. BABYLON.serialize()
  39208. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39209. __decorate([
  39210. BABYLON.serialize()
  39211. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39212. __decorate([
  39213. BABYLON.serialize()
  39214. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39215. __decorate([
  39216. BABYLON.serialize()
  39217. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39218. __decorate([
  39219. BABYLON.serialize()
  39220. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39221. __decorate([
  39222. BABYLON.serialize()
  39223. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39224. __decorate([
  39225. BABYLON.serialize()
  39226. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39227. __decorate([
  39228. BABYLON.serialize()
  39229. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39230. __decorate([
  39231. BABYLON.serialize()
  39232. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39233. __decorate([
  39234. BABYLON.serialize()
  39235. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39236. __decorate([
  39237. BABYLON.serialize()
  39238. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39239. __decorate([
  39240. BABYLON.serializeAsVector3()
  39241. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39242. __decorate([
  39243. BABYLON.serialize()
  39244. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39245. __decorate([
  39246. BABYLON.serialize()
  39247. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39248. __decorate([
  39249. BABYLON.serialize()
  39250. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39251. return ArcRotateCamera;
  39252. }(BABYLON.TargetCamera));
  39253. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39254. })(BABYLON || (BABYLON = {}));
  39255. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39256. var BABYLON;
  39257. (function (BABYLON) {
  39258. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39259. __extends(ArcRotateCameraInputsManager, _super);
  39260. function ArcRotateCameraInputsManager(camera) {
  39261. return _super.call(this, camera) || this;
  39262. }
  39263. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39264. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39265. return this;
  39266. };
  39267. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39268. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39269. return this;
  39270. };
  39271. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39272. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39273. return this;
  39274. };
  39275. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39276. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39277. return this;
  39278. };
  39279. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39280. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39281. return this;
  39282. };
  39283. return ArcRotateCameraInputsManager;
  39284. }(BABYLON.CameraInputsManager));
  39285. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39286. })(BABYLON || (BABYLON = {}));
  39287. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39288. var BABYLON;
  39289. (function (BABYLON) {
  39290. var HemisphericLight = /** @class */ (function (_super) {
  39291. __extends(HemisphericLight, _super);
  39292. /**
  39293. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39294. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39295. * The HemisphericLight can't cast shadows.
  39296. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39297. */
  39298. function HemisphericLight(name, direction, scene) {
  39299. var _this = _super.call(this, name, scene) || this;
  39300. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39301. _this.direction = direction || BABYLON.Vector3.Up();
  39302. return _this;
  39303. }
  39304. HemisphericLight.prototype._buildUniformLayout = function () {
  39305. this._uniformBuffer.addUniform("vLightData", 4);
  39306. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39307. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39308. this._uniformBuffer.addUniform("vLightGround", 3);
  39309. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39310. this._uniformBuffer.addUniform("depthValues", 2);
  39311. this._uniformBuffer.create();
  39312. };
  39313. /**
  39314. * Returns the string "HemisphericLight".
  39315. */
  39316. HemisphericLight.prototype.getClassName = function () {
  39317. return "HemisphericLight";
  39318. };
  39319. /**
  39320. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39321. * Returns the updated direction.
  39322. */
  39323. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39324. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39325. return this.direction;
  39326. };
  39327. HemisphericLight.prototype.getShadowGenerator = function () {
  39328. return null;
  39329. };
  39330. /**
  39331. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39332. * Returns the HemisphericLight.
  39333. */
  39334. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39335. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39336. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39337. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39338. return this;
  39339. };
  39340. HemisphericLight.prototype._getWorldMatrix = function () {
  39341. if (!this._worldMatrix) {
  39342. this._worldMatrix = BABYLON.Matrix.Identity();
  39343. }
  39344. return this._worldMatrix;
  39345. };
  39346. /**
  39347. * Returns the integer 3.
  39348. */
  39349. HemisphericLight.prototype.getTypeID = function () {
  39350. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39351. };
  39352. __decorate([
  39353. BABYLON.serializeAsColor3()
  39354. ], HemisphericLight.prototype, "groundColor", void 0);
  39355. __decorate([
  39356. BABYLON.serializeAsVector3()
  39357. ], HemisphericLight.prototype, "direction", void 0);
  39358. return HemisphericLight;
  39359. }(BABYLON.Light));
  39360. BABYLON.HemisphericLight = HemisphericLight;
  39361. })(BABYLON || (BABYLON = {}));
  39362. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39363. var BABYLON;
  39364. (function (BABYLON) {
  39365. var ShadowLight = /** @class */ (function (_super) {
  39366. __extends(ShadowLight, _super);
  39367. function ShadowLight() {
  39368. var _this = _super !== null && _super.apply(this, arguments) || this;
  39369. _this._needProjectionMatrixCompute = true;
  39370. return _this;
  39371. }
  39372. Object.defineProperty(ShadowLight.prototype, "direction", {
  39373. get: function () {
  39374. return this._direction;
  39375. },
  39376. set: function (value) {
  39377. this._direction = value;
  39378. },
  39379. enumerable: true,
  39380. configurable: true
  39381. });
  39382. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39383. get: function () {
  39384. return this._shadowMinZ;
  39385. },
  39386. set: function (value) {
  39387. this._shadowMinZ = value;
  39388. this.forceProjectionMatrixCompute();
  39389. },
  39390. enumerable: true,
  39391. configurable: true
  39392. });
  39393. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39394. get: function () {
  39395. return this._shadowMaxZ;
  39396. },
  39397. set: function (value) {
  39398. this._shadowMaxZ = value;
  39399. this.forceProjectionMatrixCompute();
  39400. },
  39401. enumerable: true,
  39402. configurable: true
  39403. });
  39404. /**
  39405. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39406. */
  39407. ShadowLight.prototype.computeTransformedInformation = function () {
  39408. if (this.parent && this.parent.getWorldMatrix) {
  39409. if (!this.transformedPosition) {
  39410. this.transformedPosition = BABYLON.Vector3.Zero();
  39411. }
  39412. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39413. // In case the direction is present.
  39414. if (this.direction) {
  39415. if (!this.transformedDirection) {
  39416. this.transformedDirection = BABYLON.Vector3.Zero();
  39417. }
  39418. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39419. }
  39420. return true;
  39421. }
  39422. return false;
  39423. };
  39424. /**
  39425. * Return the depth scale used for the shadow map.
  39426. */
  39427. ShadowLight.prototype.getDepthScale = function () {
  39428. return 50.0;
  39429. };
  39430. /**
  39431. * Returns the light direction (Vector3) for any passed face index.
  39432. */
  39433. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39434. return this.transformedDirection ? this.transformedDirection : this.direction;
  39435. };
  39436. /**
  39437. * Returns the DirectionalLight absolute position in the World.
  39438. */
  39439. ShadowLight.prototype.getAbsolutePosition = function () {
  39440. return this.transformedPosition ? this.transformedPosition : this.position;
  39441. };
  39442. /**
  39443. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39444. * Returns the updated DirectionalLight direction (Vector3).
  39445. */
  39446. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39447. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39448. return this.direction;
  39449. };
  39450. /**
  39451. * Returns the light rotation (Vector3).
  39452. */
  39453. ShadowLight.prototype.getRotation = function () {
  39454. this.direction.normalize();
  39455. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39456. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39457. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39458. };
  39459. /**
  39460. * Boolean : false by default.
  39461. */
  39462. ShadowLight.prototype.needCube = function () {
  39463. return false;
  39464. };
  39465. /**
  39466. * Specifies wether or not the projection matrix should be recomputed this frame.
  39467. */
  39468. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39469. return this._needProjectionMatrixCompute;
  39470. };
  39471. /**
  39472. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39473. */
  39474. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39475. this._needProjectionMatrixCompute = true;
  39476. };
  39477. /**
  39478. * Get the world matrix of the sahdow lights.
  39479. */
  39480. ShadowLight.prototype._getWorldMatrix = function () {
  39481. if (!this._worldMatrix) {
  39482. this._worldMatrix = BABYLON.Matrix.Identity();
  39483. }
  39484. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39485. return this._worldMatrix;
  39486. };
  39487. /**
  39488. * Gets the minZ used for shadow according to both the scene and the light.
  39489. * @param activeCamera
  39490. */
  39491. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39492. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39493. };
  39494. /**
  39495. * Gets the maxZ used for shadow according to both the scene and the light.
  39496. * @param activeCamera
  39497. */
  39498. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39499. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39500. };
  39501. /**
  39502. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39503. * Returns the light.
  39504. */
  39505. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39506. if (this.customProjectionMatrixBuilder) {
  39507. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39508. }
  39509. else {
  39510. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39511. }
  39512. return this;
  39513. };
  39514. __decorate([
  39515. BABYLON.serializeAsVector3()
  39516. ], ShadowLight.prototype, "position", void 0);
  39517. __decorate([
  39518. BABYLON.serializeAsVector3()
  39519. ], ShadowLight.prototype, "direction", null);
  39520. __decorate([
  39521. BABYLON.serialize()
  39522. ], ShadowLight.prototype, "shadowMinZ", null);
  39523. __decorate([
  39524. BABYLON.serialize()
  39525. ], ShadowLight.prototype, "shadowMaxZ", null);
  39526. return ShadowLight;
  39527. }(BABYLON.Light));
  39528. BABYLON.ShadowLight = ShadowLight;
  39529. })(BABYLON || (BABYLON = {}));
  39530. //# sourceMappingURL=babylon.shadowLight.js.map
  39531. var BABYLON;
  39532. (function (BABYLON) {
  39533. var PointLight = /** @class */ (function (_super) {
  39534. __extends(PointLight, _super);
  39535. /**
  39536. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39537. * A PointLight emits the light in every direction.
  39538. * It can cast shadows.
  39539. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39540. * ```javascript
  39541. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39542. * ```
  39543. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39544. */
  39545. function PointLight(name, position, scene) {
  39546. var _this = _super.call(this, name, scene) || this;
  39547. _this._shadowAngle = Math.PI / 2;
  39548. _this.position = position;
  39549. return _this;
  39550. }
  39551. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39552. /**
  39553. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39554. * This specifies what angle the shadow will use to be created.
  39555. *
  39556. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39557. */
  39558. get: function () {
  39559. return this._shadowAngle;
  39560. },
  39561. /**
  39562. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39563. * This specifies what angle the shadow will use to be created.
  39564. *
  39565. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39566. */
  39567. set: function (value) {
  39568. this._shadowAngle = value;
  39569. this.forceProjectionMatrixCompute();
  39570. },
  39571. enumerable: true,
  39572. configurable: true
  39573. });
  39574. Object.defineProperty(PointLight.prototype, "direction", {
  39575. get: function () {
  39576. return this._direction;
  39577. },
  39578. /**
  39579. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39580. */
  39581. set: function (value) {
  39582. var previousNeedCube = this.needCube();
  39583. this._direction = value;
  39584. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  39585. this._shadowGenerator.recreateShadowMap();
  39586. }
  39587. },
  39588. enumerable: true,
  39589. configurable: true
  39590. });
  39591. /**
  39592. * Returns the string "PointLight"
  39593. */
  39594. PointLight.prototype.getClassName = function () {
  39595. return "PointLight";
  39596. };
  39597. /**
  39598. * Returns the integer 0.
  39599. */
  39600. PointLight.prototype.getTypeID = function () {
  39601. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  39602. };
  39603. /**
  39604. * Specifies wether or not the shadowmap should be a cube texture.
  39605. */
  39606. PointLight.prototype.needCube = function () {
  39607. return !this.direction;
  39608. };
  39609. /**
  39610. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  39611. */
  39612. PointLight.prototype.getShadowDirection = function (faceIndex) {
  39613. if (this.direction) {
  39614. return _super.prototype.getShadowDirection.call(this, faceIndex);
  39615. }
  39616. else {
  39617. switch (faceIndex) {
  39618. case 0:
  39619. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  39620. case 1:
  39621. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  39622. case 2:
  39623. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  39624. case 3:
  39625. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  39626. case 4:
  39627. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  39628. case 5:
  39629. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  39630. }
  39631. }
  39632. return BABYLON.Vector3.Zero();
  39633. };
  39634. /**
  39635. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  39636. * - fov = PI / 2
  39637. * - aspect ratio : 1.0
  39638. * - z-near and far equal to the active camera minZ and maxZ.
  39639. * Returns the PointLight.
  39640. */
  39641. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39642. var activeCamera = this.getScene().activeCamera;
  39643. if (!activeCamera) {
  39644. return;
  39645. }
  39646. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39647. };
  39648. PointLight.prototype._buildUniformLayout = function () {
  39649. this._uniformBuffer.addUniform("vLightData", 4);
  39650. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39651. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39652. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39653. this._uniformBuffer.addUniform("depthValues", 2);
  39654. this._uniformBuffer.create();
  39655. };
  39656. /**
  39657. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  39658. * Returns the PointLight.
  39659. */
  39660. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  39661. if (this.computeTransformedInformation()) {
  39662. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  39663. return this;
  39664. }
  39665. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  39666. return this;
  39667. };
  39668. __decorate([
  39669. BABYLON.serialize()
  39670. ], PointLight.prototype, "shadowAngle", null);
  39671. return PointLight;
  39672. }(BABYLON.ShadowLight));
  39673. BABYLON.PointLight = PointLight;
  39674. })(BABYLON || (BABYLON = {}));
  39675. //# sourceMappingURL=babylon.pointLight.js.map
  39676. var BABYLON;
  39677. (function (BABYLON) {
  39678. var DirectionalLight = /** @class */ (function (_super) {
  39679. __extends(DirectionalLight, _super);
  39680. /**
  39681. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  39682. * The directional light is emitted from everywhere in the given direction.
  39683. * It can cast shawdows.
  39684. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39685. */
  39686. function DirectionalLight(name, direction, scene) {
  39687. var _this = _super.call(this, name, scene) || this;
  39688. _this._shadowFrustumSize = 0;
  39689. _this._shadowOrthoScale = 0.5;
  39690. _this.autoUpdateExtends = true;
  39691. // Cache
  39692. _this._orthoLeft = Number.MAX_VALUE;
  39693. _this._orthoRight = Number.MIN_VALUE;
  39694. _this._orthoTop = Number.MIN_VALUE;
  39695. _this._orthoBottom = Number.MAX_VALUE;
  39696. _this.position = direction.scale(-1.0);
  39697. _this.direction = direction;
  39698. return _this;
  39699. }
  39700. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  39701. /**
  39702. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  39703. */
  39704. get: function () {
  39705. return this._shadowFrustumSize;
  39706. },
  39707. /**
  39708. * Specifies a fix frustum size for the shadow generation.
  39709. */
  39710. set: function (value) {
  39711. this._shadowFrustumSize = value;
  39712. this.forceProjectionMatrixCompute();
  39713. },
  39714. enumerable: true,
  39715. configurable: true
  39716. });
  39717. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  39718. get: function () {
  39719. return this._shadowOrthoScale;
  39720. },
  39721. set: function (value) {
  39722. this._shadowOrthoScale = value;
  39723. this.forceProjectionMatrixCompute();
  39724. },
  39725. enumerable: true,
  39726. configurable: true
  39727. });
  39728. /**
  39729. * Returns the string "DirectionalLight".
  39730. */
  39731. DirectionalLight.prototype.getClassName = function () {
  39732. return "DirectionalLight";
  39733. };
  39734. /**
  39735. * Returns the integer 1.
  39736. */
  39737. DirectionalLight.prototype.getTypeID = function () {
  39738. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  39739. };
  39740. /**
  39741. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  39742. * Returns the DirectionalLight Shadow projection matrix.
  39743. */
  39744. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39745. if (this.shadowFrustumSize > 0) {
  39746. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  39747. }
  39748. else {
  39749. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39750. }
  39751. };
  39752. /**
  39753. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  39754. * Returns the DirectionalLight Shadow projection matrix.
  39755. */
  39756. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  39757. var activeCamera = this.getScene().activeCamera;
  39758. if (!activeCamera) {
  39759. return;
  39760. }
  39761. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39762. };
  39763. /**
  39764. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  39765. * Returns the DirectionalLight Shadow projection matrix.
  39766. */
  39767. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39768. var activeCamera = this.getScene().activeCamera;
  39769. if (!activeCamera) {
  39770. return;
  39771. }
  39772. // Check extends
  39773. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  39774. var tempVector3 = BABYLON.Vector3.Zero();
  39775. this._orthoLeft = Number.MAX_VALUE;
  39776. this._orthoRight = Number.MIN_VALUE;
  39777. this._orthoTop = Number.MIN_VALUE;
  39778. this._orthoBottom = Number.MAX_VALUE;
  39779. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  39780. var mesh = renderList[meshIndex];
  39781. if (!mesh) {
  39782. continue;
  39783. }
  39784. var boundingInfo = mesh.getBoundingInfo();
  39785. if (!boundingInfo) {
  39786. continue;
  39787. }
  39788. var boundingBox = boundingInfo.boundingBox;
  39789. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  39790. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  39791. if (tempVector3.x < this._orthoLeft)
  39792. this._orthoLeft = tempVector3.x;
  39793. if (tempVector3.y < this._orthoBottom)
  39794. this._orthoBottom = tempVector3.y;
  39795. if (tempVector3.x > this._orthoRight)
  39796. this._orthoRight = tempVector3.x;
  39797. if (tempVector3.y > this._orthoTop)
  39798. this._orthoTop = tempVector3.y;
  39799. }
  39800. }
  39801. }
  39802. var xOffset = this._orthoRight - this._orthoLeft;
  39803. var yOffset = this._orthoTop - this._orthoBottom;
  39804. 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);
  39805. };
  39806. DirectionalLight.prototype._buildUniformLayout = function () {
  39807. this._uniformBuffer.addUniform("vLightData", 4);
  39808. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39809. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39810. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39811. this._uniformBuffer.addUniform("depthValues", 2);
  39812. this._uniformBuffer.create();
  39813. };
  39814. /**
  39815. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39816. * Returns the DirectionalLight.
  39817. */
  39818. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39819. if (this.computeTransformedInformation()) {
  39820. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39821. return this;
  39822. }
  39823. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39824. return this;
  39825. };
  39826. /**
  39827. * Gets the minZ used for shadow according to both the scene and the light.
  39828. *
  39829. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39830. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39831. * @param activeCamera
  39832. */
  39833. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39834. return 1;
  39835. };
  39836. /**
  39837. * Gets the maxZ used for shadow according to both the scene and the light.
  39838. *
  39839. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39840. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39841. * @param activeCamera
  39842. */
  39843. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39844. return 1;
  39845. };
  39846. __decorate([
  39847. BABYLON.serialize()
  39848. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39849. __decorate([
  39850. BABYLON.serialize()
  39851. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39852. __decorate([
  39853. BABYLON.serialize()
  39854. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39855. return DirectionalLight;
  39856. }(BABYLON.ShadowLight));
  39857. BABYLON.DirectionalLight = DirectionalLight;
  39858. })(BABYLON || (BABYLON = {}));
  39859. //# sourceMappingURL=babylon.directionalLight.js.map
  39860. var BABYLON;
  39861. (function (BABYLON) {
  39862. var SpotLight = /** @class */ (function (_super) {
  39863. __extends(SpotLight, _super);
  39864. /**
  39865. * Creates a SpotLight object in the scene with the passed parameters :
  39866. * - `position` (Vector3) is the initial SpotLight position,
  39867. * - `direction` (Vector3) is the initial SpotLight direction,
  39868. * - `angle` (float, in radians) is the spot light cone angle,
  39869. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39870. * A spot light is a simply light oriented cone.
  39871. * It can cast shadows.
  39872. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39873. */
  39874. function SpotLight(name, position, direction, angle, exponent, scene) {
  39875. var _this = _super.call(this, name, scene) || this;
  39876. _this.position = position;
  39877. _this.direction = direction;
  39878. _this.angle = angle;
  39879. _this.exponent = exponent;
  39880. return _this;
  39881. }
  39882. Object.defineProperty(SpotLight.prototype, "angle", {
  39883. get: function () {
  39884. return this._angle;
  39885. },
  39886. set: function (value) {
  39887. this._angle = value;
  39888. this.forceProjectionMatrixCompute();
  39889. },
  39890. enumerable: true,
  39891. configurable: true
  39892. });
  39893. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39894. get: function () {
  39895. return this._shadowAngleScale;
  39896. },
  39897. /**
  39898. * Allows scaling the angle of the light for shadow generation only.
  39899. */
  39900. set: function (value) {
  39901. this._shadowAngleScale = value;
  39902. this.forceProjectionMatrixCompute();
  39903. },
  39904. enumerable: true,
  39905. configurable: true
  39906. });
  39907. /**
  39908. * Returns the string "SpotLight".
  39909. */
  39910. SpotLight.prototype.getClassName = function () {
  39911. return "SpotLight";
  39912. };
  39913. /**
  39914. * Returns the integer 2.
  39915. */
  39916. SpotLight.prototype.getTypeID = function () {
  39917. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  39918. };
  39919. /**
  39920. * 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.
  39921. * Returns the SpotLight.
  39922. */
  39923. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39924. var activeCamera = this.getScene().activeCamera;
  39925. if (!activeCamera) {
  39926. return;
  39927. }
  39928. this._shadowAngleScale = this._shadowAngleScale || 1;
  39929. var angle = this._shadowAngleScale * this._angle;
  39930. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39931. };
  39932. SpotLight.prototype._buildUniformLayout = function () {
  39933. this._uniformBuffer.addUniform("vLightData", 4);
  39934. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39935. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39936. this._uniformBuffer.addUniform("vLightDirection", 3);
  39937. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39938. this._uniformBuffer.addUniform("depthValues", 2);
  39939. this._uniformBuffer.create();
  39940. };
  39941. /**
  39942. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  39943. * Return the SpotLight.
  39944. */
  39945. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  39946. var normalizeDirection;
  39947. if (this.computeTransformedInformation()) {
  39948. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  39949. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  39950. }
  39951. else {
  39952. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  39953. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39954. }
  39955. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  39956. return this;
  39957. };
  39958. __decorate([
  39959. BABYLON.serialize()
  39960. ], SpotLight.prototype, "angle", null);
  39961. __decorate([
  39962. BABYLON.serialize()
  39963. /**
  39964. * Allows scaling the angle of the light for shadow generation only.
  39965. */
  39966. ], SpotLight.prototype, "shadowAngleScale", null);
  39967. __decorate([
  39968. BABYLON.serialize()
  39969. ], SpotLight.prototype, "exponent", void 0);
  39970. return SpotLight;
  39971. }(BABYLON.ShadowLight));
  39972. BABYLON.SpotLight = SpotLight;
  39973. })(BABYLON || (BABYLON = {}));
  39974. //# sourceMappingURL=babylon.spotLight.js.map
  39975. var BABYLON;
  39976. (function (BABYLON) {
  39977. var AnimationRange = /** @class */ (function () {
  39978. function AnimationRange(name, from, to) {
  39979. this.name = name;
  39980. this.from = from;
  39981. this.to = to;
  39982. }
  39983. AnimationRange.prototype.clone = function () {
  39984. return new AnimationRange(this.name, this.from, this.to);
  39985. };
  39986. return AnimationRange;
  39987. }());
  39988. BABYLON.AnimationRange = AnimationRange;
  39989. /**
  39990. * Composed of a frame, and an action function
  39991. */
  39992. var AnimationEvent = /** @class */ (function () {
  39993. function AnimationEvent(frame, action, onlyOnce) {
  39994. this.frame = frame;
  39995. this.action = action;
  39996. this.onlyOnce = onlyOnce;
  39997. this.isDone = false;
  39998. }
  39999. return AnimationEvent;
  40000. }());
  40001. BABYLON.AnimationEvent = AnimationEvent;
  40002. var PathCursor = /** @class */ (function () {
  40003. function PathCursor(path) {
  40004. this.path = path;
  40005. this._onchange = new Array();
  40006. this.value = 0;
  40007. this.animations = new Array();
  40008. }
  40009. PathCursor.prototype.getPoint = function () {
  40010. var point = this.path.getPointAtLengthPosition(this.value);
  40011. return new BABYLON.Vector3(point.x, 0, point.y);
  40012. };
  40013. PathCursor.prototype.moveAhead = function (step) {
  40014. if (step === void 0) { step = 0.002; }
  40015. this.move(step);
  40016. return this;
  40017. };
  40018. PathCursor.prototype.moveBack = function (step) {
  40019. if (step === void 0) { step = 0.002; }
  40020. this.move(-step);
  40021. return this;
  40022. };
  40023. PathCursor.prototype.move = function (step) {
  40024. if (Math.abs(step) > 1) {
  40025. throw "step size should be less than 1.";
  40026. }
  40027. this.value += step;
  40028. this.ensureLimits();
  40029. this.raiseOnChange();
  40030. return this;
  40031. };
  40032. PathCursor.prototype.ensureLimits = function () {
  40033. while (this.value > 1) {
  40034. this.value -= 1;
  40035. }
  40036. while (this.value < 0) {
  40037. this.value += 1;
  40038. }
  40039. return this;
  40040. };
  40041. // used by animation engine
  40042. PathCursor.prototype.raiseOnChange = function () {
  40043. var _this = this;
  40044. this._onchange.forEach(function (f) { return f(_this); });
  40045. return this;
  40046. };
  40047. PathCursor.prototype.onchange = function (f) {
  40048. this._onchange.push(f);
  40049. return this;
  40050. };
  40051. return PathCursor;
  40052. }());
  40053. BABYLON.PathCursor = PathCursor;
  40054. var Animation = /** @class */ (function () {
  40055. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  40056. this.name = name;
  40057. this.targetProperty = targetProperty;
  40058. this.framePerSecond = framePerSecond;
  40059. this.dataType = dataType;
  40060. this.loopMode = loopMode;
  40061. this.enableBlending = enableBlending;
  40062. this._runtimeAnimations = new Array();
  40063. // The set of event that will be linked to this animation
  40064. this._events = new Array();
  40065. this.blendingSpeed = 0.01;
  40066. this._ranges = {};
  40067. this.targetPropertyPath = targetProperty.split(".");
  40068. this.dataType = dataType;
  40069. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  40070. }
  40071. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  40072. var dataType = undefined;
  40073. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  40074. dataType = Animation.ANIMATIONTYPE_FLOAT;
  40075. }
  40076. else if (from instanceof BABYLON.Quaternion) {
  40077. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  40078. }
  40079. else if (from instanceof BABYLON.Vector3) {
  40080. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  40081. }
  40082. else if (from instanceof BABYLON.Vector2) {
  40083. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40084. }
  40085. else if (from instanceof BABYLON.Color3) {
  40086. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40087. }
  40088. else if (from instanceof BABYLON.Size) {
  40089. dataType = Animation.ANIMATIONTYPE_SIZE;
  40090. }
  40091. if (dataType == undefined) {
  40092. return null;
  40093. }
  40094. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40095. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40096. animation.setKeys(keys);
  40097. if (easingFunction !== undefined) {
  40098. animation.setEasingFunction(easingFunction);
  40099. }
  40100. return animation;
  40101. };
  40102. /**
  40103. * Sets up an animation.
  40104. * @param property the property to animate
  40105. * @param animationType the animation type to apply
  40106. * @param easingFunction the easing function used in the animation
  40107. * @returns The created animation
  40108. */
  40109. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40110. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40111. animation.setEasingFunction(easingFunction);
  40112. return animation;
  40113. };
  40114. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40115. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40116. if (!animation) {
  40117. return null;
  40118. }
  40119. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40120. };
  40121. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40122. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40123. if (!animation) {
  40124. return null;
  40125. }
  40126. node.animations.push(animation);
  40127. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40128. };
  40129. /**
  40130. * Transition property of the Camera to the target Value.
  40131. * @param property The property to transition
  40132. * @param targetValue The target Value of the property
  40133. * @param host The object where the property to animate belongs
  40134. * @param scene Scene used to run the animation
  40135. * @param frameRate Framerate (in frame/s) to use
  40136. * @param transition The transition type we want to use
  40137. * @param duration The duration of the animation, in milliseconds
  40138. * @param onAnimationEnd Call back trigger at the end of the animation.
  40139. */
  40140. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40141. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40142. if (duration <= 0) {
  40143. host[property] = targetValue;
  40144. if (onAnimationEnd) {
  40145. onAnimationEnd();
  40146. }
  40147. return null;
  40148. }
  40149. var endFrame = frameRate * (duration / 1000);
  40150. transition.setKeys([{
  40151. frame: 0,
  40152. value: host[property].clone ? host[property].clone() : host[property]
  40153. },
  40154. {
  40155. frame: endFrame,
  40156. value: targetValue
  40157. }]);
  40158. if (!host.animations) {
  40159. host.animations = [];
  40160. }
  40161. host.animations.push(transition);
  40162. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40163. animation.onAnimationEnd = onAnimationEnd;
  40164. return animation;
  40165. };
  40166. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40167. /**
  40168. * Return the array of runtime animations currently using this animation
  40169. */
  40170. get: function () {
  40171. return this._runtimeAnimations;
  40172. },
  40173. enumerable: true,
  40174. configurable: true
  40175. });
  40176. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40177. get: function () {
  40178. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40179. var runtimeAnimation = _a[_i];
  40180. if (!runtimeAnimation.isStopped) {
  40181. return true;
  40182. }
  40183. }
  40184. return false;
  40185. },
  40186. enumerable: true,
  40187. configurable: true
  40188. });
  40189. // Methods
  40190. /**
  40191. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40192. */
  40193. Animation.prototype.toString = function (fullDetails) {
  40194. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40195. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40196. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40197. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40198. if (fullDetails) {
  40199. ret += ", Ranges: {";
  40200. var first = true;
  40201. for (var name in this._ranges) {
  40202. if (first) {
  40203. ret += ", ";
  40204. first = false;
  40205. }
  40206. ret += name;
  40207. }
  40208. ret += "}";
  40209. }
  40210. return ret;
  40211. };
  40212. /**
  40213. * Add an event to this animation.
  40214. */
  40215. Animation.prototype.addEvent = function (event) {
  40216. this._events.push(event);
  40217. };
  40218. /**
  40219. * Remove all events found at the given frame
  40220. * @param frame
  40221. */
  40222. Animation.prototype.removeEvents = function (frame) {
  40223. for (var index = 0; index < this._events.length; index++) {
  40224. if (this._events[index].frame === frame) {
  40225. this._events.splice(index, 1);
  40226. index--;
  40227. }
  40228. }
  40229. };
  40230. Animation.prototype.getEvents = function () {
  40231. return this._events;
  40232. };
  40233. Animation.prototype.createRange = function (name, from, to) {
  40234. // check name not already in use; could happen for bones after serialized
  40235. if (!this._ranges[name]) {
  40236. this._ranges[name] = new AnimationRange(name, from, to);
  40237. }
  40238. };
  40239. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40240. if (deleteFrames === void 0) { deleteFrames = true; }
  40241. var range = this._ranges[name];
  40242. if (!range) {
  40243. return;
  40244. }
  40245. if (deleteFrames) {
  40246. var from = range.from;
  40247. var to = range.to;
  40248. // this loop MUST go high to low for multiple splices to work
  40249. for (var key = this._keys.length - 1; key >= 0; key--) {
  40250. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40251. this._keys.splice(key, 1);
  40252. }
  40253. }
  40254. }
  40255. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40256. };
  40257. Animation.prototype.getRange = function (name) {
  40258. return this._ranges[name];
  40259. };
  40260. Animation.prototype.getKeys = function () {
  40261. return this._keys;
  40262. };
  40263. Animation.prototype.getHighestFrame = function () {
  40264. var ret = 0;
  40265. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40266. if (ret < this._keys[key].frame) {
  40267. ret = this._keys[key].frame;
  40268. }
  40269. }
  40270. return ret;
  40271. };
  40272. Animation.prototype.getEasingFunction = function () {
  40273. return this._easingFunction;
  40274. };
  40275. Animation.prototype.setEasingFunction = function (easingFunction) {
  40276. this._easingFunction = easingFunction;
  40277. };
  40278. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40279. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40280. };
  40281. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40282. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40283. };
  40284. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40285. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40286. };
  40287. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40288. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40289. };
  40290. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40291. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40292. };
  40293. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40294. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40295. };
  40296. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40297. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40298. };
  40299. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40300. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40301. };
  40302. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40303. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40304. };
  40305. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40306. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40307. };
  40308. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40309. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40310. };
  40311. Animation.prototype.clone = function () {
  40312. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40313. clone.enableBlending = this.enableBlending;
  40314. clone.blendingSpeed = this.blendingSpeed;
  40315. if (this._keys) {
  40316. clone.setKeys(this._keys);
  40317. }
  40318. if (this._ranges) {
  40319. clone._ranges = {};
  40320. for (var name in this._ranges) {
  40321. var range = this._ranges[name];
  40322. if (!range) {
  40323. continue;
  40324. }
  40325. clone._ranges[name] = range.clone();
  40326. }
  40327. }
  40328. return clone;
  40329. };
  40330. Animation.prototype.setKeys = function (values) {
  40331. this._keys = values.slice(0);
  40332. };
  40333. Animation.prototype.serialize = function () {
  40334. var serializationObject = {};
  40335. serializationObject.name = this.name;
  40336. serializationObject.property = this.targetProperty;
  40337. serializationObject.framePerSecond = this.framePerSecond;
  40338. serializationObject.dataType = this.dataType;
  40339. serializationObject.loopBehavior = this.loopMode;
  40340. serializationObject.enableBlending = this.enableBlending;
  40341. serializationObject.blendingSpeed = this.blendingSpeed;
  40342. var dataType = this.dataType;
  40343. serializationObject.keys = [];
  40344. var keys = this.getKeys();
  40345. for (var index = 0; index < keys.length; index++) {
  40346. var animationKey = keys[index];
  40347. var key = {};
  40348. key.frame = animationKey.frame;
  40349. switch (dataType) {
  40350. case Animation.ANIMATIONTYPE_FLOAT:
  40351. key.values = [animationKey.value];
  40352. break;
  40353. case Animation.ANIMATIONTYPE_QUATERNION:
  40354. case Animation.ANIMATIONTYPE_MATRIX:
  40355. case Animation.ANIMATIONTYPE_VECTOR3:
  40356. case Animation.ANIMATIONTYPE_COLOR3:
  40357. key.values = animationKey.value.asArray();
  40358. break;
  40359. }
  40360. serializationObject.keys.push(key);
  40361. }
  40362. serializationObject.ranges = [];
  40363. for (var name in this._ranges) {
  40364. var source = this._ranges[name];
  40365. if (!source) {
  40366. continue;
  40367. }
  40368. var range = {};
  40369. range.name = name;
  40370. range.from = source.from;
  40371. range.to = source.to;
  40372. serializationObject.ranges.push(range);
  40373. }
  40374. return serializationObject;
  40375. };
  40376. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40377. get: function () {
  40378. return Animation._ANIMATIONTYPE_FLOAT;
  40379. },
  40380. enumerable: true,
  40381. configurable: true
  40382. });
  40383. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40384. get: function () {
  40385. return Animation._ANIMATIONTYPE_VECTOR3;
  40386. },
  40387. enumerable: true,
  40388. configurable: true
  40389. });
  40390. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40391. get: function () {
  40392. return Animation._ANIMATIONTYPE_VECTOR2;
  40393. },
  40394. enumerable: true,
  40395. configurable: true
  40396. });
  40397. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40398. get: function () {
  40399. return Animation._ANIMATIONTYPE_SIZE;
  40400. },
  40401. enumerable: true,
  40402. configurable: true
  40403. });
  40404. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40405. get: function () {
  40406. return Animation._ANIMATIONTYPE_QUATERNION;
  40407. },
  40408. enumerable: true,
  40409. configurable: true
  40410. });
  40411. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40412. get: function () {
  40413. return Animation._ANIMATIONTYPE_MATRIX;
  40414. },
  40415. enumerable: true,
  40416. configurable: true
  40417. });
  40418. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40419. get: function () {
  40420. return Animation._ANIMATIONTYPE_COLOR3;
  40421. },
  40422. enumerable: true,
  40423. configurable: true
  40424. });
  40425. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40426. get: function () {
  40427. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40428. },
  40429. enumerable: true,
  40430. configurable: true
  40431. });
  40432. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40433. get: function () {
  40434. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40435. },
  40436. enumerable: true,
  40437. configurable: true
  40438. });
  40439. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40440. get: function () {
  40441. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40442. },
  40443. enumerable: true,
  40444. configurable: true
  40445. });
  40446. Animation.Parse = function (parsedAnimation) {
  40447. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40448. var dataType = parsedAnimation.dataType;
  40449. var keys = [];
  40450. var data;
  40451. var index;
  40452. if (parsedAnimation.enableBlending) {
  40453. animation.enableBlending = parsedAnimation.enableBlending;
  40454. }
  40455. if (parsedAnimation.blendingSpeed) {
  40456. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40457. }
  40458. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40459. var key = parsedAnimation.keys[index];
  40460. var inTangent;
  40461. var outTangent;
  40462. switch (dataType) {
  40463. case Animation.ANIMATIONTYPE_FLOAT:
  40464. data = key.values[0];
  40465. if (key.values.length >= 1) {
  40466. inTangent = key.values[1];
  40467. }
  40468. if (key.values.length >= 2) {
  40469. outTangent = key.values[2];
  40470. }
  40471. break;
  40472. case Animation.ANIMATIONTYPE_QUATERNION:
  40473. data = BABYLON.Quaternion.FromArray(key.values);
  40474. if (key.values.length >= 8) {
  40475. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40476. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40477. inTangent = _inTangent;
  40478. }
  40479. }
  40480. if (key.values.length >= 12) {
  40481. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40482. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40483. outTangent = _outTangent;
  40484. }
  40485. }
  40486. break;
  40487. case Animation.ANIMATIONTYPE_MATRIX:
  40488. data = BABYLON.Matrix.FromArray(key.values);
  40489. break;
  40490. case Animation.ANIMATIONTYPE_COLOR3:
  40491. data = BABYLON.Color3.FromArray(key.values);
  40492. break;
  40493. case Animation.ANIMATIONTYPE_VECTOR3:
  40494. default:
  40495. data = BABYLON.Vector3.FromArray(key.values);
  40496. break;
  40497. }
  40498. var keyData = {};
  40499. keyData.frame = key.frame;
  40500. keyData.value = data;
  40501. if (inTangent != undefined) {
  40502. keyData.inTangent = inTangent;
  40503. }
  40504. if (outTangent != undefined) {
  40505. keyData.outTangent = outTangent;
  40506. }
  40507. keys.push(keyData);
  40508. }
  40509. animation.setKeys(keys);
  40510. if (parsedAnimation.ranges) {
  40511. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40512. data = parsedAnimation.ranges[index];
  40513. animation.createRange(data.name, data.from, data.to);
  40514. }
  40515. }
  40516. return animation;
  40517. };
  40518. Animation.AppendSerializedAnimations = function (source, destination) {
  40519. if (source.animations) {
  40520. destination.animations = [];
  40521. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40522. var animation = source.animations[animationIndex];
  40523. destination.animations.push(animation.serialize());
  40524. }
  40525. }
  40526. };
  40527. Animation.AllowMatricesInterpolation = false;
  40528. // Statics
  40529. Animation._ANIMATIONTYPE_FLOAT = 0;
  40530. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40531. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40532. Animation._ANIMATIONTYPE_MATRIX = 3;
  40533. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40534. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40535. Animation._ANIMATIONTYPE_SIZE = 6;
  40536. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40537. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40538. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40539. return Animation;
  40540. }());
  40541. BABYLON.Animation = Animation;
  40542. })(BABYLON || (BABYLON = {}));
  40543. //# sourceMappingURL=babylon.animation.js.map
  40544. var BABYLON;
  40545. (function (BABYLON) {
  40546. var RuntimeAnimation = /** @class */ (function () {
  40547. function RuntimeAnimation(target, animation) {
  40548. this._offsetsCache = {};
  40549. this._highLimitsCache = {};
  40550. this._stopped = false;
  40551. this._blendingFactor = 0;
  40552. this._ratioOffset = 0;
  40553. this._animation = animation;
  40554. this._target = target;
  40555. animation._runtimeAnimations.push(this);
  40556. }
  40557. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40558. get: function () {
  40559. return this._animation;
  40560. },
  40561. enumerable: true,
  40562. configurable: true
  40563. });
  40564. RuntimeAnimation.prototype.reset = function () {
  40565. this._offsetsCache = {};
  40566. this._highLimitsCache = {};
  40567. this.currentFrame = 0;
  40568. this._blendingFactor = 0;
  40569. this._originalBlendValue = null;
  40570. };
  40571. RuntimeAnimation.prototype.isStopped = function () {
  40572. return this._stopped;
  40573. };
  40574. RuntimeAnimation.prototype.dispose = function () {
  40575. var index = this._animation.runtimeAnimations.indexOf(this);
  40576. if (index > -1) {
  40577. this._animation.runtimeAnimations.splice(index, 1);
  40578. }
  40579. };
  40580. RuntimeAnimation.prototype._getKeyValue = function (value) {
  40581. if (typeof value === "function") {
  40582. return value();
  40583. }
  40584. return value;
  40585. };
  40586. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  40587. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  40588. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  40589. }
  40590. this.currentFrame = currentFrame;
  40591. var keys = this._animation.getKeys();
  40592. // Try to get a hash to find the right key
  40593. 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));
  40594. if (keys[startKeyIndex].frame >= currentFrame) {
  40595. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  40596. startKeyIndex--;
  40597. }
  40598. }
  40599. for (var key = startKeyIndex; key < keys.length; key++) {
  40600. var endKey = keys[key + 1];
  40601. if (endKey.frame >= currentFrame) {
  40602. var startKey = keys[key];
  40603. var startValue = this._getKeyValue(startKey.value);
  40604. var endValue = this._getKeyValue(endKey.value);
  40605. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  40606. var frameDelta = endKey.frame - startKey.frame;
  40607. // gradient : percent of currentFrame between the frame inf and the frame sup
  40608. var gradient = (currentFrame - startKey.frame) / frameDelta;
  40609. // check for easingFunction and correction of gradient
  40610. var easingFunction = this._animation.getEasingFunction();
  40611. if (easingFunction != null) {
  40612. gradient = easingFunction.ease(gradient);
  40613. }
  40614. switch (this._animation.dataType) {
  40615. // Float
  40616. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40617. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  40618. switch (loopMode) {
  40619. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40620. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40621. return floatValue;
  40622. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40623. return offsetValue * repeatCount + floatValue;
  40624. }
  40625. break;
  40626. // Quaternion
  40627. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40628. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  40629. switch (loopMode) {
  40630. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40631. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40632. return quatValue;
  40633. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40634. return quatValue.add(offsetValue.scale(repeatCount));
  40635. }
  40636. return quatValue;
  40637. // Vector3
  40638. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40639. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  40640. switch (loopMode) {
  40641. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40642. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40643. return vec3Value;
  40644. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40645. return vec3Value.add(offsetValue.scale(repeatCount));
  40646. }
  40647. // Vector2
  40648. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40649. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  40650. switch (loopMode) {
  40651. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40652. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40653. return vec2Value;
  40654. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40655. return vec2Value.add(offsetValue.scale(repeatCount));
  40656. }
  40657. // Size
  40658. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40659. switch (loopMode) {
  40660. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40661. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40662. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  40663. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40664. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40665. }
  40666. // Color3
  40667. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40668. switch (loopMode) {
  40669. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40670. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40671. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  40672. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40673. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40674. }
  40675. // Matrix
  40676. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  40677. switch (loopMode) {
  40678. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40679. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40680. if (BABYLON.Animation.AllowMatricesInterpolation) {
  40681. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  40682. }
  40683. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40684. return startValue;
  40685. }
  40686. default:
  40687. break;
  40688. }
  40689. break;
  40690. }
  40691. }
  40692. return this._getKeyValue(keys[keys.length - 1].value);
  40693. };
  40694. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  40695. if (blend === void 0) { blend = false; }
  40696. // Set value
  40697. var path;
  40698. var destination;
  40699. var targetPropertyPath = this._animation.targetPropertyPath;
  40700. if (targetPropertyPath.length > 1) {
  40701. var property = this._target[targetPropertyPath[0]];
  40702. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  40703. property = property[targetPropertyPath[index]];
  40704. }
  40705. path = targetPropertyPath[targetPropertyPath.length - 1];
  40706. destination = property;
  40707. }
  40708. else {
  40709. path = targetPropertyPath[0];
  40710. destination = this._target;
  40711. }
  40712. // Blending
  40713. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  40714. if (!this._originalBlendValue) {
  40715. if (destination[path].clone) {
  40716. this._originalBlendValue = destination[path].clone();
  40717. }
  40718. else {
  40719. this._originalBlendValue = destination[path];
  40720. }
  40721. }
  40722. if (this._originalBlendValue.prototype) {
  40723. if (this._originalBlendValue.prototype.Lerp) {
  40724. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  40725. }
  40726. else {
  40727. destination[path] = currentValue;
  40728. }
  40729. }
  40730. else if (this._originalBlendValue.m) {
  40731. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  40732. }
  40733. else {
  40734. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  40735. }
  40736. this._blendingFactor += this._animation.blendingSpeed;
  40737. }
  40738. else {
  40739. destination[path] = currentValue;
  40740. }
  40741. if (this._target.markAsDirty) {
  40742. this._target.markAsDirty(this._animation.targetProperty);
  40743. }
  40744. };
  40745. RuntimeAnimation.prototype.goToFrame = function (frame) {
  40746. var keys = this._animation.getKeys();
  40747. if (frame < keys[0].frame) {
  40748. frame = keys[0].frame;
  40749. }
  40750. else if (frame > keys[keys.length - 1].frame) {
  40751. frame = keys[keys.length - 1].frame;
  40752. }
  40753. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  40754. this.setValue(currentValue);
  40755. };
  40756. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  40757. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  40758. this._ratioOffset = this._previousRatio - newRatio;
  40759. };
  40760. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  40761. if (blend === void 0) { blend = false; }
  40762. var targetPropertyPath = this._animation.targetPropertyPath;
  40763. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  40764. this._stopped = true;
  40765. return false;
  40766. }
  40767. var returnValue = true;
  40768. var keys = this._animation.getKeys();
  40769. // Adding a start key at frame 0 if missing
  40770. if (keys[0].frame !== 0) {
  40771. var newKey = { frame: 0, value: keys[0].value };
  40772. keys.splice(0, 0, newKey);
  40773. }
  40774. // Check limits
  40775. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  40776. from = keys[0].frame;
  40777. }
  40778. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  40779. to = keys[keys.length - 1].frame;
  40780. }
  40781. //to and from cannot be the same key
  40782. if (from === to) {
  40783. if (from > keys[0].frame) {
  40784. from--;
  40785. }
  40786. else if (to < keys[keys.length - 1].frame) {
  40787. to++;
  40788. }
  40789. }
  40790. // Compute ratio
  40791. var range = to - from;
  40792. var offsetValue;
  40793. // ratio represents the frame delta between from and to
  40794. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40795. var highLimitValue = 0;
  40796. this._previousDelay = delay;
  40797. this._previousRatio = ratio;
  40798. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40799. returnValue = false;
  40800. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40801. }
  40802. else {
  40803. // Get max value if required
  40804. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40805. var keyOffset = to.toString() + from.toString();
  40806. if (!this._offsetsCache[keyOffset]) {
  40807. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40808. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40809. switch (this._animation.dataType) {
  40810. // Float
  40811. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40812. this._offsetsCache[keyOffset] = toValue - fromValue;
  40813. break;
  40814. // Quaternion
  40815. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40816. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40817. break;
  40818. // Vector3
  40819. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40820. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40821. // Vector2
  40822. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40823. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40824. // Size
  40825. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40826. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40827. // Color3
  40828. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40829. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40830. default:
  40831. break;
  40832. }
  40833. this._highLimitsCache[keyOffset] = toValue;
  40834. }
  40835. highLimitValue = this._highLimitsCache[keyOffset];
  40836. offsetValue = this._offsetsCache[keyOffset];
  40837. }
  40838. }
  40839. if (offsetValue === undefined) {
  40840. switch (this._animation.dataType) {
  40841. // Float
  40842. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40843. offsetValue = 0;
  40844. break;
  40845. // Quaternion
  40846. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40847. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40848. break;
  40849. // Vector3
  40850. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40851. offsetValue = BABYLON.Vector3.Zero();
  40852. break;
  40853. // Vector2
  40854. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40855. offsetValue = BABYLON.Vector2.Zero();
  40856. break;
  40857. // Size
  40858. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40859. offsetValue = BABYLON.Size.Zero();
  40860. break;
  40861. // Color3
  40862. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40863. offsetValue = BABYLON.Color3.Black();
  40864. }
  40865. }
  40866. // Compute value
  40867. var repeatCount = (ratio / range) >> 0;
  40868. var currentFrame = returnValue ? from + ratio % range : to;
  40869. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40870. // Set value
  40871. this.setValue(currentValue);
  40872. // Check events
  40873. var events = this._animation.getEvents();
  40874. for (var index = 0; index < events.length; index++) {
  40875. // Make sure current frame has passed event frame and that event frame is within the current range
  40876. // Also, handle both forward and reverse animations
  40877. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40878. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40879. var event = events[index];
  40880. if (!event.isDone) {
  40881. // If event should be done only once, remove it.
  40882. if (event.onlyOnce) {
  40883. events.splice(index, 1);
  40884. index--;
  40885. }
  40886. event.isDone = true;
  40887. event.action();
  40888. } // Don't do anything if the event has already be done.
  40889. }
  40890. else if (events[index].isDone && !events[index].onlyOnce) {
  40891. // reset event, the animation is looping
  40892. events[index].isDone = false;
  40893. }
  40894. }
  40895. if (!returnValue) {
  40896. this._stopped = true;
  40897. }
  40898. return returnValue;
  40899. };
  40900. return RuntimeAnimation;
  40901. }());
  40902. BABYLON.RuntimeAnimation = RuntimeAnimation;
  40903. })(BABYLON || (BABYLON = {}));
  40904. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  40905. var BABYLON;
  40906. (function (BABYLON) {
  40907. var Animatable = /** @class */ (function () {
  40908. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  40909. if (fromFrame === void 0) { fromFrame = 0; }
  40910. if (toFrame === void 0) { toFrame = 100; }
  40911. if (loopAnimation === void 0) { loopAnimation = false; }
  40912. if (speedRatio === void 0) { speedRatio = 1.0; }
  40913. this.target = target;
  40914. this.fromFrame = fromFrame;
  40915. this.toFrame = toFrame;
  40916. this.loopAnimation = loopAnimation;
  40917. this.onAnimationEnd = onAnimationEnd;
  40918. this._localDelayOffset = null;
  40919. this._pausedDelay = null;
  40920. this._runtimeAnimations = new Array();
  40921. this._paused = false;
  40922. this._speedRatio = 1;
  40923. this.animationStarted = false;
  40924. if (animations) {
  40925. this.appendAnimations(target, animations);
  40926. }
  40927. this._speedRatio = speedRatio;
  40928. this._scene = scene;
  40929. scene._activeAnimatables.push(this);
  40930. }
  40931. Object.defineProperty(Animatable.prototype, "speedRatio", {
  40932. get: function () {
  40933. return this._speedRatio;
  40934. },
  40935. set: function (value) {
  40936. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  40937. var animation = this._runtimeAnimations[index];
  40938. animation._prepareForSpeedRatioChange(value);
  40939. }
  40940. this._speedRatio = value;
  40941. },
  40942. enumerable: true,
  40943. configurable: true
  40944. });
  40945. // Methods
  40946. Animatable.prototype.getAnimations = function () {
  40947. return this._runtimeAnimations;
  40948. };
  40949. Animatable.prototype.appendAnimations = function (target, animations) {
  40950. for (var index = 0; index < animations.length; index++) {
  40951. var animation = animations[index];
  40952. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  40953. }
  40954. };
  40955. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  40956. var runtimeAnimations = this._runtimeAnimations;
  40957. for (var index = 0; index < runtimeAnimations.length; index++) {
  40958. if (runtimeAnimations[index].animation.targetProperty === property) {
  40959. return runtimeAnimations[index].animation;
  40960. }
  40961. }
  40962. return null;
  40963. };
  40964. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  40965. var runtimeAnimations = this._runtimeAnimations;
  40966. for (var index = 0; index < runtimeAnimations.length; index++) {
  40967. if (runtimeAnimations[index].animation.targetProperty === property) {
  40968. return runtimeAnimations[index];
  40969. }
  40970. }
  40971. return null;
  40972. };
  40973. Animatable.prototype.reset = function () {
  40974. var runtimeAnimations = this._runtimeAnimations;
  40975. for (var index = 0; index < runtimeAnimations.length; index++) {
  40976. runtimeAnimations[index].reset();
  40977. }
  40978. this._localDelayOffset = null;
  40979. this._pausedDelay = null;
  40980. };
  40981. Animatable.prototype.enableBlending = function (blendingSpeed) {
  40982. var runtimeAnimations = this._runtimeAnimations;
  40983. for (var index = 0; index < runtimeAnimations.length; index++) {
  40984. runtimeAnimations[index].animation.enableBlending = true;
  40985. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  40986. }
  40987. };
  40988. Animatable.prototype.disableBlending = function () {
  40989. var runtimeAnimations = this._runtimeAnimations;
  40990. for (var index = 0; index < runtimeAnimations.length; index++) {
  40991. runtimeAnimations[index].animation.enableBlending = false;
  40992. }
  40993. };
  40994. Animatable.prototype.goToFrame = function (frame) {
  40995. var runtimeAnimations = this._runtimeAnimations;
  40996. if (runtimeAnimations[0]) {
  40997. var fps = runtimeAnimations[0].animation.framePerSecond;
  40998. var currentFrame = runtimeAnimations[0].currentFrame;
  40999. var adjustTime = frame - currentFrame;
  41000. var delay = adjustTime * 1000 / fps;
  41001. if (this._localDelayOffset === null) {
  41002. this._localDelayOffset = 0;
  41003. }
  41004. this._localDelayOffset -= delay;
  41005. }
  41006. for (var index = 0; index < runtimeAnimations.length; index++) {
  41007. runtimeAnimations[index].goToFrame(frame);
  41008. }
  41009. };
  41010. Animatable.prototype.pause = function () {
  41011. if (this._paused) {
  41012. return;
  41013. }
  41014. this._paused = true;
  41015. };
  41016. Animatable.prototype.restart = function () {
  41017. this._paused = false;
  41018. };
  41019. Animatable.prototype.stop = function (animationName) {
  41020. if (animationName) {
  41021. var idx = this._scene._activeAnimatables.indexOf(this);
  41022. if (idx > -1) {
  41023. var runtimeAnimations = this._runtimeAnimations;
  41024. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  41025. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  41026. continue;
  41027. }
  41028. runtimeAnimations[index].dispose();
  41029. runtimeAnimations.splice(index, 1);
  41030. }
  41031. if (runtimeAnimations.length == 0) {
  41032. this._scene._activeAnimatables.splice(idx, 1);
  41033. if (this.onAnimationEnd) {
  41034. this.onAnimationEnd();
  41035. }
  41036. }
  41037. }
  41038. }
  41039. else {
  41040. var index = this._scene._activeAnimatables.indexOf(this);
  41041. if (index > -1) {
  41042. this._scene._activeAnimatables.splice(index, 1);
  41043. var runtimeAnimations = this._runtimeAnimations;
  41044. for (var index = 0; index < runtimeAnimations.length; index++) {
  41045. runtimeAnimations[index].dispose();
  41046. }
  41047. if (this.onAnimationEnd) {
  41048. this.onAnimationEnd();
  41049. }
  41050. }
  41051. }
  41052. };
  41053. Animatable.prototype._animate = function (delay) {
  41054. if (this._paused) {
  41055. this.animationStarted = false;
  41056. if (this._pausedDelay === null) {
  41057. this._pausedDelay = delay;
  41058. }
  41059. return true;
  41060. }
  41061. if (this._localDelayOffset === null) {
  41062. this._localDelayOffset = delay;
  41063. }
  41064. else if (this._pausedDelay !== null) {
  41065. this._localDelayOffset += delay - this._pausedDelay;
  41066. this._pausedDelay = null;
  41067. }
  41068. // Animating
  41069. var running = false;
  41070. var runtimeAnimations = this._runtimeAnimations;
  41071. var index;
  41072. for (index = 0; index < runtimeAnimations.length; index++) {
  41073. var animation = runtimeAnimations[index];
  41074. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  41075. running = running || isRunning;
  41076. }
  41077. this.animationStarted = running;
  41078. if (!running) {
  41079. // Remove from active animatables
  41080. index = this._scene._activeAnimatables.indexOf(this);
  41081. this._scene._activeAnimatables.splice(index, 1);
  41082. // Dispose all runtime animations
  41083. for (index = 0; index < runtimeAnimations.length; index++) {
  41084. runtimeAnimations[index].dispose();
  41085. }
  41086. }
  41087. if (!running && this.onAnimationEnd) {
  41088. this.onAnimationEnd();
  41089. this.onAnimationEnd = null;
  41090. }
  41091. return running;
  41092. };
  41093. return Animatable;
  41094. }());
  41095. BABYLON.Animatable = Animatable;
  41096. })(BABYLON || (BABYLON = {}));
  41097. //# sourceMappingURL=babylon.animatable.js.map
  41098. var BABYLON;
  41099. (function (BABYLON) {
  41100. var EasingFunction = /** @class */ (function () {
  41101. function EasingFunction() {
  41102. // Properties
  41103. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41104. }
  41105. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41106. get: function () {
  41107. return EasingFunction._EASINGMODE_EASEIN;
  41108. },
  41109. enumerable: true,
  41110. configurable: true
  41111. });
  41112. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41113. get: function () {
  41114. return EasingFunction._EASINGMODE_EASEOUT;
  41115. },
  41116. enumerable: true,
  41117. configurable: true
  41118. });
  41119. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41120. get: function () {
  41121. return EasingFunction._EASINGMODE_EASEINOUT;
  41122. },
  41123. enumerable: true,
  41124. configurable: true
  41125. });
  41126. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41127. var n = Math.min(Math.max(easingMode, 0), 2);
  41128. this._easingMode = n;
  41129. };
  41130. EasingFunction.prototype.getEasingMode = function () {
  41131. return this._easingMode;
  41132. };
  41133. EasingFunction.prototype.easeInCore = function (gradient) {
  41134. throw new Error('You must implement this method');
  41135. };
  41136. EasingFunction.prototype.ease = function (gradient) {
  41137. switch (this._easingMode) {
  41138. case EasingFunction.EASINGMODE_EASEIN:
  41139. return this.easeInCore(gradient);
  41140. case EasingFunction.EASINGMODE_EASEOUT:
  41141. return (1 - this.easeInCore(1 - gradient));
  41142. }
  41143. if (gradient >= 0.5) {
  41144. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41145. }
  41146. return (this.easeInCore(gradient * 2) * 0.5);
  41147. };
  41148. //Statics
  41149. EasingFunction._EASINGMODE_EASEIN = 0;
  41150. EasingFunction._EASINGMODE_EASEOUT = 1;
  41151. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41152. return EasingFunction;
  41153. }());
  41154. BABYLON.EasingFunction = EasingFunction;
  41155. var CircleEase = /** @class */ (function (_super) {
  41156. __extends(CircleEase, _super);
  41157. function CircleEase() {
  41158. return _super !== null && _super.apply(this, arguments) || this;
  41159. }
  41160. CircleEase.prototype.easeInCore = function (gradient) {
  41161. gradient = Math.max(0, Math.min(1, gradient));
  41162. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41163. };
  41164. return CircleEase;
  41165. }(EasingFunction));
  41166. BABYLON.CircleEase = CircleEase;
  41167. var BackEase = /** @class */ (function (_super) {
  41168. __extends(BackEase, _super);
  41169. function BackEase(amplitude) {
  41170. if (amplitude === void 0) { amplitude = 1; }
  41171. var _this = _super.call(this) || this;
  41172. _this.amplitude = amplitude;
  41173. return _this;
  41174. }
  41175. BackEase.prototype.easeInCore = function (gradient) {
  41176. var num = Math.max(0, this.amplitude);
  41177. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41178. };
  41179. return BackEase;
  41180. }(EasingFunction));
  41181. BABYLON.BackEase = BackEase;
  41182. var BounceEase = /** @class */ (function (_super) {
  41183. __extends(BounceEase, _super);
  41184. function BounceEase(bounces, bounciness) {
  41185. if (bounces === void 0) { bounces = 3; }
  41186. if (bounciness === void 0) { bounciness = 2; }
  41187. var _this = _super.call(this) || this;
  41188. _this.bounces = bounces;
  41189. _this.bounciness = bounciness;
  41190. return _this;
  41191. }
  41192. BounceEase.prototype.easeInCore = function (gradient) {
  41193. var y = Math.max(0.0, this.bounces);
  41194. var bounciness = this.bounciness;
  41195. if (bounciness <= 1.0) {
  41196. bounciness = 1.001;
  41197. }
  41198. var num9 = Math.pow(bounciness, y);
  41199. var num5 = 1.0 - bounciness;
  41200. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41201. var num15 = gradient * num4;
  41202. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41203. var num3 = Math.floor(num65);
  41204. var num13 = num3 + 1.0;
  41205. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41206. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41207. var num7 = (num8 + num12) * 0.5;
  41208. var num6 = gradient - num7;
  41209. var num2 = num7 - num8;
  41210. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41211. };
  41212. return BounceEase;
  41213. }(EasingFunction));
  41214. BABYLON.BounceEase = BounceEase;
  41215. var CubicEase = /** @class */ (function (_super) {
  41216. __extends(CubicEase, _super);
  41217. function CubicEase() {
  41218. return _super !== null && _super.apply(this, arguments) || this;
  41219. }
  41220. CubicEase.prototype.easeInCore = function (gradient) {
  41221. return (gradient * gradient * gradient);
  41222. };
  41223. return CubicEase;
  41224. }(EasingFunction));
  41225. BABYLON.CubicEase = CubicEase;
  41226. var ElasticEase = /** @class */ (function (_super) {
  41227. __extends(ElasticEase, _super);
  41228. function ElasticEase(oscillations, springiness) {
  41229. if (oscillations === void 0) { oscillations = 3; }
  41230. if (springiness === void 0) { springiness = 3; }
  41231. var _this = _super.call(this) || this;
  41232. _this.oscillations = oscillations;
  41233. _this.springiness = springiness;
  41234. return _this;
  41235. }
  41236. ElasticEase.prototype.easeInCore = function (gradient) {
  41237. var num2;
  41238. var num3 = Math.max(0.0, this.oscillations);
  41239. var num = Math.max(0.0, this.springiness);
  41240. if (num == 0) {
  41241. num2 = gradient;
  41242. }
  41243. else {
  41244. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41245. }
  41246. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41247. };
  41248. return ElasticEase;
  41249. }(EasingFunction));
  41250. BABYLON.ElasticEase = ElasticEase;
  41251. var ExponentialEase = /** @class */ (function (_super) {
  41252. __extends(ExponentialEase, _super);
  41253. function ExponentialEase(exponent) {
  41254. if (exponent === void 0) { exponent = 2; }
  41255. var _this = _super.call(this) || this;
  41256. _this.exponent = exponent;
  41257. return _this;
  41258. }
  41259. ExponentialEase.prototype.easeInCore = function (gradient) {
  41260. if (this.exponent <= 0) {
  41261. return gradient;
  41262. }
  41263. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41264. };
  41265. return ExponentialEase;
  41266. }(EasingFunction));
  41267. BABYLON.ExponentialEase = ExponentialEase;
  41268. var PowerEase = /** @class */ (function (_super) {
  41269. __extends(PowerEase, _super);
  41270. function PowerEase(power) {
  41271. if (power === void 0) { power = 2; }
  41272. var _this = _super.call(this) || this;
  41273. _this.power = power;
  41274. return _this;
  41275. }
  41276. PowerEase.prototype.easeInCore = function (gradient) {
  41277. var y = Math.max(0.0, this.power);
  41278. return Math.pow(gradient, y);
  41279. };
  41280. return PowerEase;
  41281. }(EasingFunction));
  41282. BABYLON.PowerEase = PowerEase;
  41283. var QuadraticEase = /** @class */ (function (_super) {
  41284. __extends(QuadraticEase, _super);
  41285. function QuadraticEase() {
  41286. return _super !== null && _super.apply(this, arguments) || this;
  41287. }
  41288. QuadraticEase.prototype.easeInCore = function (gradient) {
  41289. return (gradient * gradient);
  41290. };
  41291. return QuadraticEase;
  41292. }(EasingFunction));
  41293. BABYLON.QuadraticEase = QuadraticEase;
  41294. var QuarticEase = /** @class */ (function (_super) {
  41295. __extends(QuarticEase, _super);
  41296. function QuarticEase() {
  41297. return _super !== null && _super.apply(this, arguments) || this;
  41298. }
  41299. QuarticEase.prototype.easeInCore = function (gradient) {
  41300. return (gradient * gradient * gradient * gradient);
  41301. };
  41302. return QuarticEase;
  41303. }(EasingFunction));
  41304. BABYLON.QuarticEase = QuarticEase;
  41305. var QuinticEase = /** @class */ (function (_super) {
  41306. __extends(QuinticEase, _super);
  41307. function QuinticEase() {
  41308. return _super !== null && _super.apply(this, arguments) || this;
  41309. }
  41310. QuinticEase.prototype.easeInCore = function (gradient) {
  41311. return (gradient * gradient * gradient * gradient * gradient);
  41312. };
  41313. return QuinticEase;
  41314. }(EasingFunction));
  41315. BABYLON.QuinticEase = QuinticEase;
  41316. var SineEase = /** @class */ (function (_super) {
  41317. __extends(SineEase, _super);
  41318. function SineEase() {
  41319. return _super !== null && _super.apply(this, arguments) || this;
  41320. }
  41321. SineEase.prototype.easeInCore = function (gradient) {
  41322. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41323. };
  41324. return SineEase;
  41325. }(EasingFunction));
  41326. BABYLON.SineEase = SineEase;
  41327. var BezierCurveEase = /** @class */ (function (_super) {
  41328. __extends(BezierCurveEase, _super);
  41329. function BezierCurveEase(x1, y1, x2, y2) {
  41330. if (x1 === void 0) { x1 = 0; }
  41331. if (y1 === void 0) { y1 = 0; }
  41332. if (x2 === void 0) { x2 = 1; }
  41333. if (y2 === void 0) { y2 = 1; }
  41334. var _this = _super.call(this) || this;
  41335. _this.x1 = x1;
  41336. _this.y1 = y1;
  41337. _this.x2 = x2;
  41338. _this.y2 = y2;
  41339. return _this;
  41340. }
  41341. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41342. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41343. };
  41344. return BezierCurveEase;
  41345. }(EasingFunction));
  41346. BABYLON.BezierCurveEase = BezierCurveEase;
  41347. })(BABYLON || (BABYLON = {}));
  41348. //# sourceMappingURL=babylon.easing.js.map
  41349. var BABYLON;
  41350. (function (BABYLON) {
  41351. var Condition = /** @class */ (function () {
  41352. function Condition(actionManager) {
  41353. this._actionManager = actionManager;
  41354. }
  41355. Condition.prototype.isValid = function () {
  41356. return true;
  41357. };
  41358. Condition.prototype._getProperty = function (propertyPath) {
  41359. return this._actionManager._getProperty(propertyPath);
  41360. };
  41361. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41362. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41363. };
  41364. Condition.prototype.serialize = function () {
  41365. };
  41366. Condition.prototype._serialize = function (serializedCondition) {
  41367. return {
  41368. type: 2,
  41369. children: [],
  41370. name: serializedCondition.name,
  41371. properties: serializedCondition.properties
  41372. };
  41373. };
  41374. return Condition;
  41375. }());
  41376. BABYLON.Condition = Condition;
  41377. var ValueCondition = /** @class */ (function (_super) {
  41378. __extends(ValueCondition, _super);
  41379. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41380. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41381. var _this = _super.call(this, actionManager) || this;
  41382. _this.propertyPath = propertyPath;
  41383. _this.value = value;
  41384. _this.operator = operator;
  41385. _this._target = target;
  41386. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41387. _this._property = _this._getProperty(_this.propertyPath);
  41388. return _this;
  41389. }
  41390. Object.defineProperty(ValueCondition, "IsEqual", {
  41391. get: function () {
  41392. return ValueCondition._IsEqual;
  41393. },
  41394. enumerable: true,
  41395. configurable: true
  41396. });
  41397. Object.defineProperty(ValueCondition, "IsDifferent", {
  41398. get: function () {
  41399. return ValueCondition._IsDifferent;
  41400. },
  41401. enumerable: true,
  41402. configurable: true
  41403. });
  41404. Object.defineProperty(ValueCondition, "IsGreater", {
  41405. get: function () {
  41406. return ValueCondition._IsGreater;
  41407. },
  41408. enumerable: true,
  41409. configurable: true
  41410. });
  41411. Object.defineProperty(ValueCondition, "IsLesser", {
  41412. get: function () {
  41413. return ValueCondition._IsLesser;
  41414. },
  41415. enumerable: true,
  41416. configurable: true
  41417. });
  41418. // Methods
  41419. ValueCondition.prototype.isValid = function () {
  41420. switch (this.operator) {
  41421. case ValueCondition.IsGreater:
  41422. return this._effectiveTarget[this._property] > this.value;
  41423. case ValueCondition.IsLesser:
  41424. return this._effectiveTarget[this._property] < this.value;
  41425. case ValueCondition.IsEqual:
  41426. case ValueCondition.IsDifferent:
  41427. var check;
  41428. if (this.value.equals) {
  41429. check = this.value.equals(this._effectiveTarget[this._property]);
  41430. }
  41431. else {
  41432. check = this.value === this._effectiveTarget[this._property];
  41433. }
  41434. return this.operator === ValueCondition.IsEqual ? check : !check;
  41435. }
  41436. return false;
  41437. };
  41438. ValueCondition.prototype.serialize = function () {
  41439. return this._serialize({
  41440. name: "ValueCondition",
  41441. properties: [
  41442. BABYLON.Action._GetTargetProperty(this._target),
  41443. { name: "propertyPath", value: this.propertyPath },
  41444. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41445. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41446. ]
  41447. });
  41448. };
  41449. ValueCondition.GetOperatorName = function (operator) {
  41450. switch (operator) {
  41451. case ValueCondition._IsEqual: return "IsEqual";
  41452. case ValueCondition._IsDifferent: return "IsDifferent";
  41453. case ValueCondition._IsGreater: return "IsGreater";
  41454. case ValueCondition._IsLesser: return "IsLesser";
  41455. default: return "";
  41456. }
  41457. };
  41458. // Statics
  41459. ValueCondition._IsEqual = 0;
  41460. ValueCondition._IsDifferent = 1;
  41461. ValueCondition._IsGreater = 2;
  41462. ValueCondition._IsLesser = 3;
  41463. return ValueCondition;
  41464. }(Condition));
  41465. BABYLON.ValueCondition = ValueCondition;
  41466. var PredicateCondition = /** @class */ (function (_super) {
  41467. __extends(PredicateCondition, _super);
  41468. function PredicateCondition(actionManager, predicate) {
  41469. var _this = _super.call(this, actionManager) || this;
  41470. _this.predicate = predicate;
  41471. return _this;
  41472. }
  41473. PredicateCondition.prototype.isValid = function () {
  41474. return this.predicate();
  41475. };
  41476. return PredicateCondition;
  41477. }(Condition));
  41478. BABYLON.PredicateCondition = PredicateCondition;
  41479. var StateCondition = /** @class */ (function (_super) {
  41480. __extends(StateCondition, _super);
  41481. function StateCondition(actionManager, target, value) {
  41482. var _this = _super.call(this, actionManager) || this;
  41483. _this.value = value;
  41484. _this._target = target;
  41485. return _this;
  41486. }
  41487. // Methods
  41488. StateCondition.prototype.isValid = function () {
  41489. return this._target.state === this.value;
  41490. };
  41491. StateCondition.prototype.serialize = function () {
  41492. return this._serialize({
  41493. name: "StateCondition",
  41494. properties: [
  41495. BABYLON.Action._GetTargetProperty(this._target),
  41496. { name: "value", value: this.value }
  41497. ]
  41498. });
  41499. };
  41500. return StateCondition;
  41501. }(Condition));
  41502. BABYLON.StateCondition = StateCondition;
  41503. })(BABYLON || (BABYLON = {}));
  41504. //# sourceMappingURL=babylon.condition.js.map
  41505. var BABYLON;
  41506. (function (BABYLON) {
  41507. var Action = /** @class */ (function () {
  41508. function Action(triggerOptions, condition) {
  41509. this.triggerOptions = triggerOptions;
  41510. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41511. if (triggerOptions.parameter) {
  41512. this.trigger = triggerOptions.trigger;
  41513. this._triggerParameter = triggerOptions.parameter;
  41514. }
  41515. else {
  41516. this.trigger = triggerOptions;
  41517. }
  41518. this._nextActiveAction = this;
  41519. this._condition = condition;
  41520. }
  41521. // Methods
  41522. Action.prototype._prepare = function () {
  41523. };
  41524. Action.prototype.getTriggerParameter = function () {
  41525. return this._triggerParameter;
  41526. };
  41527. Action.prototype._executeCurrent = function (evt) {
  41528. if (this._nextActiveAction._condition) {
  41529. var condition = this._nextActiveAction._condition;
  41530. var currentRenderId = this._actionManager.getScene().getRenderId();
  41531. // We cache the current evaluation for the current frame
  41532. if (condition._evaluationId === currentRenderId) {
  41533. if (!condition._currentResult) {
  41534. return;
  41535. }
  41536. }
  41537. else {
  41538. condition._evaluationId = currentRenderId;
  41539. if (!condition.isValid()) {
  41540. condition._currentResult = false;
  41541. return;
  41542. }
  41543. condition._currentResult = true;
  41544. }
  41545. }
  41546. this.onBeforeExecuteObservable.notifyObservers(this);
  41547. this._nextActiveAction.execute(evt);
  41548. this.skipToNextActiveAction();
  41549. };
  41550. Action.prototype.execute = function (evt) {
  41551. };
  41552. Action.prototype.skipToNextActiveAction = function () {
  41553. if (this._nextActiveAction._child) {
  41554. if (!this._nextActiveAction._child._actionManager) {
  41555. this._nextActiveAction._child._actionManager = this._actionManager;
  41556. }
  41557. this._nextActiveAction = this._nextActiveAction._child;
  41558. }
  41559. else {
  41560. this._nextActiveAction = this;
  41561. }
  41562. };
  41563. Action.prototype.then = function (action) {
  41564. this._child = action;
  41565. action._actionManager = this._actionManager;
  41566. action._prepare();
  41567. return action;
  41568. };
  41569. Action.prototype._getProperty = function (propertyPath) {
  41570. return this._actionManager._getProperty(propertyPath);
  41571. };
  41572. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41573. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41574. };
  41575. Action.prototype.serialize = function (parent) {
  41576. };
  41577. // Called by BABYLON.Action objects in serialize(...). Internal use
  41578. Action.prototype._serialize = function (serializedAction, parent) {
  41579. var serializationObject = {
  41580. type: 1,
  41581. children: [],
  41582. name: serializedAction.name,
  41583. properties: serializedAction.properties || []
  41584. };
  41585. // Serialize child
  41586. if (this._child) {
  41587. this._child.serialize(serializationObject);
  41588. }
  41589. // Check if "this" has a condition
  41590. if (this._condition) {
  41591. var serializedCondition = this._condition.serialize();
  41592. serializedCondition.children.push(serializationObject);
  41593. if (parent) {
  41594. parent.children.push(serializedCondition);
  41595. }
  41596. return serializedCondition;
  41597. }
  41598. if (parent) {
  41599. parent.children.push(serializationObject);
  41600. }
  41601. return serializationObject;
  41602. };
  41603. Action._SerializeValueAsString = function (value) {
  41604. if (typeof value === "number") {
  41605. return value.toString();
  41606. }
  41607. if (typeof value === "boolean") {
  41608. return value ? "true" : "false";
  41609. }
  41610. if (value instanceof BABYLON.Vector2) {
  41611. return value.x + ", " + value.y;
  41612. }
  41613. if (value instanceof BABYLON.Vector3) {
  41614. return value.x + ", " + value.y + ", " + value.z;
  41615. }
  41616. if (value instanceof BABYLON.Color3) {
  41617. return value.r + ", " + value.g + ", " + value.b;
  41618. }
  41619. if (value instanceof BABYLON.Color4) {
  41620. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41621. }
  41622. return value; // string
  41623. };
  41624. Action._GetTargetProperty = function (target) {
  41625. return {
  41626. name: "target",
  41627. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41628. : target instanceof BABYLON.Light ? "LightProperties"
  41629. : target instanceof BABYLON.Camera ? "CameraProperties"
  41630. : "SceneProperties",
  41631. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41632. };
  41633. };
  41634. return Action;
  41635. }());
  41636. BABYLON.Action = Action;
  41637. })(BABYLON || (BABYLON = {}));
  41638. //# sourceMappingURL=babylon.action.js.map
  41639. var BABYLON;
  41640. (function (BABYLON) {
  41641. /**
  41642. * ActionEvent is the event beint sent when an action is triggered.
  41643. */
  41644. var ActionEvent = /** @class */ (function () {
  41645. /**
  41646. * @param source The mesh or sprite that triggered the action.
  41647. * @param pointerX The X mouse cursor position at the time of the event
  41648. * @param pointerY The Y mouse cursor position at the time of the event
  41649. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41650. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41651. */
  41652. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41653. this.source = source;
  41654. this.pointerX = pointerX;
  41655. this.pointerY = pointerY;
  41656. this.meshUnderPointer = meshUnderPointer;
  41657. this.sourceEvent = sourceEvent;
  41658. this.additionalData = additionalData;
  41659. }
  41660. /**
  41661. * Helper function to auto-create an ActionEvent from a source mesh.
  41662. * @param source The source mesh that triggered the event
  41663. * @param evt {Event} The original (browser) event
  41664. */
  41665. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41666. var scene = source.getScene();
  41667. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41668. };
  41669. /**
  41670. * Helper function to auto-create an ActionEvent from a source mesh.
  41671. * @param source The source sprite that triggered the event
  41672. * @param scene Scene associated with the sprite
  41673. * @param evt {Event} The original (browser) event
  41674. */
  41675. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41676. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41677. };
  41678. /**
  41679. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41680. * @param scene the scene where the event occurred
  41681. * @param evt {Event} The original (browser) event
  41682. */
  41683. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41684. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41685. };
  41686. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41687. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41688. };
  41689. return ActionEvent;
  41690. }());
  41691. BABYLON.ActionEvent = ActionEvent;
  41692. /**
  41693. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41694. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41695. */
  41696. var ActionManager = /** @class */ (function () {
  41697. function ActionManager(scene) {
  41698. // Members
  41699. this.actions = new Array();
  41700. this.hoverCursor = '';
  41701. this._scene = scene;
  41702. scene._actionManagers.push(this);
  41703. }
  41704. Object.defineProperty(ActionManager, "NothingTrigger", {
  41705. get: function () {
  41706. return ActionManager._NothingTrigger;
  41707. },
  41708. enumerable: true,
  41709. configurable: true
  41710. });
  41711. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41712. get: function () {
  41713. return ActionManager._OnPickTrigger;
  41714. },
  41715. enumerable: true,
  41716. configurable: true
  41717. });
  41718. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41719. get: function () {
  41720. return ActionManager._OnLeftPickTrigger;
  41721. },
  41722. enumerable: true,
  41723. configurable: true
  41724. });
  41725. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41726. get: function () {
  41727. return ActionManager._OnRightPickTrigger;
  41728. },
  41729. enumerable: true,
  41730. configurable: true
  41731. });
  41732. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41733. get: function () {
  41734. return ActionManager._OnCenterPickTrigger;
  41735. },
  41736. enumerable: true,
  41737. configurable: true
  41738. });
  41739. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41740. get: function () {
  41741. return ActionManager._OnPickDownTrigger;
  41742. },
  41743. enumerable: true,
  41744. configurable: true
  41745. });
  41746. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41747. get: function () {
  41748. return ActionManager._OnDoublePickTrigger;
  41749. },
  41750. enumerable: true,
  41751. configurable: true
  41752. });
  41753. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41754. get: function () {
  41755. return ActionManager._OnPickUpTrigger;
  41756. },
  41757. enumerable: true,
  41758. configurable: true
  41759. });
  41760. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41761. /// This trigger will only be raised if you also declared a OnPickDown
  41762. get: function () {
  41763. return ActionManager._OnPickOutTrigger;
  41764. },
  41765. enumerable: true,
  41766. configurable: true
  41767. });
  41768. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41769. get: function () {
  41770. return ActionManager._OnLongPressTrigger;
  41771. },
  41772. enumerable: true,
  41773. configurable: true
  41774. });
  41775. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41776. get: function () {
  41777. return ActionManager._OnPointerOverTrigger;
  41778. },
  41779. enumerable: true,
  41780. configurable: true
  41781. });
  41782. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41783. get: function () {
  41784. return ActionManager._OnPointerOutTrigger;
  41785. },
  41786. enumerable: true,
  41787. configurable: true
  41788. });
  41789. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41790. get: function () {
  41791. return ActionManager._OnEveryFrameTrigger;
  41792. },
  41793. enumerable: true,
  41794. configurable: true
  41795. });
  41796. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41797. get: function () {
  41798. return ActionManager._OnIntersectionEnterTrigger;
  41799. },
  41800. enumerable: true,
  41801. configurable: true
  41802. });
  41803. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41804. get: function () {
  41805. return ActionManager._OnIntersectionExitTrigger;
  41806. },
  41807. enumerable: true,
  41808. configurable: true
  41809. });
  41810. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41811. get: function () {
  41812. return ActionManager._OnKeyDownTrigger;
  41813. },
  41814. enumerable: true,
  41815. configurable: true
  41816. });
  41817. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41818. get: function () {
  41819. return ActionManager._OnKeyUpTrigger;
  41820. },
  41821. enumerable: true,
  41822. configurable: true
  41823. });
  41824. // Methods
  41825. ActionManager.prototype.dispose = function () {
  41826. var index = this._scene._actionManagers.indexOf(this);
  41827. for (var i = 0; i < this.actions.length; i++) {
  41828. var action = this.actions[i];
  41829. ActionManager.Triggers[action.trigger]--;
  41830. if (ActionManager.Triggers[action.trigger] === 0) {
  41831. delete ActionManager.Triggers[action.trigger];
  41832. }
  41833. }
  41834. if (index > -1) {
  41835. this._scene._actionManagers.splice(index, 1);
  41836. }
  41837. };
  41838. ActionManager.prototype.getScene = function () {
  41839. return this._scene;
  41840. };
  41841. /**
  41842. * Does this action manager handles actions of any of the given triggers
  41843. * @param {number[]} triggers - the triggers to be tested
  41844. * @return {boolean} whether one (or more) of the triggers is handeled
  41845. */
  41846. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41847. for (var index = 0; index < this.actions.length; index++) {
  41848. var action = this.actions[index];
  41849. if (triggers.indexOf(action.trigger) > -1) {
  41850. return true;
  41851. }
  41852. }
  41853. return false;
  41854. };
  41855. /**
  41856. * Does this action manager handles actions of a given trigger
  41857. * @param {number} trigger - the trigger to be tested
  41858. * @return {boolean} whether the trigger is handeled
  41859. */
  41860. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41861. for (var index = 0; index < this.actions.length; index++) {
  41862. var action = this.actions[index];
  41863. if (action.trigger === trigger) {
  41864. return true;
  41865. }
  41866. }
  41867. return false;
  41868. };
  41869. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41870. /**
  41871. * Does this action manager has pointer triggers
  41872. * @return {boolean} whether or not it has pointer triggers
  41873. */
  41874. get: function () {
  41875. for (var index = 0; index < this.actions.length; index++) {
  41876. var action = this.actions[index];
  41877. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41878. return true;
  41879. }
  41880. }
  41881. return false;
  41882. },
  41883. enumerable: true,
  41884. configurable: true
  41885. });
  41886. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41887. /**
  41888. * Does this action manager has pick triggers
  41889. * @return {boolean} whether or not it has pick triggers
  41890. */
  41891. get: function () {
  41892. for (var index = 0; index < this.actions.length; index++) {
  41893. var action = this.actions[index];
  41894. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41895. return true;
  41896. }
  41897. }
  41898. return false;
  41899. },
  41900. enumerable: true,
  41901. configurable: true
  41902. });
  41903. Object.defineProperty(ActionManager, "HasTriggers", {
  41904. /**
  41905. * Does exist one action manager with at least one trigger
  41906. * @return {boolean} whether or not it exists one action manager with one trigger
  41907. **/
  41908. get: function () {
  41909. for (var t in ActionManager.Triggers) {
  41910. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41911. return true;
  41912. }
  41913. }
  41914. return false;
  41915. },
  41916. enumerable: true,
  41917. configurable: true
  41918. });
  41919. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41920. /**
  41921. * Does exist one action manager with at least one pick trigger
  41922. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41923. **/
  41924. get: function () {
  41925. for (var t in ActionManager.Triggers) {
  41926. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41927. var t_int = parseInt(t);
  41928. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41929. return true;
  41930. }
  41931. }
  41932. }
  41933. return false;
  41934. },
  41935. enumerable: true,
  41936. configurable: true
  41937. });
  41938. /**
  41939. * Does exist one action manager that handles actions of a given trigger
  41940. * @param {number} trigger - the trigger to be tested
  41941. * @return {boolean} whether the trigger is handeled by at least one action manager
  41942. **/
  41943. ActionManager.HasSpecificTrigger = function (trigger) {
  41944. for (var t in ActionManager.Triggers) {
  41945. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41946. var t_int = parseInt(t);
  41947. if (t_int === trigger) {
  41948. return true;
  41949. }
  41950. }
  41951. }
  41952. return false;
  41953. };
  41954. /**
  41955. * Registers an action to this action manager
  41956. * @param {BABYLON.Action} action - the action to be registered
  41957. * @return {BABYLON.Action} the action amended (prepared) after registration
  41958. */
  41959. ActionManager.prototype.registerAction = function (action) {
  41960. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41961. if (this.getScene().actionManager !== this) {
  41962. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41963. return null;
  41964. }
  41965. }
  41966. this.actions.push(action);
  41967. if (ActionManager.Triggers[action.trigger]) {
  41968. ActionManager.Triggers[action.trigger]++;
  41969. }
  41970. else {
  41971. ActionManager.Triggers[action.trigger] = 1;
  41972. }
  41973. action._actionManager = this;
  41974. action._prepare();
  41975. return action;
  41976. };
  41977. /**
  41978. * Process a specific trigger
  41979. * @param {number} trigger - the trigger to process
  41980. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41981. */
  41982. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41983. for (var index = 0; index < this.actions.length; index++) {
  41984. var action = this.actions[index];
  41985. if (action.trigger === trigger) {
  41986. if (evt) {
  41987. if (trigger === ActionManager.OnKeyUpTrigger
  41988. || trigger === ActionManager.OnKeyDownTrigger) {
  41989. var parameter = action.getTriggerParameter();
  41990. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41991. if (!parameter.toLowerCase) {
  41992. continue;
  41993. }
  41994. var lowerCase = parameter.toLowerCase();
  41995. if (lowerCase !== evt.sourceEvent.key) {
  41996. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41997. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41998. if (actualkey !== lowerCase) {
  41999. continue;
  42000. }
  42001. }
  42002. }
  42003. }
  42004. }
  42005. action._executeCurrent(evt);
  42006. }
  42007. }
  42008. };
  42009. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  42010. var properties = propertyPath.split(".");
  42011. for (var index = 0; index < properties.length - 1; index++) {
  42012. target = target[properties[index]];
  42013. }
  42014. return target;
  42015. };
  42016. ActionManager.prototype._getProperty = function (propertyPath) {
  42017. var properties = propertyPath.split(".");
  42018. return properties[properties.length - 1];
  42019. };
  42020. ActionManager.prototype.serialize = function (name) {
  42021. var root = {
  42022. children: new Array(),
  42023. name: name,
  42024. type: 3,
  42025. properties: new Array() // Empty for root but required
  42026. };
  42027. for (var i = 0; i < this.actions.length; i++) {
  42028. var triggerObject = {
  42029. type: 0,
  42030. children: new Array(),
  42031. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  42032. properties: new Array()
  42033. };
  42034. var triggerOptions = this.actions[i].triggerOptions;
  42035. if (triggerOptions && typeof triggerOptions !== "number") {
  42036. if (triggerOptions.parameter instanceof BABYLON.Node) {
  42037. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  42038. }
  42039. else {
  42040. var parameter = {};
  42041. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  42042. if (triggerOptions.parameter.mesh) {
  42043. parameter._meshId = triggerOptions.parameter.mesh.id;
  42044. }
  42045. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  42046. }
  42047. }
  42048. // Serialize child action, recursively
  42049. this.actions[i].serialize(triggerObject);
  42050. // Add serialized trigger
  42051. root.children.push(triggerObject);
  42052. }
  42053. return root;
  42054. };
  42055. ActionManager.Parse = function (parsedActions, object, scene) {
  42056. var actionManager = new BABYLON.ActionManager(scene);
  42057. if (object === null)
  42058. scene.actionManager = actionManager;
  42059. else
  42060. object.actionManager = actionManager;
  42061. // instanciate a new object
  42062. var instanciate = function (name, params) {
  42063. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  42064. newInstance.constructor.apply(newInstance, params);
  42065. return newInstance;
  42066. };
  42067. var parseParameter = function (name, value, target, propertyPath) {
  42068. if (propertyPath === null) {
  42069. // String, boolean or float
  42070. var floatValue = parseFloat(value);
  42071. if (value === "true" || value === "false")
  42072. return value === "true";
  42073. else
  42074. return isNaN(floatValue) ? value : floatValue;
  42075. }
  42076. var effectiveTarget = propertyPath.split(".");
  42077. var values = value.split(",");
  42078. // Get effective Target
  42079. for (var i = 0; i < effectiveTarget.length; i++) {
  42080. target = target[effectiveTarget[i]];
  42081. }
  42082. // Return appropriate value with its type
  42083. if (typeof (target) === "boolean")
  42084. return values[0] === "true";
  42085. if (typeof (target) === "string")
  42086. return values[0];
  42087. // Parameters with multiple values such as Vector3 etc.
  42088. var split = new Array();
  42089. for (var i = 0; i < values.length; i++)
  42090. split.push(parseFloat(values[i]));
  42091. if (target instanceof BABYLON.Vector3)
  42092. return BABYLON.Vector3.FromArray(split);
  42093. if (target instanceof BABYLON.Vector4)
  42094. return BABYLON.Vector4.FromArray(split);
  42095. if (target instanceof BABYLON.Color3)
  42096. return BABYLON.Color3.FromArray(split);
  42097. if (target instanceof BABYLON.Color4)
  42098. return BABYLON.Color4.FromArray(split);
  42099. return parseFloat(values[0]);
  42100. };
  42101. // traverse graph per trigger
  42102. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42103. if (combineArray === void 0) { combineArray = null; }
  42104. if (parsedAction.detached)
  42105. return;
  42106. var parameters = new Array();
  42107. var target = null;
  42108. var propertyPath = null;
  42109. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42110. // Parameters
  42111. if (parsedAction.type === 2)
  42112. parameters.push(actionManager);
  42113. else
  42114. parameters.push(trigger);
  42115. if (combine) {
  42116. var actions = new Array();
  42117. for (var j = 0; j < parsedAction.combine.length; j++) {
  42118. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42119. }
  42120. parameters.push(actions);
  42121. }
  42122. else {
  42123. for (var i = 0; i < parsedAction.properties.length; i++) {
  42124. var value = parsedAction.properties[i].value;
  42125. var name = parsedAction.properties[i].name;
  42126. var targetType = parsedAction.properties[i].targetType;
  42127. if (name === "target")
  42128. if (targetType !== null && targetType === "SceneProperties")
  42129. value = target = scene;
  42130. else
  42131. value = target = scene.getNodeByName(value);
  42132. else if (name === "parent")
  42133. value = scene.getNodeByName(value);
  42134. else if (name === "sound")
  42135. value = scene.getSoundByName(value);
  42136. else if (name !== "propertyPath") {
  42137. if (parsedAction.type === 2 && name === "operator")
  42138. value = BABYLON.ValueCondition[value];
  42139. else
  42140. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42141. }
  42142. else {
  42143. propertyPath = value;
  42144. }
  42145. parameters.push(value);
  42146. }
  42147. }
  42148. if (combineArray === null) {
  42149. parameters.push(condition);
  42150. }
  42151. else {
  42152. parameters.push(null);
  42153. }
  42154. // If interpolate value action
  42155. if (parsedAction.name === "InterpolateValueAction") {
  42156. var param = parameters[parameters.length - 2];
  42157. parameters[parameters.length - 1] = param;
  42158. parameters[parameters.length - 2] = condition;
  42159. }
  42160. // Action or condition(s) and not CombineAction
  42161. var newAction = instanciate(parsedAction.name, parameters);
  42162. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42163. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42164. if (action)
  42165. action.then(nothing);
  42166. else
  42167. actionManager.registerAction(nothing);
  42168. action = nothing;
  42169. }
  42170. if (combineArray === null) {
  42171. if (newAction instanceof BABYLON.Condition) {
  42172. condition = newAction;
  42173. newAction = action;
  42174. }
  42175. else {
  42176. condition = null;
  42177. if (action)
  42178. action.then(newAction);
  42179. else
  42180. actionManager.registerAction(newAction);
  42181. }
  42182. }
  42183. else {
  42184. combineArray.push(newAction);
  42185. }
  42186. for (var i = 0; i < parsedAction.children.length; i++)
  42187. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42188. };
  42189. // triggers
  42190. for (var i = 0; i < parsedActions.children.length; i++) {
  42191. var triggerParams;
  42192. var trigger = parsedActions.children[i];
  42193. if (trigger.properties.length > 0) {
  42194. var param = trigger.properties[0].value;
  42195. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42196. if (value._meshId) {
  42197. value.mesh = scene.getMeshByID(value._meshId);
  42198. }
  42199. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42200. }
  42201. else
  42202. triggerParams = ActionManager[trigger.name];
  42203. for (var j = 0; j < trigger.children.length; j++) {
  42204. if (!trigger.detached)
  42205. traverse(trigger.children[j], triggerParams, null, null);
  42206. }
  42207. }
  42208. };
  42209. ActionManager.GetTriggerName = function (trigger) {
  42210. switch (trigger) {
  42211. case 0: return "NothingTrigger";
  42212. case 1: return "OnPickTrigger";
  42213. case 2: return "OnLeftPickTrigger";
  42214. case 3: return "OnRightPickTrigger";
  42215. case 4: return "OnCenterPickTrigger";
  42216. case 5: return "OnPickDownTrigger";
  42217. case 6: return "OnPickUpTrigger";
  42218. case 7: return "OnLongPressTrigger";
  42219. case 8: return "OnPointerOverTrigger";
  42220. case 9: return "OnPointerOutTrigger";
  42221. case 10: return "OnEveryFrameTrigger";
  42222. case 11: return "OnIntersectionEnterTrigger";
  42223. case 12: return "OnIntersectionExitTrigger";
  42224. case 13: return "OnKeyDownTrigger";
  42225. case 14: return "OnKeyUpTrigger";
  42226. case 15: return "OnPickOutTrigger";
  42227. default: return "";
  42228. }
  42229. };
  42230. // Statics
  42231. ActionManager._NothingTrigger = 0;
  42232. ActionManager._OnPickTrigger = 1;
  42233. ActionManager._OnLeftPickTrigger = 2;
  42234. ActionManager._OnRightPickTrigger = 3;
  42235. ActionManager._OnCenterPickTrigger = 4;
  42236. ActionManager._OnPickDownTrigger = 5;
  42237. ActionManager._OnDoublePickTrigger = 6;
  42238. ActionManager._OnPickUpTrigger = 7;
  42239. ActionManager._OnLongPressTrigger = 8;
  42240. ActionManager._OnPointerOverTrigger = 9;
  42241. ActionManager._OnPointerOutTrigger = 10;
  42242. ActionManager._OnEveryFrameTrigger = 11;
  42243. ActionManager._OnIntersectionEnterTrigger = 12;
  42244. ActionManager._OnIntersectionExitTrigger = 13;
  42245. ActionManager._OnKeyDownTrigger = 14;
  42246. ActionManager._OnKeyUpTrigger = 15;
  42247. ActionManager._OnPickOutTrigger = 16;
  42248. ActionManager.Triggers = {};
  42249. return ActionManager;
  42250. }());
  42251. BABYLON.ActionManager = ActionManager;
  42252. })(BABYLON || (BABYLON = {}));
  42253. //# sourceMappingURL=babylon.actionManager.js.map
  42254. var BABYLON;
  42255. (function (BABYLON) {
  42256. var InterpolateValueAction = /** @class */ (function (_super) {
  42257. __extends(InterpolateValueAction, _super);
  42258. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42259. if (duration === void 0) { duration = 1000; }
  42260. var _this = _super.call(this, triggerOptions, condition) || this;
  42261. _this.propertyPath = propertyPath;
  42262. _this.value = value;
  42263. _this.duration = duration;
  42264. _this.stopOtherAnimations = stopOtherAnimations;
  42265. _this.onInterpolationDone = onInterpolationDone;
  42266. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42267. _this._target = _this._effectiveTarget = target;
  42268. return _this;
  42269. }
  42270. InterpolateValueAction.prototype._prepare = function () {
  42271. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42272. this._property = this._getProperty(this.propertyPath);
  42273. };
  42274. InterpolateValueAction.prototype.execute = function () {
  42275. var _this = this;
  42276. var scene = this._actionManager.getScene();
  42277. var keys = [
  42278. {
  42279. frame: 0,
  42280. value: this._effectiveTarget[this._property]
  42281. }, {
  42282. frame: 100,
  42283. value: this.value
  42284. }
  42285. ];
  42286. var dataType;
  42287. if (typeof this.value === "number") {
  42288. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42289. }
  42290. else if (this.value instanceof BABYLON.Color3) {
  42291. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42292. }
  42293. else if (this.value instanceof BABYLON.Vector3) {
  42294. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42295. }
  42296. else if (this.value instanceof BABYLON.Matrix) {
  42297. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42298. }
  42299. else if (this.value instanceof BABYLON.Quaternion) {
  42300. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42301. }
  42302. else {
  42303. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42304. return;
  42305. }
  42306. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42307. animation.setKeys(keys);
  42308. if (this.stopOtherAnimations) {
  42309. scene.stopAnimation(this._effectiveTarget);
  42310. }
  42311. var wrapper = function () {
  42312. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42313. if (_this.onInterpolationDone) {
  42314. _this.onInterpolationDone();
  42315. }
  42316. };
  42317. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42318. };
  42319. InterpolateValueAction.prototype.serialize = function (parent) {
  42320. return _super.prototype._serialize.call(this, {
  42321. name: "InterpolateValueAction",
  42322. properties: [
  42323. BABYLON.Action._GetTargetProperty(this._target),
  42324. { name: "propertyPath", value: this.propertyPath },
  42325. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42326. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42327. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42328. ]
  42329. }, parent);
  42330. };
  42331. return InterpolateValueAction;
  42332. }(BABYLON.Action));
  42333. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42334. })(BABYLON || (BABYLON = {}));
  42335. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42336. var BABYLON;
  42337. (function (BABYLON) {
  42338. var SwitchBooleanAction = /** @class */ (function (_super) {
  42339. __extends(SwitchBooleanAction, _super);
  42340. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42341. var _this = _super.call(this, triggerOptions, condition) || this;
  42342. _this.propertyPath = propertyPath;
  42343. _this._target = _this._effectiveTarget = target;
  42344. return _this;
  42345. }
  42346. SwitchBooleanAction.prototype._prepare = function () {
  42347. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42348. this._property = this._getProperty(this.propertyPath);
  42349. };
  42350. SwitchBooleanAction.prototype.execute = function () {
  42351. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42352. };
  42353. SwitchBooleanAction.prototype.serialize = function (parent) {
  42354. return _super.prototype._serialize.call(this, {
  42355. name: "SwitchBooleanAction",
  42356. properties: [
  42357. BABYLON.Action._GetTargetProperty(this._target),
  42358. { name: "propertyPath", value: this.propertyPath }
  42359. ]
  42360. }, parent);
  42361. };
  42362. return SwitchBooleanAction;
  42363. }(BABYLON.Action));
  42364. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42365. var SetStateAction = /** @class */ (function (_super) {
  42366. __extends(SetStateAction, _super);
  42367. function SetStateAction(triggerOptions, target, value, condition) {
  42368. var _this = _super.call(this, triggerOptions, condition) || this;
  42369. _this.value = value;
  42370. _this._target = target;
  42371. return _this;
  42372. }
  42373. SetStateAction.prototype.execute = function () {
  42374. this._target.state = this.value;
  42375. };
  42376. SetStateAction.prototype.serialize = function (parent) {
  42377. return _super.prototype._serialize.call(this, {
  42378. name: "SetStateAction",
  42379. properties: [
  42380. BABYLON.Action._GetTargetProperty(this._target),
  42381. { name: "value", value: this.value }
  42382. ]
  42383. }, parent);
  42384. };
  42385. return SetStateAction;
  42386. }(BABYLON.Action));
  42387. BABYLON.SetStateAction = SetStateAction;
  42388. var SetValueAction = /** @class */ (function (_super) {
  42389. __extends(SetValueAction, _super);
  42390. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42391. var _this = _super.call(this, triggerOptions, condition) || this;
  42392. _this.propertyPath = propertyPath;
  42393. _this.value = value;
  42394. _this._target = _this._effectiveTarget = target;
  42395. return _this;
  42396. }
  42397. SetValueAction.prototype._prepare = function () {
  42398. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42399. this._property = this._getProperty(this.propertyPath);
  42400. };
  42401. SetValueAction.prototype.execute = function () {
  42402. this._effectiveTarget[this._property] = this.value;
  42403. if (this._target.markAsDirty) {
  42404. this._target.markAsDirty(this._property);
  42405. }
  42406. };
  42407. SetValueAction.prototype.serialize = function (parent) {
  42408. return _super.prototype._serialize.call(this, {
  42409. name: "SetValueAction",
  42410. properties: [
  42411. BABYLON.Action._GetTargetProperty(this._target),
  42412. { name: "propertyPath", value: this.propertyPath },
  42413. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42414. ]
  42415. }, parent);
  42416. };
  42417. return SetValueAction;
  42418. }(BABYLON.Action));
  42419. BABYLON.SetValueAction = SetValueAction;
  42420. var IncrementValueAction = /** @class */ (function (_super) {
  42421. __extends(IncrementValueAction, _super);
  42422. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42423. var _this = _super.call(this, triggerOptions, condition) || this;
  42424. _this.propertyPath = propertyPath;
  42425. _this.value = value;
  42426. _this._target = _this._effectiveTarget = target;
  42427. return _this;
  42428. }
  42429. IncrementValueAction.prototype._prepare = function () {
  42430. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42431. this._property = this._getProperty(this.propertyPath);
  42432. if (typeof this._effectiveTarget[this._property] !== "number") {
  42433. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42434. }
  42435. };
  42436. IncrementValueAction.prototype.execute = function () {
  42437. this._effectiveTarget[this._property] += this.value;
  42438. if (this._target.markAsDirty) {
  42439. this._target.markAsDirty(this._property);
  42440. }
  42441. };
  42442. IncrementValueAction.prototype.serialize = function (parent) {
  42443. return _super.prototype._serialize.call(this, {
  42444. name: "IncrementValueAction",
  42445. properties: [
  42446. BABYLON.Action._GetTargetProperty(this._target),
  42447. { name: "propertyPath", value: this.propertyPath },
  42448. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42449. ]
  42450. }, parent);
  42451. };
  42452. return IncrementValueAction;
  42453. }(BABYLON.Action));
  42454. BABYLON.IncrementValueAction = IncrementValueAction;
  42455. var PlayAnimationAction = /** @class */ (function (_super) {
  42456. __extends(PlayAnimationAction, _super);
  42457. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42458. var _this = _super.call(this, triggerOptions, condition) || this;
  42459. _this.from = from;
  42460. _this.to = to;
  42461. _this.loop = loop;
  42462. _this._target = target;
  42463. return _this;
  42464. }
  42465. PlayAnimationAction.prototype._prepare = function () {
  42466. };
  42467. PlayAnimationAction.prototype.execute = function () {
  42468. var scene = this._actionManager.getScene();
  42469. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42470. };
  42471. PlayAnimationAction.prototype.serialize = function (parent) {
  42472. return _super.prototype._serialize.call(this, {
  42473. name: "PlayAnimationAction",
  42474. properties: [
  42475. BABYLON.Action._GetTargetProperty(this._target),
  42476. { name: "from", value: String(this.from) },
  42477. { name: "to", value: String(this.to) },
  42478. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42479. ]
  42480. }, parent);
  42481. };
  42482. return PlayAnimationAction;
  42483. }(BABYLON.Action));
  42484. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42485. var StopAnimationAction = /** @class */ (function (_super) {
  42486. __extends(StopAnimationAction, _super);
  42487. function StopAnimationAction(triggerOptions, target, condition) {
  42488. var _this = _super.call(this, triggerOptions, condition) || this;
  42489. _this._target = target;
  42490. return _this;
  42491. }
  42492. StopAnimationAction.prototype._prepare = function () {
  42493. };
  42494. StopAnimationAction.prototype.execute = function () {
  42495. var scene = this._actionManager.getScene();
  42496. scene.stopAnimation(this._target);
  42497. };
  42498. StopAnimationAction.prototype.serialize = function (parent) {
  42499. return _super.prototype._serialize.call(this, {
  42500. name: "StopAnimationAction",
  42501. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42502. }, parent);
  42503. };
  42504. return StopAnimationAction;
  42505. }(BABYLON.Action));
  42506. BABYLON.StopAnimationAction = StopAnimationAction;
  42507. var DoNothingAction = /** @class */ (function (_super) {
  42508. __extends(DoNothingAction, _super);
  42509. function DoNothingAction(triggerOptions, condition) {
  42510. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42511. return _super.call(this, triggerOptions, condition) || this;
  42512. }
  42513. DoNothingAction.prototype.execute = function () {
  42514. };
  42515. DoNothingAction.prototype.serialize = function (parent) {
  42516. return _super.prototype._serialize.call(this, {
  42517. name: "DoNothingAction",
  42518. properties: []
  42519. }, parent);
  42520. };
  42521. return DoNothingAction;
  42522. }(BABYLON.Action));
  42523. BABYLON.DoNothingAction = DoNothingAction;
  42524. var CombineAction = /** @class */ (function (_super) {
  42525. __extends(CombineAction, _super);
  42526. function CombineAction(triggerOptions, children, condition) {
  42527. var _this = _super.call(this, triggerOptions, condition) || this;
  42528. _this.children = children;
  42529. return _this;
  42530. }
  42531. CombineAction.prototype._prepare = function () {
  42532. for (var index = 0; index < this.children.length; index++) {
  42533. this.children[index]._actionManager = this._actionManager;
  42534. this.children[index]._prepare();
  42535. }
  42536. };
  42537. CombineAction.prototype.execute = function (evt) {
  42538. for (var index = 0; index < this.children.length; index++) {
  42539. this.children[index].execute(evt);
  42540. }
  42541. };
  42542. CombineAction.prototype.serialize = function (parent) {
  42543. var serializationObject = _super.prototype._serialize.call(this, {
  42544. name: "CombineAction",
  42545. properties: [],
  42546. combine: []
  42547. }, parent);
  42548. for (var i = 0; i < this.children.length; i++) {
  42549. serializationObject.combine.push(this.children[i].serialize(null));
  42550. }
  42551. return serializationObject;
  42552. };
  42553. return CombineAction;
  42554. }(BABYLON.Action));
  42555. BABYLON.CombineAction = CombineAction;
  42556. var ExecuteCodeAction = /** @class */ (function (_super) {
  42557. __extends(ExecuteCodeAction, _super);
  42558. function ExecuteCodeAction(triggerOptions, func, condition) {
  42559. var _this = _super.call(this, triggerOptions, condition) || this;
  42560. _this.func = func;
  42561. return _this;
  42562. }
  42563. ExecuteCodeAction.prototype.execute = function (evt) {
  42564. this.func(evt);
  42565. };
  42566. return ExecuteCodeAction;
  42567. }(BABYLON.Action));
  42568. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42569. var SetParentAction = /** @class */ (function (_super) {
  42570. __extends(SetParentAction, _super);
  42571. function SetParentAction(triggerOptions, target, parent, condition) {
  42572. var _this = _super.call(this, triggerOptions, condition) || this;
  42573. _this._target = target;
  42574. _this._parent = parent;
  42575. return _this;
  42576. }
  42577. SetParentAction.prototype._prepare = function () {
  42578. };
  42579. SetParentAction.prototype.execute = function () {
  42580. if (this._target.parent === this._parent) {
  42581. return;
  42582. }
  42583. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42584. invertParentWorldMatrix.invert();
  42585. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42586. this._target.parent = this._parent;
  42587. };
  42588. SetParentAction.prototype.serialize = function (parent) {
  42589. return _super.prototype._serialize.call(this, {
  42590. name: "SetParentAction",
  42591. properties: [
  42592. BABYLON.Action._GetTargetProperty(this._target),
  42593. BABYLON.Action._GetTargetProperty(this._parent),
  42594. ]
  42595. }, parent);
  42596. };
  42597. return SetParentAction;
  42598. }(BABYLON.Action));
  42599. BABYLON.SetParentAction = SetParentAction;
  42600. var PlaySoundAction = /** @class */ (function (_super) {
  42601. __extends(PlaySoundAction, _super);
  42602. function PlaySoundAction(triggerOptions, sound, condition) {
  42603. var _this = _super.call(this, triggerOptions, condition) || this;
  42604. _this._sound = sound;
  42605. return _this;
  42606. }
  42607. PlaySoundAction.prototype._prepare = function () {
  42608. };
  42609. PlaySoundAction.prototype.execute = function () {
  42610. if (this._sound !== undefined)
  42611. this._sound.play();
  42612. };
  42613. PlaySoundAction.prototype.serialize = function (parent) {
  42614. return _super.prototype._serialize.call(this, {
  42615. name: "PlaySoundAction",
  42616. properties: [{ name: "sound", value: this._sound.name }]
  42617. }, parent);
  42618. };
  42619. return PlaySoundAction;
  42620. }(BABYLON.Action));
  42621. BABYLON.PlaySoundAction = PlaySoundAction;
  42622. var StopSoundAction = /** @class */ (function (_super) {
  42623. __extends(StopSoundAction, _super);
  42624. function StopSoundAction(triggerOptions, sound, condition) {
  42625. var _this = _super.call(this, triggerOptions, condition) || this;
  42626. _this._sound = sound;
  42627. return _this;
  42628. }
  42629. StopSoundAction.prototype._prepare = function () {
  42630. };
  42631. StopSoundAction.prototype.execute = function () {
  42632. if (this._sound !== undefined)
  42633. this._sound.stop();
  42634. };
  42635. StopSoundAction.prototype.serialize = function (parent) {
  42636. return _super.prototype._serialize.call(this, {
  42637. name: "StopSoundAction",
  42638. properties: [{ name: "sound", value: this._sound.name }]
  42639. }, parent);
  42640. };
  42641. return StopSoundAction;
  42642. }(BABYLON.Action));
  42643. BABYLON.StopSoundAction = StopSoundAction;
  42644. })(BABYLON || (BABYLON = {}));
  42645. //# sourceMappingURL=babylon.directActions.js.map
  42646. var BABYLON;
  42647. (function (BABYLON) {
  42648. var SpriteManager = /** @class */ (function () {
  42649. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  42650. if (epsilon === void 0) { epsilon = 0.01; }
  42651. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42652. this.name = name;
  42653. this.sprites = new Array();
  42654. this.renderingGroupId = 0;
  42655. this.layerMask = 0x0FFFFFFF;
  42656. this.fogEnabled = true;
  42657. this.isPickable = false;
  42658. /**
  42659. * An event triggered when the manager is disposed.
  42660. * @type {BABYLON.Observable}
  42661. */
  42662. this.onDisposeObservable = new BABYLON.Observable();
  42663. this._vertexBuffers = {};
  42664. this._capacity = capacity;
  42665. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  42666. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42667. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42668. if (cellSize.width && cellSize.height) {
  42669. this.cellWidth = cellSize.width;
  42670. this.cellHeight = cellSize.height;
  42671. }
  42672. else if (cellSize !== undefined) {
  42673. this.cellWidth = cellSize;
  42674. this.cellHeight = cellSize;
  42675. }
  42676. else {
  42677. return;
  42678. }
  42679. this._epsilon = epsilon;
  42680. this._scene = scene;
  42681. this._scene.spriteManagers.push(this);
  42682. var indices = [];
  42683. var index = 0;
  42684. for (var count = 0; count < capacity; count++) {
  42685. indices.push(index);
  42686. indices.push(index + 1);
  42687. indices.push(index + 2);
  42688. indices.push(index);
  42689. indices.push(index + 2);
  42690. indices.push(index + 3);
  42691. index += 4;
  42692. }
  42693. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  42694. // VBO
  42695. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  42696. this._vertexData = new Float32Array(capacity * 16 * 4);
  42697. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  42698. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  42699. var options = this._buffer.createVertexBuffer("options", 4, 4);
  42700. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  42701. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  42702. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42703. this._vertexBuffers["options"] = options;
  42704. this._vertexBuffers["cellInfo"] = cellInfo;
  42705. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42706. // Effects
  42707. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  42708. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  42709. }
  42710. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  42711. set: function (callback) {
  42712. if (this._onDisposeObserver) {
  42713. this.onDisposeObservable.remove(this._onDisposeObserver);
  42714. }
  42715. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42716. },
  42717. enumerable: true,
  42718. configurable: true
  42719. });
  42720. Object.defineProperty(SpriteManager.prototype, "texture", {
  42721. get: function () {
  42722. return this._spriteTexture;
  42723. },
  42724. set: function (value) {
  42725. this._spriteTexture = value;
  42726. },
  42727. enumerable: true,
  42728. configurable: true
  42729. });
  42730. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  42731. var arrayOffset = index * 16;
  42732. if (offsetX === 0)
  42733. offsetX = this._epsilon;
  42734. else if (offsetX === 1)
  42735. offsetX = 1 - this._epsilon;
  42736. if (offsetY === 0)
  42737. offsetY = this._epsilon;
  42738. else if (offsetY === 1)
  42739. offsetY = 1 - this._epsilon;
  42740. this._vertexData[arrayOffset] = sprite.position.x;
  42741. this._vertexData[arrayOffset + 1] = sprite.position.y;
  42742. this._vertexData[arrayOffset + 2] = sprite.position.z;
  42743. this._vertexData[arrayOffset + 3] = sprite.angle;
  42744. this._vertexData[arrayOffset + 4] = sprite.width;
  42745. this._vertexData[arrayOffset + 5] = sprite.height;
  42746. this._vertexData[arrayOffset + 6] = offsetX;
  42747. this._vertexData[arrayOffset + 7] = offsetY;
  42748. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  42749. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  42750. var offset = (sprite.cellIndex / rowSize) >> 0;
  42751. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  42752. this._vertexData[arrayOffset + 11] = offset;
  42753. // Color
  42754. this._vertexData[arrayOffset + 12] = sprite.color.r;
  42755. this._vertexData[arrayOffset + 13] = sprite.color.g;
  42756. this._vertexData[arrayOffset + 14] = sprite.color.b;
  42757. this._vertexData[arrayOffset + 15] = sprite.color.a;
  42758. };
  42759. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  42760. var count = Math.min(this._capacity, this.sprites.length);
  42761. var min = BABYLON.Vector3.Zero();
  42762. var max = BABYLON.Vector3.Zero();
  42763. var distance = Number.MAX_VALUE;
  42764. var currentSprite = null;
  42765. var cameraSpacePosition = BABYLON.Vector3.Zero();
  42766. var cameraView = camera.getViewMatrix();
  42767. for (var index = 0; index < count; index++) {
  42768. var sprite = this.sprites[index];
  42769. if (!sprite) {
  42770. continue;
  42771. }
  42772. if (predicate) {
  42773. if (!predicate(sprite)) {
  42774. continue;
  42775. }
  42776. }
  42777. else if (!sprite.isPickable) {
  42778. continue;
  42779. }
  42780. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  42781. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  42782. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  42783. if (ray.intersectsBoxMinMax(min, max)) {
  42784. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  42785. if (distance > currentDistance) {
  42786. distance = currentDistance;
  42787. currentSprite = sprite;
  42788. if (fastCheck) {
  42789. break;
  42790. }
  42791. }
  42792. }
  42793. }
  42794. if (currentSprite) {
  42795. var result = new BABYLON.PickingInfo();
  42796. result.hit = true;
  42797. result.pickedSprite = currentSprite;
  42798. result.distance = distance;
  42799. return result;
  42800. }
  42801. return null;
  42802. };
  42803. SpriteManager.prototype.render = function () {
  42804. // Check
  42805. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42806. return;
  42807. var engine = this._scene.getEngine();
  42808. var baseSize = this._spriteTexture.getBaseSize();
  42809. // Sprites
  42810. var deltaTime = engine.getDeltaTime();
  42811. var max = Math.min(this._capacity, this.sprites.length);
  42812. var rowSize = baseSize.width / this.cellWidth;
  42813. var offset = 0;
  42814. for (var index = 0; index < max; index++) {
  42815. var sprite = this.sprites[index];
  42816. if (!sprite) {
  42817. continue;
  42818. }
  42819. sprite._animate(deltaTime);
  42820. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42821. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42822. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42823. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42824. }
  42825. this._buffer.update(this._vertexData);
  42826. // Render
  42827. var effect = this._effectBase;
  42828. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42829. effect = this._effectFog;
  42830. }
  42831. engine.enableEffect(effect);
  42832. var viewMatrix = this._scene.getViewMatrix();
  42833. effect.setTexture("diffuseSampler", this._spriteTexture);
  42834. effect.setMatrix("view", viewMatrix);
  42835. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42836. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42837. // Fog
  42838. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42839. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42840. effect.setColor3("vFogColor", this._scene.fogColor);
  42841. }
  42842. // VBOs
  42843. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42844. // Draw order
  42845. engine.setDepthFunctionToLessOrEqual();
  42846. effect.setBool("alphaTest", true);
  42847. engine.setColorWrite(false);
  42848. engine.draw(true, 0, max * 6);
  42849. engine.setColorWrite(true);
  42850. effect.setBool("alphaTest", false);
  42851. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42852. engine.draw(true, 0, max * 6);
  42853. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42854. };
  42855. SpriteManager.prototype.dispose = function () {
  42856. if (this._buffer) {
  42857. this._buffer.dispose();
  42858. this._buffer = null;
  42859. }
  42860. if (this._indexBuffer) {
  42861. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42862. this._indexBuffer = null;
  42863. }
  42864. if (this._spriteTexture) {
  42865. this._spriteTexture.dispose();
  42866. this._spriteTexture = null;
  42867. }
  42868. // Remove from scene
  42869. var index = this._scene.spriteManagers.indexOf(this);
  42870. this._scene.spriteManagers.splice(index, 1);
  42871. // Callback
  42872. this.onDisposeObservable.notifyObservers(this);
  42873. this.onDisposeObservable.clear();
  42874. };
  42875. return SpriteManager;
  42876. }());
  42877. BABYLON.SpriteManager = SpriteManager;
  42878. })(BABYLON || (BABYLON = {}));
  42879. //# sourceMappingURL=babylon.spriteManager.js.map
  42880. var BABYLON;
  42881. (function (BABYLON) {
  42882. var Sprite = /** @class */ (function () {
  42883. function Sprite(name, manager) {
  42884. this.name = name;
  42885. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42886. this.width = 1.0;
  42887. this.height = 1.0;
  42888. this.angle = 0;
  42889. this.cellIndex = 0;
  42890. this.invertU = 0;
  42891. this.invertV = 0;
  42892. this.animations = new Array();
  42893. this.isPickable = false;
  42894. this._animationStarted = false;
  42895. this._loopAnimation = false;
  42896. this._fromIndex = 0;
  42897. this._toIndex = 0;
  42898. this._delay = 0;
  42899. this._direction = 1;
  42900. this._time = 0;
  42901. this._manager = manager;
  42902. this._manager.sprites.push(this);
  42903. this.position = BABYLON.Vector3.Zero();
  42904. }
  42905. Object.defineProperty(Sprite.prototype, "size", {
  42906. get: function () {
  42907. return this.width;
  42908. },
  42909. set: function (value) {
  42910. this.width = value;
  42911. this.height = value;
  42912. },
  42913. enumerable: true,
  42914. configurable: true
  42915. });
  42916. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  42917. this._fromIndex = from;
  42918. this._toIndex = to;
  42919. this._loopAnimation = loop;
  42920. this._delay = delay;
  42921. this._animationStarted = true;
  42922. this._direction = from < to ? 1 : -1;
  42923. this.cellIndex = from;
  42924. this._time = 0;
  42925. this._onAnimationEnd = onAnimationEnd;
  42926. };
  42927. Sprite.prototype.stopAnimation = function () {
  42928. this._animationStarted = false;
  42929. };
  42930. Sprite.prototype._animate = function (deltaTime) {
  42931. if (!this._animationStarted)
  42932. return;
  42933. this._time += deltaTime;
  42934. if (this._time > this._delay) {
  42935. this._time = this._time % this._delay;
  42936. this.cellIndex += this._direction;
  42937. if (this.cellIndex > this._toIndex) {
  42938. if (this._loopAnimation) {
  42939. this.cellIndex = this._fromIndex;
  42940. }
  42941. else {
  42942. this.cellIndex = this._toIndex;
  42943. this._animationStarted = false;
  42944. if (this._onAnimationEnd) {
  42945. this._onAnimationEnd();
  42946. }
  42947. if (this.disposeWhenFinishedAnimating) {
  42948. this.dispose();
  42949. }
  42950. }
  42951. }
  42952. }
  42953. };
  42954. Sprite.prototype.dispose = function () {
  42955. for (var i = 0; i < this._manager.sprites.length; i++) {
  42956. if (this._manager.sprites[i] == this) {
  42957. this._manager.sprites.splice(i, 1);
  42958. }
  42959. }
  42960. };
  42961. return Sprite;
  42962. }());
  42963. BABYLON.Sprite = Sprite;
  42964. })(BABYLON || (BABYLON = {}));
  42965. //# sourceMappingURL=babylon.sprite.js.map
  42966. var BABYLON;
  42967. (function (BABYLON) {
  42968. var IntersectionInfo = /** @class */ (function () {
  42969. function IntersectionInfo(bu, bv, distance) {
  42970. this.bu = bu;
  42971. this.bv = bv;
  42972. this.distance = distance;
  42973. this.faceId = 0;
  42974. this.subMeshId = 0;
  42975. }
  42976. return IntersectionInfo;
  42977. }());
  42978. BABYLON.IntersectionInfo = IntersectionInfo;
  42979. var PickingInfo = /** @class */ (function () {
  42980. function PickingInfo() {
  42981. this.hit = false;
  42982. this.distance = 0;
  42983. this.pickedPoint = null;
  42984. this.pickedMesh = null;
  42985. this.bu = 0;
  42986. this.bv = 0;
  42987. this.faceId = -1;
  42988. this.subMeshId = 0;
  42989. this.pickedSprite = null;
  42990. }
  42991. // Methods
  42992. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  42993. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  42994. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  42995. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42996. return null;
  42997. }
  42998. var indices = this.pickedMesh.getIndices();
  42999. if (!indices) {
  43000. return null;
  43001. }
  43002. var result;
  43003. if (useVerticesNormals) {
  43004. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43005. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  43006. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  43007. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  43008. normal0 = normal0.scale(this.bu);
  43009. normal1 = normal1.scale(this.bv);
  43010. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  43011. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  43012. }
  43013. else {
  43014. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43015. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  43016. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  43017. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  43018. var p1p2 = vertex1.subtract(vertex2);
  43019. var p3p2 = vertex3.subtract(vertex2);
  43020. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  43021. }
  43022. if (useWorldCoordinates) {
  43023. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  43024. }
  43025. return BABYLON.Vector3.Normalize(result);
  43026. };
  43027. PickingInfo.prototype.getTextureCoordinates = function () {
  43028. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43029. return null;
  43030. }
  43031. var indices = this.pickedMesh.getIndices();
  43032. if (!indices) {
  43033. return null;
  43034. }
  43035. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43036. if (!uvs) {
  43037. return null;
  43038. }
  43039. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  43040. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  43041. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  43042. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  43043. uv1 = uv1.scale(this.bu);
  43044. uv2 = uv2.scale(this.bv);
  43045. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  43046. };
  43047. return PickingInfo;
  43048. }());
  43049. BABYLON.PickingInfo = PickingInfo;
  43050. })(BABYLON || (BABYLON = {}));
  43051. //# sourceMappingURL=babylon.pickingInfo.js.map
  43052. var BABYLON;
  43053. (function (BABYLON) {
  43054. var Ray = /** @class */ (function () {
  43055. function Ray(origin, direction, length) {
  43056. if (length === void 0) { length = Number.MAX_VALUE; }
  43057. this.origin = origin;
  43058. this.direction = direction;
  43059. this.length = length;
  43060. }
  43061. // Methods
  43062. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  43063. var d = 0.0;
  43064. var maxValue = Number.MAX_VALUE;
  43065. var inv;
  43066. var min;
  43067. var max;
  43068. var temp;
  43069. if (Math.abs(this.direction.x) < 0.0000001) {
  43070. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  43071. return false;
  43072. }
  43073. }
  43074. else {
  43075. inv = 1.0 / this.direction.x;
  43076. min = (minimum.x - this.origin.x) * inv;
  43077. max = (maximum.x - this.origin.x) * inv;
  43078. if (max === -Infinity) {
  43079. max = Infinity;
  43080. }
  43081. if (min > max) {
  43082. temp = min;
  43083. min = max;
  43084. max = temp;
  43085. }
  43086. d = Math.max(min, d);
  43087. maxValue = Math.min(max, maxValue);
  43088. if (d > maxValue) {
  43089. return false;
  43090. }
  43091. }
  43092. if (Math.abs(this.direction.y) < 0.0000001) {
  43093. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43094. return false;
  43095. }
  43096. }
  43097. else {
  43098. inv = 1.0 / this.direction.y;
  43099. min = (minimum.y - this.origin.y) * inv;
  43100. max = (maximum.y - this.origin.y) * inv;
  43101. if (max === -Infinity) {
  43102. max = Infinity;
  43103. }
  43104. if (min > max) {
  43105. temp = min;
  43106. min = max;
  43107. max = temp;
  43108. }
  43109. d = Math.max(min, d);
  43110. maxValue = Math.min(max, maxValue);
  43111. if (d > maxValue) {
  43112. return false;
  43113. }
  43114. }
  43115. if (Math.abs(this.direction.z) < 0.0000001) {
  43116. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43117. return false;
  43118. }
  43119. }
  43120. else {
  43121. inv = 1.0 / this.direction.z;
  43122. min = (minimum.z - this.origin.z) * inv;
  43123. max = (maximum.z - this.origin.z) * inv;
  43124. if (max === -Infinity) {
  43125. max = Infinity;
  43126. }
  43127. if (min > max) {
  43128. temp = min;
  43129. min = max;
  43130. max = temp;
  43131. }
  43132. d = Math.max(min, d);
  43133. maxValue = Math.min(max, maxValue);
  43134. if (d > maxValue) {
  43135. return false;
  43136. }
  43137. }
  43138. return true;
  43139. };
  43140. Ray.prototype.intersectsBox = function (box) {
  43141. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43142. };
  43143. Ray.prototype.intersectsSphere = function (sphere) {
  43144. var x = sphere.center.x - this.origin.x;
  43145. var y = sphere.center.y - this.origin.y;
  43146. var z = sphere.center.z - this.origin.z;
  43147. var pyth = (x * x) + (y * y) + (z * z);
  43148. var rr = sphere.radius * sphere.radius;
  43149. if (pyth <= rr) {
  43150. return true;
  43151. }
  43152. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43153. if (dot < 0.0) {
  43154. return false;
  43155. }
  43156. var temp = pyth - (dot * dot);
  43157. return temp <= rr;
  43158. };
  43159. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43160. if (!this._edge1) {
  43161. this._edge1 = BABYLON.Vector3.Zero();
  43162. this._edge2 = BABYLON.Vector3.Zero();
  43163. this._pvec = BABYLON.Vector3.Zero();
  43164. this._tvec = BABYLON.Vector3.Zero();
  43165. this._qvec = BABYLON.Vector3.Zero();
  43166. }
  43167. vertex1.subtractToRef(vertex0, this._edge1);
  43168. vertex2.subtractToRef(vertex0, this._edge2);
  43169. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43170. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43171. if (det === 0) {
  43172. return null;
  43173. }
  43174. var invdet = 1 / det;
  43175. this.origin.subtractToRef(vertex0, this._tvec);
  43176. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43177. if (bu < 0 || bu > 1.0) {
  43178. return null;
  43179. }
  43180. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43181. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43182. if (bv < 0 || bu + bv > 1.0) {
  43183. return null;
  43184. }
  43185. //check if the distance is longer than the predefined length.
  43186. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43187. if (distance > this.length) {
  43188. return null;
  43189. }
  43190. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43191. };
  43192. Ray.prototype.intersectsPlane = function (plane) {
  43193. var distance;
  43194. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43195. if (Math.abs(result1) < 9.99999997475243E-07) {
  43196. return null;
  43197. }
  43198. else {
  43199. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43200. distance = (-plane.d - result2) / result1;
  43201. if (distance < 0.0) {
  43202. if (distance < -9.99999997475243E-07) {
  43203. return null;
  43204. }
  43205. else {
  43206. return 0;
  43207. }
  43208. }
  43209. return distance;
  43210. }
  43211. };
  43212. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43213. var tm = BABYLON.Tmp.Matrix[0];
  43214. mesh.getWorldMatrix().invertToRef(tm);
  43215. if (this._tmpRay) {
  43216. Ray.TransformToRef(this, tm, this._tmpRay);
  43217. }
  43218. else {
  43219. this._tmpRay = Ray.Transform(this, tm);
  43220. }
  43221. return mesh.intersects(this._tmpRay, fastCheck);
  43222. };
  43223. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43224. if (results) {
  43225. results.length = 0;
  43226. }
  43227. else {
  43228. results = [];
  43229. }
  43230. for (var i = 0; i < meshes.length; i++) {
  43231. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43232. if (pickInfo.hit) {
  43233. results.push(pickInfo);
  43234. }
  43235. }
  43236. results.sort(this._comparePickingInfo);
  43237. return results;
  43238. };
  43239. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43240. if (pickingInfoA.distance < pickingInfoB.distance) {
  43241. return -1;
  43242. }
  43243. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43244. return 1;
  43245. }
  43246. else {
  43247. return 0;
  43248. }
  43249. };
  43250. /**
  43251. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43252. * @param sega the first point of the segment to test the intersection against
  43253. * @param segb the second point of the segment to test the intersection against
  43254. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43255. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43256. */
  43257. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43258. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43259. var u = segb.subtract(sega);
  43260. var v = rsegb.subtract(this.origin);
  43261. var w = sega.subtract(this.origin);
  43262. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43263. var b = BABYLON.Vector3.Dot(u, v);
  43264. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43265. var d = BABYLON.Vector3.Dot(u, w);
  43266. var e = BABYLON.Vector3.Dot(v, w);
  43267. var D = a * c - b * b; // always >= 0
  43268. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43269. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43270. // compute the line parameters of the two closest points
  43271. if (D < Ray.smallnum) {
  43272. sN = 0.0; // force using point P0 on segment S1
  43273. sD = 1.0; // to prevent possible division by 0.0 later
  43274. tN = e;
  43275. tD = c;
  43276. }
  43277. else {
  43278. sN = (b * e - c * d);
  43279. tN = (a * e - b * d);
  43280. if (sN < 0.0) {
  43281. sN = 0.0;
  43282. tN = e;
  43283. tD = c;
  43284. }
  43285. else if (sN > sD) {
  43286. sN = sD;
  43287. tN = e + b;
  43288. tD = c;
  43289. }
  43290. }
  43291. if (tN < 0.0) {
  43292. tN = 0.0;
  43293. // recompute sc for this edge
  43294. if (-d < 0.0) {
  43295. sN = 0.0;
  43296. }
  43297. else if (-d > a)
  43298. sN = sD;
  43299. else {
  43300. sN = -d;
  43301. sD = a;
  43302. }
  43303. }
  43304. else if (tN > tD) {
  43305. tN = tD;
  43306. // recompute sc for this edge
  43307. if ((-d + b) < 0.0) {
  43308. sN = 0;
  43309. }
  43310. else if ((-d + b) > a) {
  43311. sN = sD;
  43312. }
  43313. else {
  43314. sN = (-d + b);
  43315. sD = a;
  43316. }
  43317. }
  43318. // finally do the division to get sc and tc
  43319. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43320. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43321. // get the difference of the two closest points
  43322. var qtc = v.multiplyByFloats(tc, tc, tc);
  43323. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43324. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43325. if (isIntersected) {
  43326. return qtc.length();
  43327. }
  43328. return -1;
  43329. };
  43330. // Statics
  43331. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43332. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  43333. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  43334. var direction = end.subtract(start);
  43335. direction.normalize();
  43336. return new Ray(start, direction);
  43337. };
  43338. /**
  43339. * 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
  43340. * transformed to the given world matrix.
  43341. * @param origin The origin point
  43342. * @param end The end point
  43343. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43344. */
  43345. Ray.CreateNewFromTo = function (origin, end, world) {
  43346. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43347. var direction = end.subtract(origin);
  43348. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43349. direction.normalize();
  43350. return Ray.Transform(new Ray(origin, direction, length), world);
  43351. };
  43352. Ray.Transform = function (ray, matrix) {
  43353. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43354. Ray.TransformToRef(ray, matrix, result);
  43355. return result;
  43356. };
  43357. Ray.TransformToRef = function (ray, matrix, result) {
  43358. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43359. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43360. result.length = ray.length;
  43361. var dir = result.direction;
  43362. var len = dir.length();
  43363. if (!(len === 0 || len === 1)) {
  43364. var num = 1.0 / len;
  43365. dir.x *= num;
  43366. dir.y *= num;
  43367. dir.z *= num;
  43368. result.length *= len;
  43369. }
  43370. };
  43371. Ray.smallnum = 0.00000001;
  43372. Ray.rayl = 10e8;
  43373. return Ray;
  43374. }());
  43375. BABYLON.Ray = Ray;
  43376. })(BABYLON || (BABYLON = {}));
  43377. //# sourceMappingURL=babylon.ray.js.map
  43378. var BABYLON;
  43379. (function (BABYLON) {
  43380. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43381. if (boxMin.x > sphereCenter.x + sphereRadius)
  43382. return false;
  43383. if (sphereCenter.x - sphereRadius > boxMax.x)
  43384. return false;
  43385. if (boxMin.y > sphereCenter.y + sphereRadius)
  43386. return false;
  43387. if (sphereCenter.y - sphereRadius > boxMax.y)
  43388. return false;
  43389. if (boxMin.z > sphereCenter.z + sphereRadius)
  43390. return false;
  43391. if (sphereCenter.z - sphereRadius > boxMax.z)
  43392. return false;
  43393. return true;
  43394. };
  43395. var getLowestRoot = (function () {
  43396. var result = { root: 0, found: false };
  43397. return function (a, b, c, maxR) {
  43398. result.root = 0;
  43399. result.found = false;
  43400. var determinant = b * b - 4.0 * a * c;
  43401. if (determinant < 0)
  43402. return result;
  43403. var sqrtD = Math.sqrt(determinant);
  43404. var r1 = (-b - sqrtD) / (2.0 * a);
  43405. var r2 = (-b + sqrtD) / (2.0 * a);
  43406. if (r1 > r2) {
  43407. var temp = r2;
  43408. r2 = r1;
  43409. r1 = temp;
  43410. }
  43411. if (r1 > 0 && r1 < maxR) {
  43412. result.root = r1;
  43413. result.found = true;
  43414. return result;
  43415. }
  43416. if (r2 > 0 && r2 < maxR) {
  43417. result.root = r2;
  43418. result.found = true;
  43419. return result;
  43420. }
  43421. return result;
  43422. };
  43423. })();
  43424. var Collider = /** @class */ (function () {
  43425. function Collider() {
  43426. this.radius = BABYLON.Vector3.One();
  43427. this.retry = 0;
  43428. this.basePointWorld = BABYLON.Vector3.Zero();
  43429. this.velocityWorld = BABYLON.Vector3.Zero();
  43430. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43431. this._collisionPoint = BABYLON.Vector3.Zero();
  43432. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43433. this._tempVector = BABYLON.Vector3.Zero();
  43434. this._tempVector2 = BABYLON.Vector3.Zero();
  43435. this._tempVector3 = BABYLON.Vector3.Zero();
  43436. this._tempVector4 = BABYLON.Vector3.Zero();
  43437. this._edge = BABYLON.Vector3.Zero();
  43438. this._baseToVertex = BABYLON.Vector3.Zero();
  43439. this._destinationPoint = BABYLON.Vector3.Zero();
  43440. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43441. this._displacementVector = BABYLON.Vector3.Zero();
  43442. this._collisionMask = -1;
  43443. }
  43444. Object.defineProperty(Collider.prototype, "collisionMask", {
  43445. get: function () {
  43446. return this._collisionMask;
  43447. },
  43448. set: function (mask) {
  43449. this._collisionMask = !isNaN(mask) ? mask : -1;
  43450. },
  43451. enumerable: true,
  43452. configurable: true
  43453. });
  43454. // Methods
  43455. Collider.prototype._initialize = function (source, dir, e) {
  43456. this.velocity = dir;
  43457. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43458. this.basePoint = source;
  43459. source.multiplyToRef(this.radius, this.basePointWorld);
  43460. dir.multiplyToRef(this.radius, this.velocityWorld);
  43461. this.velocityWorldLength = this.velocityWorld.length();
  43462. this.epsilon = e;
  43463. this.collisionFound = false;
  43464. };
  43465. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43466. pa.subtractToRef(point, this._tempVector);
  43467. pb.subtractToRef(point, this._tempVector2);
  43468. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43469. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43470. if (d < 0)
  43471. return false;
  43472. pc.subtractToRef(point, this._tempVector3);
  43473. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43474. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43475. if (d < 0)
  43476. return false;
  43477. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43478. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43479. return d >= 0;
  43480. };
  43481. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43482. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43483. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43484. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43485. return false;
  43486. }
  43487. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43488. return false;
  43489. return true;
  43490. };
  43491. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43492. var t0;
  43493. var embeddedInPlane = false;
  43494. //defensive programming, actually not needed.
  43495. if (!trianglePlaneArray) {
  43496. trianglePlaneArray = [];
  43497. }
  43498. if (!trianglePlaneArray[faceIndex]) {
  43499. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43500. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43501. }
  43502. var trianglePlane = trianglePlaneArray[faceIndex];
  43503. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43504. return;
  43505. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43506. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43507. if (normalDotVelocity == 0) {
  43508. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43509. return;
  43510. embeddedInPlane = true;
  43511. t0 = 0;
  43512. }
  43513. else {
  43514. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43515. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43516. if (t0 > t1) {
  43517. var temp = t1;
  43518. t1 = t0;
  43519. t0 = temp;
  43520. }
  43521. if (t0 > 1.0 || t1 < 0.0)
  43522. return;
  43523. if (t0 < 0)
  43524. t0 = 0;
  43525. if (t0 > 1.0)
  43526. t0 = 1.0;
  43527. }
  43528. this._collisionPoint.copyFromFloats(0, 0, 0);
  43529. var found = false;
  43530. var t = 1.0;
  43531. if (!embeddedInPlane) {
  43532. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43533. this.velocity.scaleToRef(t0, this._tempVector);
  43534. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43535. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43536. found = true;
  43537. t = t0;
  43538. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43539. }
  43540. }
  43541. if (!found) {
  43542. var velocitySquaredLength = this.velocity.lengthSquared();
  43543. var a = velocitySquaredLength;
  43544. this.basePoint.subtractToRef(p1, this._tempVector);
  43545. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43546. var c = this._tempVector.lengthSquared() - 1.0;
  43547. var lowestRoot = getLowestRoot(a, b, c, t);
  43548. if (lowestRoot.found) {
  43549. t = lowestRoot.root;
  43550. found = true;
  43551. this._collisionPoint.copyFrom(p1);
  43552. }
  43553. this.basePoint.subtractToRef(p2, this._tempVector);
  43554. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43555. c = this._tempVector.lengthSquared() - 1.0;
  43556. lowestRoot = getLowestRoot(a, b, c, t);
  43557. if (lowestRoot.found) {
  43558. t = lowestRoot.root;
  43559. found = true;
  43560. this._collisionPoint.copyFrom(p2);
  43561. }
  43562. this.basePoint.subtractToRef(p3, this._tempVector);
  43563. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43564. c = this._tempVector.lengthSquared() - 1.0;
  43565. lowestRoot = getLowestRoot(a, b, c, t);
  43566. if (lowestRoot.found) {
  43567. t = lowestRoot.root;
  43568. found = true;
  43569. this._collisionPoint.copyFrom(p3);
  43570. }
  43571. p2.subtractToRef(p1, this._edge);
  43572. p1.subtractToRef(this.basePoint, this._baseToVertex);
  43573. var edgeSquaredLength = this._edge.lengthSquared();
  43574. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43575. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43576. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43577. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43578. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43579. lowestRoot = getLowestRoot(a, b, c, t);
  43580. if (lowestRoot.found) {
  43581. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43582. if (f >= 0.0 && f <= 1.0) {
  43583. t = lowestRoot.root;
  43584. found = true;
  43585. this._edge.scaleInPlace(f);
  43586. p1.addToRef(this._edge, this._collisionPoint);
  43587. }
  43588. }
  43589. p3.subtractToRef(p2, this._edge);
  43590. p2.subtractToRef(this.basePoint, this._baseToVertex);
  43591. edgeSquaredLength = this._edge.lengthSquared();
  43592. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43593. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43594. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43595. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43596. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43597. lowestRoot = getLowestRoot(a, b, c, t);
  43598. if (lowestRoot.found) {
  43599. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43600. if (f >= 0.0 && f <= 1.0) {
  43601. t = lowestRoot.root;
  43602. found = true;
  43603. this._edge.scaleInPlace(f);
  43604. p2.addToRef(this._edge, this._collisionPoint);
  43605. }
  43606. }
  43607. p1.subtractToRef(p3, this._edge);
  43608. p3.subtractToRef(this.basePoint, this._baseToVertex);
  43609. edgeSquaredLength = this._edge.lengthSquared();
  43610. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43611. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43612. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43613. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43614. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43615. lowestRoot = getLowestRoot(a, b, c, t);
  43616. if (lowestRoot.found) {
  43617. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43618. if (f >= 0.0 && f <= 1.0) {
  43619. t = lowestRoot.root;
  43620. found = true;
  43621. this._edge.scaleInPlace(f);
  43622. p3.addToRef(this._edge, this._collisionPoint);
  43623. }
  43624. }
  43625. }
  43626. if (found) {
  43627. var distToCollision = t * this.velocity.length();
  43628. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  43629. if (!this.intersectionPoint) {
  43630. this.intersectionPoint = this._collisionPoint.clone();
  43631. }
  43632. else {
  43633. this.intersectionPoint.copyFrom(this._collisionPoint);
  43634. }
  43635. this.nearestDistance = distToCollision;
  43636. this.collisionFound = true;
  43637. }
  43638. }
  43639. };
  43640. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  43641. for (var i = indexStart; i < indexEnd; i += 3) {
  43642. var p1 = pts[indices[i] - decal];
  43643. var p2 = pts[indices[i + 1] - decal];
  43644. var p3 = pts[indices[i + 2] - decal];
  43645. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  43646. }
  43647. };
  43648. Collider.prototype._getResponse = function (pos, vel) {
  43649. pos.addToRef(vel, this._destinationPoint);
  43650. vel.scaleInPlace((this.nearestDistance / vel.length()));
  43651. this.basePoint.addToRef(vel, pos);
  43652. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  43653. this._slidePlaneNormal.normalize();
  43654. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  43655. pos.addInPlace(this._displacementVector);
  43656. this.intersectionPoint.addInPlace(this._displacementVector);
  43657. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  43658. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  43659. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  43660. };
  43661. return Collider;
  43662. }());
  43663. BABYLON.Collider = Collider;
  43664. })(BABYLON || (BABYLON = {}));
  43665. //# sourceMappingURL=babylon.collider.js.map
  43666. var BABYLON;
  43667. (function (BABYLON) {
  43668. //WebWorker code will be inserted to this variable.
  43669. BABYLON.CollisionWorker = "";
  43670. var WorkerTaskType;
  43671. (function (WorkerTaskType) {
  43672. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  43673. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  43674. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  43675. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  43676. var WorkerReplyType;
  43677. (function (WorkerReplyType) {
  43678. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  43679. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  43680. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  43681. var CollisionCoordinatorWorker = /** @class */ (function () {
  43682. function CollisionCoordinatorWorker() {
  43683. var _this = this;
  43684. this._scaledPosition = BABYLON.Vector3.Zero();
  43685. this._scaledVelocity = BABYLON.Vector3.Zero();
  43686. this.onMeshUpdated = function (mesh) {
  43687. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  43688. };
  43689. this.onGeometryUpdated = function (geometry) {
  43690. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  43691. };
  43692. this._afterRender = function () {
  43693. if (!_this._init)
  43694. return;
  43695. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  43696. return;
  43697. }
  43698. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  43699. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  43700. if (_this._runningUpdated > 4) {
  43701. return;
  43702. }
  43703. ++_this._runningUpdated;
  43704. var payload = {
  43705. updatedMeshes: _this._addUpdateMeshesList,
  43706. updatedGeometries: _this._addUpdateGeometriesList,
  43707. removedGeometries: _this._toRemoveGeometryArray,
  43708. removedMeshes: _this._toRemoveMeshesArray
  43709. };
  43710. var message = {
  43711. payload: payload,
  43712. taskType: WorkerTaskType.UPDATE
  43713. };
  43714. var serializable = [];
  43715. for (var id in payload.updatedGeometries) {
  43716. if (payload.updatedGeometries.hasOwnProperty(id)) {
  43717. //prepare transferables
  43718. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  43719. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  43720. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  43721. }
  43722. }
  43723. _this._worker.postMessage(message, serializable);
  43724. _this._addUpdateMeshesList = {};
  43725. _this._addUpdateGeometriesList = {};
  43726. _this._toRemoveGeometryArray = [];
  43727. _this._toRemoveMeshesArray = [];
  43728. };
  43729. this._onMessageFromWorker = function (e) {
  43730. var returnData = e.data;
  43731. if (returnData.error != WorkerReplyType.SUCCESS) {
  43732. //TODO what errors can be returned from the worker?
  43733. BABYLON.Tools.Warn("error returned from worker!");
  43734. return;
  43735. }
  43736. switch (returnData.taskType) {
  43737. case WorkerTaskType.INIT:
  43738. _this._init = true;
  43739. //Update the worked with ALL of the scene's current state
  43740. _this._scene.meshes.forEach(function (mesh) {
  43741. _this.onMeshAdded(mesh);
  43742. });
  43743. _this._scene.getGeometries().forEach(function (geometry) {
  43744. _this.onGeometryAdded(geometry);
  43745. });
  43746. break;
  43747. case WorkerTaskType.UPDATE:
  43748. _this._runningUpdated--;
  43749. break;
  43750. case WorkerTaskType.COLLIDE:
  43751. _this._runningCollisionTask = false;
  43752. var returnPayload = returnData.payload;
  43753. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  43754. return;
  43755. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  43756. if (callback) {
  43757. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  43758. if (mesh) {
  43759. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  43760. }
  43761. }
  43762. //cleanup
  43763. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  43764. break;
  43765. }
  43766. };
  43767. this._collisionsCallbackArray = [];
  43768. this._init = false;
  43769. this._runningUpdated = 0;
  43770. this._runningCollisionTask = false;
  43771. this._addUpdateMeshesList = {};
  43772. this._addUpdateGeometriesList = {};
  43773. this._toRemoveGeometryArray = [];
  43774. this._toRemoveMeshesArray = [];
  43775. }
  43776. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43777. if (!this._init)
  43778. return;
  43779. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  43780. return;
  43781. position.divideToRef(collider.radius, this._scaledPosition);
  43782. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43783. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  43784. var payload = {
  43785. collider: {
  43786. position: this._scaledPosition.asArray(),
  43787. velocity: this._scaledVelocity.asArray(),
  43788. radius: collider.radius.asArray()
  43789. },
  43790. collisionId: collisionIndex,
  43791. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43792. maximumRetry: maximumRetry
  43793. };
  43794. var message = {
  43795. payload: payload,
  43796. taskType: WorkerTaskType.COLLIDE
  43797. };
  43798. this._worker.postMessage(message);
  43799. };
  43800. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43801. this._scene = scene;
  43802. this._scene.registerAfterRender(this._afterRender);
  43803. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43804. this._worker = new Worker(workerUrl);
  43805. this._worker.onmessage = this._onMessageFromWorker;
  43806. var message = {
  43807. payload: {},
  43808. taskType: WorkerTaskType.INIT
  43809. };
  43810. this._worker.postMessage(message);
  43811. };
  43812. CollisionCoordinatorWorker.prototype.destroy = function () {
  43813. this._scene.unregisterAfterRender(this._afterRender);
  43814. this._worker.terminate();
  43815. };
  43816. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43817. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43818. this.onMeshUpdated(mesh);
  43819. };
  43820. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43821. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43822. };
  43823. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43824. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43825. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43826. this.onGeometryUpdated(geometry);
  43827. };
  43828. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43829. this._toRemoveGeometryArray.push(geometry.id);
  43830. };
  43831. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43832. var submeshes = [];
  43833. if (mesh.subMeshes) {
  43834. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43835. var boundingInfo = sm.getBoundingInfo();
  43836. return {
  43837. position: idx,
  43838. verticesStart: sm.verticesStart,
  43839. verticesCount: sm.verticesCount,
  43840. indexStart: sm.indexStart,
  43841. indexCount: sm.indexCount,
  43842. hasMaterial: !!sm.getMaterial(),
  43843. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43844. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43845. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43846. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  43847. };
  43848. });
  43849. }
  43850. var geometryId = null;
  43851. if (mesh instanceof BABYLON.Mesh) {
  43852. var geometry = mesh.geometry;
  43853. geometryId = geometry ? geometry.id : null;
  43854. }
  43855. else if (mesh instanceof BABYLON.InstancedMesh) {
  43856. var geometry = mesh.sourceMesh.geometry;
  43857. geometryId = geometry ? geometry.id : null;
  43858. }
  43859. var boundingInfo = mesh.getBoundingInfo();
  43860. return {
  43861. uniqueId: mesh.uniqueId,
  43862. id: mesh.id,
  43863. name: mesh.name,
  43864. geometryId: geometryId,
  43865. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43866. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43867. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43868. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  43869. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43870. subMeshes: submeshes,
  43871. checkCollisions: mesh.checkCollisions
  43872. };
  43873. };
  43874. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43875. return {
  43876. id: geometry.id,
  43877. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43878. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43879. indices: new Uint32Array(geometry.getIndices() || []),
  43880. };
  43881. };
  43882. return CollisionCoordinatorWorker;
  43883. }());
  43884. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43885. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43886. function CollisionCoordinatorLegacy() {
  43887. this._scaledPosition = BABYLON.Vector3.Zero();
  43888. this._scaledVelocity = BABYLON.Vector3.Zero();
  43889. this._finalPosition = BABYLON.Vector3.Zero();
  43890. }
  43891. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43892. position.divideToRef(collider.radius, this._scaledPosition);
  43893. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43894. collider.collidedMesh = null;
  43895. collider.retry = 0;
  43896. collider.initialVelocity = this._scaledVelocity;
  43897. collider.initialPosition = this._scaledPosition;
  43898. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  43899. this._finalPosition.multiplyInPlace(collider.radius);
  43900. //run the callback
  43901. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  43902. };
  43903. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  43904. this._scene = scene;
  43905. };
  43906. CollisionCoordinatorLegacy.prototype.destroy = function () {
  43907. //Legacy need no destruction method.
  43908. };
  43909. //No update in legacy mode
  43910. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  43911. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  43912. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  43913. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  43914. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  43915. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  43916. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  43917. if (excludedMesh === void 0) { excludedMesh = null; }
  43918. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  43919. if (collider.retry >= maximumRetry) {
  43920. finalPosition.copyFrom(position);
  43921. return;
  43922. }
  43923. // Check if this is a mesh else camera or -1
  43924. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  43925. collider._initialize(position, velocity, closeDistance);
  43926. // Check all meshes
  43927. for (var index = 0; index < this._scene.meshes.length; index++) {
  43928. var mesh = this._scene.meshes[index];
  43929. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  43930. mesh._checkCollision(collider);
  43931. }
  43932. }
  43933. if (!collider.collisionFound) {
  43934. position.addToRef(velocity, finalPosition);
  43935. return;
  43936. }
  43937. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  43938. collider._getResponse(position, velocity);
  43939. }
  43940. if (velocity.length() <= closeDistance) {
  43941. finalPosition.copyFrom(position);
  43942. return;
  43943. }
  43944. collider.retry++;
  43945. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  43946. };
  43947. return CollisionCoordinatorLegacy;
  43948. }());
  43949. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  43950. })(BABYLON || (BABYLON = {}));
  43951. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  43952. var BABYLON;
  43953. (function (BABYLON) {
  43954. var Particle = /** @class */ (function () {
  43955. function Particle(particleSystem) {
  43956. this.particleSystem = particleSystem;
  43957. this.position = BABYLON.Vector3.Zero();
  43958. this.direction = BABYLON.Vector3.Zero();
  43959. this.color = new BABYLON.Color4(0, 0, 0, 0);
  43960. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  43961. this.lifeTime = 1.0;
  43962. this.age = 0;
  43963. this.size = 0;
  43964. this.angle = 0;
  43965. this.angularSpeed = 0;
  43966. this._currentFrameCounter = 0;
  43967. this.cellIndex = 0;
  43968. if (!this.particleSystem.isAnimationSheetEnabled) {
  43969. return;
  43970. }
  43971. this.cellIndex = this.particleSystem.startSpriteCellID;
  43972. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  43973. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  43974. }
  43975. else {
  43976. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  43977. }
  43978. }
  43979. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  43980. // (ageOffset / scaledUpdateSpeed) / available cells
  43981. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  43982. this._currentFrameCounter += scaledUpdateSpeed;
  43983. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  43984. this._currentFrameCounter = 0;
  43985. this.cellIndex++;
  43986. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43987. this.cellIndex = this.particleSystem.endSpriteCellID;
  43988. }
  43989. }
  43990. };
  43991. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  43992. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  43993. this.cellIndex++;
  43994. this._currentFrameCounter = 0;
  43995. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43996. if (this.particleSystem.spriteCellLoop) {
  43997. this.cellIndex = this.particleSystem.startSpriteCellID;
  43998. }
  43999. else {
  44000. this.cellIndex = this.particleSystem.endSpriteCellID;
  44001. }
  44002. }
  44003. }
  44004. else {
  44005. this._currentFrameCounter++;
  44006. }
  44007. };
  44008. Particle.prototype.copyTo = function (other) {
  44009. other.position.copyFrom(this.position);
  44010. other.direction.copyFrom(this.direction);
  44011. other.color.copyFrom(this.color);
  44012. other.colorStep.copyFrom(this.colorStep);
  44013. other.lifeTime = this.lifeTime;
  44014. other.age = this.age;
  44015. other.size = this.size;
  44016. other.angle = this.angle;
  44017. other.angularSpeed = this.angularSpeed;
  44018. other.particleSystem = this.particleSystem;
  44019. other.cellIndex = this.cellIndex;
  44020. };
  44021. return Particle;
  44022. }());
  44023. BABYLON.Particle = Particle;
  44024. })(BABYLON || (BABYLON = {}));
  44025. //# sourceMappingURL=babylon.particle.js.map
  44026. var BABYLON;
  44027. (function (BABYLON) {
  44028. var randomNumber = function (min, max) {
  44029. if (min === max) {
  44030. return (min);
  44031. }
  44032. var random = Math.random();
  44033. return ((random * (max - min)) + min);
  44034. };
  44035. var ParticleSystem = /** @class */ (function () {
  44036. // end of sheet animation
  44037. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  44038. if (customEffect === void 0) { customEffect = null; }
  44039. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  44040. if (epsilon === void 0) { epsilon = 0.01; }
  44041. var _this = this;
  44042. this.name = name;
  44043. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  44044. // Members
  44045. this.animations = [];
  44046. this.renderingGroupId = 0;
  44047. this.emitter = null;
  44048. this.emitRate = 10;
  44049. this.manualEmitCount = -1;
  44050. this.updateSpeed = 0.01;
  44051. this.targetStopDuration = 0;
  44052. this.disposeOnStop = false;
  44053. this.minEmitPower = 1;
  44054. this.maxEmitPower = 1;
  44055. this.minLifeTime = 1;
  44056. this.maxLifeTime = 1;
  44057. this.minSize = 1;
  44058. this.maxSize = 1;
  44059. this.minAngularSpeed = 0;
  44060. this.maxAngularSpeed = 0;
  44061. this.layerMask = 0x0FFFFFFF;
  44062. this.customShader = null;
  44063. this.preventAutoStart = false;
  44064. /**
  44065. * An event triggered when the system is disposed.
  44066. * @type {BABYLON.Observable}
  44067. */
  44068. this.onDisposeObservable = new BABYLON.Observable();
  44069. this.onAnimationEnd = null;
  44070. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  44071. this.forceDepthWrite = false;
  44072. this.gravity = BABYLON.Vector3.Zero();
  44073. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  44074. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  44075. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  44076. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44077. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44078. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44079. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  44080. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44081. this.particles = new Array();
  44082. this._stockParticles = new Array();
  44083. this._newPartsExcess = 0;
  44084. this._vertexBuffers = {};
  44085. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44086. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44087. this._scaledDirection = BABYLON.Vector3.Zero();
  44088. this._scaledGravity = BABYLON.Vector3.Zero();
  44089. this._currentRenderId = -1;
  44090. this._started = false;
  44091. this._stopped = false;
  44092. this._actualFrame = 0;
  44093. // sheet animation
  44094. this.startSpriteCellID = 0;
  44095. this.endSpriteCellID = 0;
  44096. this.spriteCellLoop = true;
  44097. this.spriteCellChangeSpeed = 0;
  44098. this.spriteCellWidth = 0;
  44099. this.spriteCellHeight = 0;
  44100. this._vertexBufferSize = 11;
  44101. this.appendParticleVertexes = null;
  44102. this.id = name;
  44103. this._capacity = capacity;
  44104. this._epsilon = epsilon;
  44105. if (_isAnimationSheetEnabled) {
  44106. this._vertexBufferSize = 12;
  44107. }
  44108. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44109. this._customEffect = customEffect;
  44110. scene.particleSystems.push(this);
  44111. this._createIndexBuffer();
  44112. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44113. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44114. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44115. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44116. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44117. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44118. if (this._isAnimationSheetEnabled) {
  44119. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44120. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44121. }
  44122. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44123. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44124. this._vertexBuffers["options"] = options;
  44125. // Default behaviors
  44126. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44127. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44128. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44129. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44130. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44131. };
  44132. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44133. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44134. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44135. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44136. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44137. };
  44138. this.updateFunction = function (particles) {
  44139. for (var index = 0; index < particles.length; index++) {
  44140. var particle = particles[index];
  44141. particle.age += _this._scaledUpdateSpeed;
  44142. if (particle.age >= particle.lifeTime) {
  44143. _this.recycleParticle(particle);
  44144. index--;
  44145. continue;
  44146. }
  44147. else {
  44148. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44149. particle.color.addInPlace(_this._scaledColorStep);
  44150. if (particle.color.a < 0)
  44151. particle.color.a = 0;
  44152. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44153. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44154. particle.position.addInPlace(_this._scaledDirection);
  44155. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44156. particle.direction.addInPlace(_this._scaledGravity);
  44157. if (_this._isAnimationSheetEnabled) {
  44158. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44159. }
  44160. }
  44161. }
  44162. };
  44163. }
  44164. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44165. set: function (callback) {
  44166. if (this._onDisposeObserver) {
  44167. this.onDisposeObservable.remove(this._onDisposeObserver);
  44168. }
  44169. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44170. },
  44171. enumerable: true,
  44172. configurable: true
  44173. });
  44174. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44175. get: function () {
  44176. return this._isAnimationSheetEnabled;
  44177. },
  44178. enumerable: true,
  44179. configurable: true
  44180. });
  44181. ParticleSystem.prototype._createIndexBuffer = function () {
  44182. var indices = [];
  44183. var index = 0;
  44184. for (var count = 0; count < this._capacity; count++) {
  44185. indices.push(index);
  44186. indices.push(index + 1);
  44187. indices.push(index + 2);
  44188. indices.push(index);
  44189. indices.push(index + 2);
  44190. indices.push(index + 3);
  44191. index += 4;
  44192. }
  44193. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44194. };
  44195. ParticleSystem.prototype.recycleParticle = function (particle) {
  44196. var lastParticle = this.particles.pop();
  44197. if (lastParticle !== particle) {
  44198. lastParticle.copyTo(particle);
  44199. this._stockParticles.push(lastParticle);
  44200. }
  44201. };
  44202. ParticleSystem.prototype.getCapacity = function () {
  44203. return this._capacity;
  44204. };
  44205. ParticleSystem.prototype.isAlive = function () {
  44206. return this._alive;
  44207. };
  44208. ParticleSystem.prototype.isStarted = function () {
  44209. return this._started;
  44210. };
  44211. ParticleSystem.prototype.start = function () {
  44212. this._started = true;
  44213. this._stopped = false;
  44214. this._actualFrame = 0;
  44215. };
  44216. ParticleSystem.prototype.stop = function () {
  44217. this._stopped = true;
  44218. };
  44219. // animation sheet
  44220. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44221. var offset = index * this._vertexBufferSize;
  44222. this._vertexData[offset] = particle.position.x;
  44223. this._vertexData[offset + 1] = particle.position.y;
  44224. this._vertexData[offset + 2] = particle.position.z;
  44225. this._vertexData[offset + 3] = particle.color.r;
  44226. this._vertexData[offset + 4] = particle.color.g;
  44227. this._vertexData[offset + 5] = particle.color.b;
  44228. this._vertexData[offset + 6] = particle.color.a;
  44229. this._vertexData[offset + 7] = particle.angle;
  44230. this._vertexData[offset + 8] = particle.size;
  44231. this._vertexData[offset + 9] = offsetX;
  44232. this._vertexData[offset + 10] = offsetY;
  44233. };
  44234. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44235. if (offsetX === 0)
  44236. offsetX = this._epsilon;
  44237. else if (offsetX === 1)
  44238. offsetX = 1 - this._epsilon;
  44239. if (offsetY === 0)
  44240. offsetY = this._epsilon;
  44241. else if (offsetY === 1)
  44242. offsetY = 1 - this._epsilon;
  44243. var offset = index * this._vertexBufferSize;
  44244. this._vertexData[offset] = particle.position.x;
  44245. this._vertexData[offset + 1] = particle.position.y;
  44246. this._vertexData[offset + 2] = particle.position.z;
  44247. this._vertexData[offset + 3] = particle.color.r;
  44248. this._vertexData[offset + 4] = particle.color.g;
  44249. this._vertexData[offset + 5] = particle.color.b;
  44250. this._vertexData[offset + 6] = particle.color.a;
  44251. this._vertexData[offset + 7] = particle.angle;
  44252. this._vertexData[offset + 8] = particle.size;
  44253. this._vertexData[offset + 9] = offsetX;
  44254. this._vertexData[offset + 10] = offsetY;
  44255. this._vertexData[offset + 11] = particle.cellIndex;
  44256. };
  44257. ParticleSystem.prototype._update = function (newParticles) {
  44258. // Update current
  44259. this._alive = this.particles.length > 0;
  44260. this.updateFunction(this.particles);
  44261. // Add new ones
  44262. var worldMatrix;
  44263. if (this.emitter.position) {
  44264. var emitterMesh = this.emitter;
  44265. worldMatrix = emitterMesh.getWorldMatrix();
  44266. }
  44267. else {
  44268. var emitterPosition = this.emitter;
  44269. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44270. }
  44271. var particle;
  44272. for (var index = 0; index < newParticles; index++) {
  44273. if (this.particles.length === this._capacity) {
  44274. break;
  44275. }
  44276. if (this._stockParticles.length !== 0) {
  44277. particle = this._stockParticles.pop();
  44278. particle.age = 0;
  44279. particle.cellIndex = this.startSpriteCellID;
  44280. }
  44281. else {
  44282. particle = new BABYLON.Particle(this);
  44283. }
  44284. this.particles.push(particle);
  44285. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44286. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44287. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44288. particle.size = randomNumber(this.minSize, this.maxSize);
  44289. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44290. this.startPositionFunction(worldMatrix, particle.position, particle);
  44291. var step = randomNumber(0, 1.0);
  44292. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44293. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44294. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44295. }
  44296. };
  44297. ParticleSystem.prototype._getEffect = function () {
  44298. if (this._customEffect) {
  44299. return this._customEffect;
  44300. }
  44301. ;
  44302. var defines = [];
  44303. if (this._scene.clipPlane) {
  44304. defines.push("#define CLIPPLANE");
  44305. }
  44306. if (this._isAnimationSheetEnabled) {
  44307. defines.push("#define ANIMATESHEET");
  44308. }
  44309. // Effect
  44310. var join = defines.join("\n");
  44311. if (this._cachedDefines !== join) {
  44312. this._cachedDefines = join;
  44313. var attributesNamesOrOptions;
  44314. var effectCreationOption;
  44315. if (this._isAnimationSheetEnabled) {
  44316. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44317. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44318. }
  44319. else {
  44320. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44321. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44322. }
  44323. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44324. }
  44325. return this._effect;
  44326. };
  44327. ParticleSystem.prototype.animate = function () {
  44328. if (!this._started)
  44329. return;
  44330. var effect = this._getEffect();
  44331. // Check
  44332. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44333. return;
  44334. if (this._currentRenderId === this._scene.getRenderId()) {
  44335. return;
  44336. }
  44337. this._currentRenderId = this._scene.getRenderId();
  44338. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44339. // determine the number of particles we need to create
  44340. var newParticles;
  44341. if (this.manualEmitCount > -1) {
  44342. newParticles = this.manualEmitCount;
  44343. this._newPartsExcess = 0;
  44344. this.manualEmitCount = 0;
  44345. }
  44346. else {
  44347. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44348. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44349. }
  44350. if (this._newPartsExcess > 1.0) {
  44351. newParticles += this._newPartsExcess >> 0;
  44352. this._newPartsExcess -= this._newPartsExcess >> 0;
  44353. }
  44354. this._alive = false;
  44355. if (!this._stopped) {
  44356. this._actualFrame += this._scaledUpdateSpeed;
  44357. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44358. this.stop();
  44359. }
  44360. else {
  44361. newParticles = 0;
  44362. }
  44363. this._update(newParticles);
  44364. // Stopped?
  44365. if (this._stopped) {
  44366. if (!this._alive) {
  44367. this._started = false;
  44368. if (this.onAnimationEnd) {
  44369. this.onAnimationEnd();
  44370. }
  44371. if (this.disposeOnStop) {
  44372. this._scene._toBeDisposed.push(this);
  44373. }
  44374. }
  44375. }
  44376. // Animation sheet
  44377. if (this._isAnimationSheetEnabled) {
  44378. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44379. }
  44380. else {
  44381. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44382. }
  44383. // Update VBO
  44384. var offset = 0;
  44385. for (var index = 0; index < this.particles.length; index++) {
  44386. var particle = this.particles[index];
  44387. this.appendParticleVertexes(offset, particle);
  44388. offset += 4;
  44389. }
  44390. if (this._vertexBuffer) {
  44391. this._vertexBuffer.update(this._vertexData);
  44392. }
  44393. };
  44394. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44395. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44396. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44397. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44398. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44399. };
  44400. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44401. this._appendParticleVertex(offset++, particle, 0, 0);
  44402. this._appendParticleVertex(offset++, particle, 1, 0);
  44403. this._appendParticleVertex(offset++, particle, 1, 1);
  44404. this._appendParticleVertex(offset++, particle, 0, 1);
  44405. };
  44406. ParticleSystem.prototype.rebuild = function () {
  44407. this._createIndexBuffer();
  44408. if (this._vertexBuffer) {
  44409. this._vertexBuffer._rebuild();
  44410. }
  44411. };
  44412. ParticleSystem.prototype.render = function () {
  44413. var effect = this._getEffect();
  44414. // Check
  44415. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44416. return 0;
  44417. var engine = this._scene.getEngine();
  44418. // Render
  44419. engine.enableEffect(effect);
  44420. engine.setState(false);
  44421. var viewMatrix = this._scene.getViewMatrix();
  44422. effect.setTexture("diffuseSampler", this.particleTexture);
  44423. effect.setMatrix("view", viewMatrix);
  44424. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44425. if (this._isAnimationSheetEnabled) {
  44426. var baseSize = this.particleTexture.getBaseSize();
  44427. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44428. }
  44429. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44430. if (this._scene.clipPlane) {
  44431. var clipPlane = this._scene.clipPlane;
  44432. var invView = viewMatrix.clone();
  44433. invView.invert();
  44434. effect.setMatrix("invView", invView);
  44435. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44436. }
  44437. // VBOs
  44438. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44439. // Draw order
  44440. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44441. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44442. }
  44443. else {
  44444. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44445. }
  44446. if (this.forceDepthWrite) {
  44447. engine.setDepthWrite(true);
  44448. }
  44449. engine.draw(true, 0, this.particles.length * 6);
  44450. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44451. return this.particles.length;
  44452. };
  44453. ParticleSystem.prototype.dispose = function () {
  44454. if (this._vertexBuffer) {
  44455. this._vertexBuffer.dispose();
  44456. this._vertexBuffer = null;
  44457. }
  44458. if (this._indexBuffer) {
  44459. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44460. this._indexBuffer = null;
  44461. }
  44462. if (this.particleTexture) {
  44463. this.particleTexture.dispose();
  44464. this.particleTexture = null;
  44465. }
  44466. // Remove from scene
  44467. var index = this._scene.particleSystems.indexOf(this);
  44468. if (index > -1) {
  44469. this._scene.particleSystems.splice(index, 1);
  44470. }
  44471. // Callback
  44472. this.onDisposeObservable.notifyObservers(this);
  44473. this.onDisposeObservable.clear();
  44474. };
  44475. // Clone
  44476. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44477. var custom = null;
  44478. var program = null;
  44479. if (this.customShader != null) {
  44480. program = this.customShader;
  44481. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44482. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44483. }
  44484. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44485. result.customShader = program;
  44486. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44487. if (newEmitter === undefined) {
  44488. newEmitter = this.emitter;
  44489. }
  44490. result.emitter = newEmitter;
  44491. if (this.particleTexture) {
  44492. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44493. }
  44494. if (!this.preventAutoStart) {
  44495. result.start();
  44496. }
  44497. return result;
  44498. };
  44499. ParticleSystem.prototype.serialize = function () {
  44500. var serializationObject = {};
  44501. serializationObject.name = this.name;
  44502. serializationObject.id = this.id;
  44503. // Emitter
  44504. if (this.emitter.position) {
  44505. var emitterMesh = this.emitter;
  44506. serializationObject.emitterId = emitterMesh.id;
  44507. }
  44508. else {
  44509. var emitterPosition = this.emitter;
  44510. serializationObject.emitter = emitterPosition.asArray();
  44511. }
  44512. serializationObject.capacity = this.getCapacity();
  44513. if (this.particleTexture) {
  44514. serializationObject.textureName = this.particleTexture.name;
  44515. }
  44516. // Animations
  44517. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44518. // Particle system
  44519. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44520. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44521. serializationObject.minSize = this.minSize;
  44522. serializationObject.maxSize = this.maxSize;
  44523. serializationObject.minEmitPower = this.minEmitPower;
  44524. serializationObject.maxEmitPower = this.maxEmitPower;
  44525. serializationObject.minLifeTime = this.minLifeTime;
  44526. serializationObject.maxLifeTime = this.maxLifeTime;
  44527. serializationObject.emitRate = this.emitRate;
  44528. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44529. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44530. serializationObject.gravity = this.gravity.asArray();
  44531. serializationObject.direction1 = this.direction1.asArray();
  44532. serializationObject.direction2 = this.direction2.asArray();
  44533. serializationObject.color1 = this.color1.asArray();
  44534. serializationObject.color2 = this.color2.asArray();
  44535. serializationObject.colorDead = this.colorDead.asArray();
  44536. serializationObject.updateSpeed = this.updateSpeed;
  44537. serializationObject.targetStopDuration = this.targetStopDuration;
  44538. serializationObject.textureMask = this.textureMask.asArray();
  44539. serializationObject.blendMode = this.blendMode;
  44540. serializationObject.customShader = this.customShader;
  44541. serializationObject.preventAutoStart = this.preventAutoStart;
  44542. return serializationObject;
  44543. };
  44544. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44545. var name = parsedParticleSystem.name;
  44546. var custom = null;
  44547. var program = null;
  44548. if (parsedParticleSystem.customShader) {
  44549. program = parsedParticleSystem.customShader;
  44550. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44551. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44552. }
  44553. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44554. particleSystem.customShader = program;
  44555. if (parsedParticleSystem.id) {
  44556. particleSystem.id = parsedParticleSystem.id;
  44557. }
  44558. // Auto start
  44559. if (parsedParticleSystem.preventAutoStart) {
  44560. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44561. }
  44562. // Texture
  44563. if (parsedParticleSystem.textureName) {
  44564. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  44565. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  44566. }
  44567. // Emitter
  44568. if (parsedParticleSystem.emitterId) {
  44569. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  44570. }
  44571. else {
  44572. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  44573. }
  44574. // Animations
  44575. if (parsedParticleSystem.animations) {
  44576. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  44577. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  44578. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44579. }
  44580. }
  44581. if (parsedParticleSystem.autoAnimate) {
  44582. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  44583. }
  44584. // Particle system
  44585. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  44586. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  44587. particleSystem.minSize = parsedParticleSystem.minSize;
  44588. particleSystem.maxSize = parsedParticleSystem.maxSize;
  44589. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  44590. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  44591. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  44592. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  44593. particleSystem.emitRate = parsedParticleSystem.emitRate;
  44594. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  44595. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  44596. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  44597. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  44598. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  44599. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  44600. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  44601. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  44602. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  44603. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  44604. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  44605. particleSystem.blendMode = parsedParticleSystem.blendMode;
  44606. if (!particleSystem.preventAutoStart) {
  44607. particleSystem.start();
  44608. }
  44609. return particleSystem;
  44610. };
  44611. // Statics
  44612. ParticleSystem.BLENDMODE_ONEONE = 0;
  44613. ParticleSystem.BLENDMODE_STANDARD = 1;
  44614. return ParticleSystem;
  44615. }());
  44616. BABYLON.ParticleSystem = ParticleSystem;
  44617. })(BABYLON || (BABYLON = {}));
  44618. //# sourceMappingURL=babylon.particleSystem.js.map
  44619. var BABYLON;
  44620. (function (BABYLON) {
  44621. var SolidParticle = /** @class */ (function () {
  44622. /**
  44623. * Creates a Solid Particle object.
  44624. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  44625. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  44626. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  44627. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  44628. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  44629. * `shapeId` (integer) is the model shape identifier in the SPS.
  44630. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  44631. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  44632. */
  44633. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  44634. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  44635. this.idx = 0; // particle global index
  44636. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  44637. this.position = BABYLON.Vector3.Zero(); // position
  44638. this.rotation = BABYLON.Vector3.Zero(); // rotation
  44639. this.scaling = BABYLON.Vector3.One(); // scaling
  44640. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  44641. this.velocity = BABYLON.Vector3.Zero(); // velocity
  44642. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  44643. this.alive = true; // alive
  44644. this.isVisible = true; // visibility
  44645. this._pos = 0; // index of this particle in the global "positions" array
  44646. this._ind = 0; // index of this particle in the global "indices" array
  44647. this.shapeId = 0; // model shape id
  44648. this.idxInShape = 0; // index of the particle in its shape id
  44649. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  44650. this.idx = particleIndex;
  44651. this._pos = positionIndex;
  44652. this._ind = indiceIndex;
  44653. this._model = model;
  44654. this.shapeId = shapeId;
  44655. this.idxInShape = idxInShape;
  44656. this._sps = sps;
  44657. if (modelBoundingInfo) {
  44658. this._modelBoundingInfo = modelBoundingInfo;
  44659. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  44660. }
  44661. }
  44662. Object.defineProperty(SolidParticle.prototype, "scale", {
  44663. /**
  44664. * legacy support, changed scale to scaling
  44665. */
  44666. get: function () {
  44667. return this.scaling;
  44668. },
  44669. set: function (scale) {
  44670. this.scaling = scale;
  44671. },
  44672. enumerable: true,
  44673. configurable: true
  44674. });
  44675. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  44676. /**
  44677. * legacy support, changed quaternion to rotationQuaternion
  44678. */
  44679. get: function () {
  44680. return this.rotationQuaternion;
  44681. },
  44682. set: function (q) {
  44683. this.rotationQuaternion = q;
  44684. },
  44685. enumerable: true,
  44686. configurable: true
  44687. });
  44688. /**
  44689. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  44690. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  44691. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  44692. */
  44693. SolidParticle.prototype.intersectsMesh = function (target) {
  44694. if (!this._boundingInfo || !target._boundingInfo) {
  44695. return false;
  44696. }
  44697. if (this._sps._bSphereOnly) {
  44698. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  44699. }
  44700. return this._boundingInfo.intersects(target._boundingInfo, false);
  44701. };
  44702. return SolidParticle;
  44703. }());
  44704. BABYLON.SolidParticle = SolidParticle;
  44705. var ModelShape = /** @class */ (function () {
  44706. /**
  44707. * 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.
  44708. * SPS internal tool, don't use it manually.
  44709. */
  44710. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  44711. this._indicesLength = 0; // length of the shape in the model indices array
  44712. this.shapeID = id;
  44713. this._shape = shape;
  44714. this._indicesLength = indicesLength;
  44715. this._shapeUV = shapeUV;
  44716. this._positionFunction = posFunction;
  44717. this._vertexFunction = vtxFunction;
  44718. }
  44719. return ModelShape;
  44720. }());
  44721. BABYLON.ModelShape = ModelShape;
  44722. var DepthSortedParticle = /** @class */ (function () {
  44723. function DepthSortedParticle() {
  44724. this.ind = 0; // index of the particle in the "indices" array
  44725. this.indicesLength = 0; // length of the particle shape in the "indices" array
  44726. this.sqDistance = 0.0; // squared distance from the particle to the camera
  44727. }
  44728. return DepthSortedParticle;
  44729. }());
  44730. BABYLON.DepthSortedParticle = DepthSortedParticle;
  44731. })(BABYLON || (BABYLON = {}));
  44732. //# sourceMappingURL=babylon.solidParticle.js.map
  44733. var BABYLON;
  44734. (function (BABYLON) {
  44735. /**
  44736. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  44737. */
  44738. var SolidParticleSystem = /** @class */ (function () {
  44739. /**
  44740. * Creates a SPS (Solid Particle System) object.
  44741. * `name` (String) is the SPS name, this will be the underlying mesh name.
  44742. * `scene` (Scene) is the scene in which the SPS is added.
  44743. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  44744. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  44745. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  44746. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  44747. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  44748. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  44749. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  44750. */
  44751. function SolidParticleSystem(name, scene, options) {
  44752. // public members
  44753. /**
  44754. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  44755. * Example : var p = SPS.particles[i];
  44756. */
  44757. this.particles = new Array();
  44758. /**
  44759. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  44760. */
  44761. this.nbParticles = 0;
  44762. /**
  44763. * If the particles must ever face the camera (default false). Useful for planar particles.
  44764. */
  44765. this.billboard = false;
  44766. /**
  44767. * Recompute normals when adding a shape
  44768. */
  44769. this.recomputeNormals = true;
  44770. /**
  44771. * This a counter ofr your own usage. It's not set by any SPS functions.
  44772. */
  44773. this.counter = 0;
  44774. /**
  44775. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  44776. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  44777. */
  44778. this.vars = {};
  44779. this._positions = new Array();
  44780. this._indices = new Array();
  44781. this._normals = new Array();
  44782. this._colors = new Array();
  44783. this._uvs = new Array();
  44784. this._index = 0; // indices index
  44785. this._updatable = true;
  44786. this._pickable = false;
  44787. this._isVisibilityBoxLocked = false;
  44788. this._alwaysVisible = false;
  44789. this._depthSort = false;
  44790. this._shapeCounter = 0;
  44791. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  44792. this._color = new BABYLON.Color4(0, 0, 0, 0);
  44793. this._computeParticleColor = true;
  44794. this._computeParticleTexture = true;
  44795. this._computeParticleRotation = true;
  44796. this._computeParticleVertex = false;
  44797. this._computeBoundingBox = false;
  44798. this._depthSortParticles = true;
  44799. this._cam_axisZ = BABYLON.Vector3.Zero();
  44800. this._cam_axisY = BABYLON.Vector3.Zero();
  44801. this._cam_axisX = BABYLON.Vector3.Zero();
  44802. this._axisZ = BABYLON.Axis.Z;
  44803. this._camDir = BABYLON.Vector3.Zero();
  44804. this._camInvertedPosition = BABYLON.Vector3.Zero();
  44805. this._rotMatrix = new BABYLON.Matrix();
  44806. this._invertMatrix = new BABYLON.Matrix();
  44807. this._rotated = BABYLON.Vector3.Zero();
  44808. this._quaternion = new BABYLON.Quaternion();
  44809. this._vertex = BABYLON.Vector3.Zero();
  44810. this._normal = BABYLON.Vector3.Zero();
  44811. this._yaw = 0.0;
  44812. this._pitch = 0.0;
  44813. this._roll = 0.0;
  44814. this._halfroll = 0.0;
  44815. this._halfpitch = 0.0;
  44816. this._halfyaw = 0.0;
  44817. this._sinRoll = 0.0;
  44818. this._cosRoll = 0.0;
  44819. this._sinPitch = 0.0;
  44820. this._cosPitch = 0.0;
  44821. this._sinYaw = 0.0;
  44822. this._cosYaw = 0.0;
  44823. this._mustUnrotateFixedNormals = false;
  44824. this._minimum = BABYLON.Tmp.Vector3[0];
  44825. this._maximum = BABYLON.Tmp.Vector3[1];
  44826. this._minBbox = BABYLON.Tmp.Vector3[4];
  44827. this._maxBbox = BABYLON.Tmp.Vector3[5];
  44828. this._particlesIntersect = false;
  44829. this._depthSortFunction = function (p1, p2) {
  44830. return (p2.sqDistance - p1.sqDistance);
  44831. };
  44832. this._needs32Bits = false;
  44833. this._bSphereOnly = false;
  44834. this._bSphereRadiusFactor = 1.0;
  44835. this.name = name;
  44836. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44837. this._camera = scene.activeCamera;
  44838. this._pickable = options ? options.isPickable : false;
  44839. this._depthSort = options ? options.enableDepthSort : false;
  44840. this._particlesIntersect = options ? options.particleIntersection : false;
  44841. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  44842. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  44843. if (options && options.updatable) {
  44844. this._updatable = options.updatable;
  44845. }
  44846. else {
  44847. this._updatable = true;
  44848. }
  44849. if (this._pickable) {
  44850. this.pickedParticles = [];
  44851. }
  44852. if (this._depthSort) {
  44853. this.depthSortedParticles = [];
  44854. }
  44855. }
  44856. /**
  44857. * Builds the SPS underlying mesh. Returns a standard Mesh.
  44858. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  44859. */
  44860. SolidParticleSystem.prototype.buildMesh = function () {
  44861. if (this.nbParticles === 0) {
  44862. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  44863. this.addShape(triangle, 1);
  44864. triangle.dispose();
  44865. }
  44866. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  44867. this._positions32 = new Float32Array(this._positions);
  44868. this._uvs32 = new Float32Array(this._uvs);
  44869. this._colors32 = new Float32Array(this._colors);
  44870. if (this.recomputeNormals) {
  44871. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  44872. }
  44873. this._normals32 = new Float32Array(this._normals);
  44874. this._fixedNormal32 = new Float32Array(this._normals);
  44875. if (this._mustUnrotateFixedNormals) {
  44876. this._unrotateFixedNormals();
  44877. }
  44878. var vertexData = new BABYLON.VertexData();
  44879. vertexData.indices = this._indices32;
  44880. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  44881. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  44882. if (this._uvs32) {
  44883. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  44884. ;
  44885. }
  44886. if (this._colors32) {
  44887. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  44888. }
  44889. var mesh = new BABYLON.Mesh(this.name, this._scene);
  44890. vertexData.applyToMesh(mesh, this._updatable);
  44891. this.mesh = mesh;
  44892. this.mesh.isPickable = this._pickable;
  44893. // free memory
  44894. if (!this._depthSort) {
  44895. this._indices = null;
  44896. }
  44897. this._positions = null;
  44898. this._normals = null;
  44899. this._uvs = null;
  44900. this._colors = null;
  44901. if (!this._updatable) {
  44902. this.particles.length = 0;
  44903. }
  44904. return mesh;
  44905. };
  44906. /**
  44907. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  44908. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  44909. * Thus the particles generated from `digest()` have their property `position` set yet.
  44910. * `mesh` ( Mesh ) is the mesh to be digested
  44911. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  44912. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  44913. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  44914. */
  44915. SolidParticleSystem.prototype.digest = function (mesh, options) {
  44916. var size = (options && options.facetNb) || 1;
  44917. var number = (options && options.number) || 0;
  44918. var delta = (options && options.delta) || 0;
  44919. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44920. var meshInd = mesh.getIndices();
  44921. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44922. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44923. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44924. var f = 0; // facet counter
  44925. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  44926. // compute size from number
  44927. if (number) {
  44928. number = (number > totalFacets) ? totalFacets : number;
  44929. size = Math.round(totalFacets / number);
  44930. delta = 0;
  44931. }
  44932. else {
  44933. size = (size > totalFacets) ? totalFacets : size;
  44934. }
  44935. var facetPos = []; // submesh positions
  44936. var facetInd = []; // submesh indices
  44937. var facetUV = []; // submesh UV
  44938. var facetCol = []; // submesh colors
  44939. var barycenter = BABYLON.Tmp.Vector3[0];
  44940. var sizeO = size;
  44941. while (f < totalFacets) {
  44942. size = sizeO + Math.floor((1 + delta) * Math.random());
  44943. if (f > totalFacets - size) {
  44944. size = totalFacets - f;
  44945. }
  44946. // reset temp arrays
  44947. facetPos.length = 0;
  44948. facetInd.length = 0;
  44949. facetUV.length = 0;
  44950. facetCol.length = 0;
  44951. // iterate over "size" facets
  44952. var fi = 0;
  44953. for (var j = f * 3; j < (f + size) * 3; j++) {
  44954. facetInd.push(fi);
  44955. var i = meshInd[j];
  44956. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  44957. if (meshUV) {
  44958. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  44959. }
  44960. if (meshCol) {
  44961. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  44962. }
  44963. fi++;
  44964. }
  44965. // create a model shape for each single particle
  44966. var idx = this.nbParticles;
  44967. var shape = this._posToShape(facetPos);
  44968. var shapeUV = this._uvsToShapeUV(facetUV);
  44969. // compute the barycenter of the shape
  44970. var v;
  44971. for (v = 0; v < shape.length; v++) {
  44972. barycenter.addInPlace(shape[v]);
  44973. }
  44974. barycenter.scaleInPlace(1 / shape.length);
  44975. // shift the shape from its barycenter to the origin
  44976. for (v = 0; v < shape.length; v++) {
  44977. shape[v].subtractInPlace(barycenter);
  44978. }
  44979. var bInfo;
  44980. if (this._particlesIntersect) {
  44981. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  44982. }
  44983. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  44984. // add the particle in the SPS
  44985. var currentPos = this._positions.length;
  44986. var currentInd = this._indices.length;
  44987. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  44988. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  44989. // initialize the particle position
  44990. this.particles[this.nbParticles].position.addInPlace(barycenter);
  44991. this._index += shape.length;
  44992. idx++;
  44993. this.nbParticles++;
  44994. this._shapeCounter++;
  44995. f += size;
  44996. }
  44997. return this;
  44998. };
  44999. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  45000. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  45001. var index = 0;
  45002. var idx = 0;
  45003. for (var p = 0; p < this.particles.length; p++) {
  45004. this._particle = this.particles[p];
  45005. this._shape = this._particle._model._shape;
  45006. if (this._particle.rotationQuaternion) {
  45007. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45008. }
  45009. else {
  45010. this._yaw = this._particle.rotation.y;
  45011. this._pitch = this._particle.rotation.x;
  45012. this._roll = this._particle.rotation.z;
  45013. this._quaternionRotationYPR();
  45014. }
  45015. this._quaternionToRotationMatrix();
  45016. this._rotMatrix.invertToRef(this._invertMatrix);
  45017. for (var pt = 0; pt < this._shape.length; pt++) {
  45018. idx = index + pt * 3;
  45019. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  45020. this._fixedNormal32[idx] = this._normal.x;
  45021. this._fixedNormal32[idx + 1] = this._normal.y;
  45022. this._fixedNormal32[idx + 2] = this._normal.z;
  45023. }
  45024. index = idx + 3;
  45025. }
  45026. };
  45027. //reset copy
  45028. SolidParticleSystem.prototype._resetCopy = function () {
  45029. this._copy.position.x = 0;
  45030. this._copy.position.y = 0;
  45031. this._copy.position.z = 0;
  45032. this._copy.rotation.x = 0;
  45033. this._copy.rotation.y = 0;
  45034. this._copy.rotation.z = 0;
  45035. this._copy.rotationQuaternion = null;
  45036. this._copy.scaling.x = 1.0;
  45037. this._copy.scaling.y = 1.0;
  45038. this._copy.scaling.z = 1.0;
  45039. this._copy.uvs.x = 0;
  45040. this._copy.uvs.y = 0;
  45041. this._copy.uvs.z = 1.0;
  45042. this._copy.uvs.w = 1.0;
  45043. this._copy.color = null;
  45044. };
  45045. // _meshBuilder : inserts the shape model in the global SPS mesh
  45046. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  45047. var i;
  45048. var u = 0;
  45049. var c = 0;
  45050. var n = 0;
  45051. this._resetCopy();
  45052. if (options && options.positionFunction) {
  45053. options.positionFunction(this._copy, idx, idxInShape);
  45054. this._mustUnrotateFixedNormals = true;
  45055. }
  45056. if (this._copy.rotationQuaternion) {
  45057. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45058. }
  45059. else {
  45060. this._yaw = this._copy.rotation.y;
  45061. this._pitch = this._copy.rotation.x;
  45062. this._roll = this._copy.rotation.z;
  45063. this._quaternionRotationYPR();
  45064. }
  45065. this._quaternionToRotationMatrix();
  45066. for (i = 0; i < shape.length; i++) {
  45067. this._vertex.x = shape[i].x;
  45068. this._vertex.y = shape[i].y;
  45069. this._vertex.z = shape[i].z;
  45070. if (options && options.vertexFunction) {
  45071. options.vertexFunction(this._copy, this._vertex, i);
  45072. }
  45073. this._vertex.x *= this._copy.scaling.x;
  45074. this._vertex.y *= this._copy.scaling.y;
  45075. this._vertex.z *= this._copy.scaling.z;
  45076. this._vertex.x += this._copy.pivot.x;
  45077. this._vertex.y += this._copy.pivot.y;
  45078. this._vertex.z += this._copy.pivot.z;
  45079. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45080. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  45081. if (meshUV) {
  45082. 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);
  45083. u += 2;
  45084. }
  45085. if (this._copy.color) {
  45086. this._color = this._copy.color;
  45087. }
  45088. else if (meshCol && meshCol[c] !== undefined) {
  45089. this._color.r = meshCol[c];
  45090. this._color.g = meshCol[c + 1];
  45091. this._color.b = meshCol[c + 2];
  45092. this._color.a = meshCol[c + 3];
  45093. }
  45094. else {
  45095. this._color.r = 1.0;
  45096. this._color.g = 1.0;
  45097. this._color.b = 1.0;
  45098. this._color.a = 1.0;
  45099. }
  45100. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45101. c += 4;
  45102. if (!this.recomputeNormals && meshNor) {
  45103. this._normal.x = meshNor[n];
  45104. this._normal.y = meshNor[n + 1];
  45105. this._normal.z = meshNor[n + 2];
  45106. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45107. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45108. n += 3;
  45109. }
  45110. }
  45111. for (i = 0; i < meshInd.length; i++) {
  45112. var current_ind = p + meshInd[i];
  45113. indices.push(current_ind);
  45114. if (current_ind > 65535) {
  45115. this._needs32Bits = true;
  45116. }
  45117. }
  45118. if (this._pickable) {
  45119. var nbfaces = meshInd.length / 3;
  45120. for (i = 0; i < nbfaces; i++) {
  45121. this.pickedParticles.push({ idx: idx, faceId: i });
  45122. }
  45123. }
  45124. if (this._depthSort) {
  45125. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45126. }
  45127. return this._copy;
  45128. };
  45129. // returns a shape array from positions array
  45130. SolidParticleSystem.prototype._posToShape = function (positions) {
  45131. var shape = [];
  45132. for (var i = 0; i < positions.length; i += 3) {
  45133. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45134. }
  45135. return shape;
  45136. };
  45137. // returns a shapeUV array from a Vector4 uvs
  45138. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45139. var shapeUV = [];
  45140. if (uvs) {
  45141. for (var i = 0; i < uvs.length; i++)
  45142. shapeUV.push(uvs[i]);
  45143. }
  45144. return shapeUV;
  45145. };
  45146. // adds a new particle object in the particles array
  45147. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45148. if (bInfo === void 0) { bInfo = null; }
  45149. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45150. this.particles.push(sp);
  45151. return sp;
  45152. };
  45153. /**
  45154. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45155. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45156. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45157. * `nb` (positive integer) the number of particles to be created from this model
  45158. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45159. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  45160. */
  45161. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  45162. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45163. var meshInd = mesh.getIndices();
  45164. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45165. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45166. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45167. var bbInfo;
  45168. if (this._particlesIntersect) {
  45169. bbInfo = mesh.getBoundingInfo();
  45170. }
  45171. var shape = this._posToShape(meshPos);
  45172. var shapeUV = this._uvsToShapeUV(meshUV);
  45173. var posfunc = options ? options.positionFunction : null;
  45174. var vtxfunc = options ? options.vertexFunction : null;
  45175. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45176. // particles
  45177. var sp;
  45178. var currentCopy;
  45179. var idx = this.nbParticles;
  45180. for (var i = 0; i < nb; i++) {
  45181. var currentPos = this._positions.length;
  45182. var currentInd = this._indices.length;
  45183. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45184. if (this._updatable) {
  45185. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45186. sp.position.copyFrom(currentCopy.position);
  45187. sp.rotation.copyFrom(currentCopy.rotation);
  45188. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45189. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45190. }
  45191. if (currentCopy.color && sp.color) {
  45192. sp.color.copyFrom(currentCopy.color);
  45193. }
  45194. sp.scaling.copyFrom(currentCopy.scaling);
  45195. sp.uvs.copyFrom(currentCopy.uvs);
  45196. }
  45197. this._index += shape.length;
  45198. idx++;
  45199. }
  45200. this.nbParticles += nb;
  45201. this._shapeCounter++;
  45202. return this._shapeCounter - 1;
  45203. };
  45204. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45205. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45206. this._resetCopy();
  45207. if (particle._model._positionFunction) {
  45208. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45209. }
  45210. if (this._copy.rotationQuaternion) {
  45211. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45212. }
  45213. else {
  45214. this._yaw = this._copy.rotation.y;
  45215. this._pitch = this._copy.rotation.x;
  45216. this._roll = this._copy.rotation.z;
  45217. this._quaternionRotationYPR();
  45218. }
  45219. this._quaternionToRotationMatrix();
  45220. this._shape = particle._model._shape;
  45221. for (var pt = 0; pt < this._shape.length; pt++) {
  45222. this._vertex.x = this._shape[pt].x;
  45223. this._vertex.y = this._shape[pt].y;
  45224. this._vertex.z = this._shape[pt].z;
  45225. if (particle._model._vertexFunction) {
  45226. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45227. }
  45228. this._vertex.x *= this._copy.scaling.x;
  45229. this._vertex.y *= this._copy.scaling.y;
  45230. this._vertex.z *= this._copy.scaling.z;
  45231. this._vertex.x += this._copy.pivot.x;
  45232. this._vertex.y += this._copy.pivot.y;
  45233. this._vertex.z += this._copy.pivot.z;
  45234. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45235. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45236. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45237. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45238. }
  45239. particle.position.x = 0.0;
  45240. particle.position.y = 0.0;
  45241. particle.position.z = 0.0;
  45242. particle.rotation.x = 0.0;
  45243. particle.rotation.y = 0.0;
  45244. particle.rotation.z = 0.0;
  45245. particle.rotationQuaternion = null;
  45246. particle.scaling.x = 1.0;
  45247. particle.scaling.y = 1.0;
  45248. particle.scaling.z = 1.0;
  45249. };
  45250. /**
  45251. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45252. * Returns the SPS.
  45253. */
  45254. SolidParticleSystem.prototype.rebuildMesh = function () {
  45255. for (var p = 0; p < this.particles.length; p++) {
  45256. this._rebuildParticle(this.particles[p]);
  45257. }
  45258. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45259. return this;
  45260. };
  45261. /**
  45262. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45263. * This method calls `updateParticle()` for each particle of the SPS.
  45264. * For an animated SPS, it is usually called within the render loop.
  45265. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45266. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45267. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45268. * Returns the SPS.
  45269. */
  45270. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45271. if (start === void 0) { start = 0; }
  45272. if (end === void 0) { end = this.nbParticles - 1; }
  45273. if (update === void 0) { update = true; }
  45274. if (!this._updatable) {
  45275. return this;
  45276. }
  45277. // custom beforeUpdate
  45278. this.beforeUpdateParticles(start, end, update);
  45279. this._cam_axisX.x = 1.0;
  45280. this._cam_axisX.y = 0.0;
  45281. this._cam_axisX.z = 0.0;
  45282. this._cam_axisY.x = 0.0;
  45283. this._cam_axisY.y = 1.0;
  45284. this._cam_axisY.z = 0.0;
  45285. this._cam_axisZ.x = 0.0;
  45286. this._cam_axisZ.y = 0.0;
  45287. this._cam_axisZ.z = 1.0;
  45288. // cases when the World Matrix is to be computed first
  45289. if (this.billboard || this._depthSort) {
  45290. this.mesh.computeWorldMatrix(true);
  45291. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45292. }
  45293. // if the particles will always face the camera
  45294. if (this.billboard) {
  45295. // compute the camera position and un-rotate it by the current mesh rotation
  45296. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45297. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45298. this._cam_axisZ.normalize();
  45299. // same for camera up vector extracted from the cam view matrix
  45300. var view = this._camera.getViewMatrix(true);
  45301. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45302. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45303. this._cam_axisY.normalize();
  45304. this._cam_axisX.normalize();
  45305. }
  45306. // if depthSort, compute the camera global position in the mesh local system
  45307. if (this._depthSort) {
  45308. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45309. }
  45310. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45311. var idx = 0; // current position index in the global array positions32
  45312. var index = 0; // position start index in the global array positions32 of the current particle
  45313. var colidx = 0; // current color index in the global array colors32
  45314. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45315. var uvidx = 0; // current uv index in the global array uvs32
  45316. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45317. var pt = 0; // current index in the particle model shape
  45318. if (this.mesh.isFacetDataEnabled) {
  45319. this._computeBoundingBox = true;
  45320. }
  45321. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45322. if (this._computeBoundingBox) {
  45323. if (start == 0 && end == this.nbParticles - 1) {
  45324. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45325. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45326. }
  45327. else {
  45328. if (this.mesh._boundingInfo) {
  45329. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45330. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45331. }
  45332. }
  45333. }
  45334. // particle loop
  45335. index = this.particles[start]._pos;
  45336. var vpos = (index / 3) | 0;
  45337. colorIndex = vpos * 4;
  45338. uvIndex = vpos * 2;
  45339. for (var p = start; p <= end; p++) {
  45340. this._particle = this.particles[p];
  45341. this._shape = this._particle._model._shape;
  45342. this._shapeUV = this._particle._model._shapeUV;
  45343. // call to custom user function to update the particle properties
  45344. this.updateParticle(this._particle);
  45345. // camera-particle distance for depth sorting
  45346. if (this._depthSort && this._depthSortParticles) {
  45347. var dsp = this.depthSortedParticles[p];
  45348. dsp.ind = this._particle._ind;
  45349. dsp.indicesLength = this._particle._model._indicesLength;
  45350. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45351. }
  45352. // skip the computations for inactive or already invisible particles
  45353. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45354. // increment indexes for the next particle
  45355. pt = this._shape.length;
  45356. index += pt * 3;
  45357. colorIndex += pt * 4;
  45358. uvIndex += pt * 2;
  45359. continue;
  45360. }
  45361. if (this._particle.isVisible) {
  45362. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45363. // particle rotation matrix
  45364. if (this.billboard) {
  45365. this._particle.rotation.x = 0.0;
  45366. this._particle.rotation.y = 0.0;
  45367. }
  45368. if (this._computeParticleRotation || this.billboard) {
  45369. if (this._particle.rotationQuaternion) {
  45370. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45371. }
  45372. else {
  45373. this._yaw = this._particle.rotation.y;
  45374. this._pitch = this._particle.rotation.x;
  45375. this._roll = this._particle.rotation.z;
  45376. this._quaternionRotationYPR();
  45377. }
  45378. this._quaternionToRotationMatrix();
  45379. }
  45380. // particle vertex loop
  45381. for (pt = 0; pt < this._shape.length; pt++) {
  45382. idx = index + pt * 3;
  45383. colidx = colorIndex + pt * 4;
  45384. uvidx = uvIndex + pt * 2;
  45385. this._vertex.x = this._shape[pt].x;
  45386. this._vertex.y = this._shape[pt].y;
  45387. this._vertex.z = this._shape[pt].z;
  45388. if (this._computeParticleVertex) {
  45389. this.updateParticleVertex(this._particle, this._vertex, pt);
  45390. }
  45391. // positions
  45392. this._vertex.x *= this._particle.scaling.x;
  45393. this._vertex.y *= this._particle.scaling.y;
  45394. this._vertex.z *= this._particle.scaling.z;
  45395. this._vertex.x += this._particle.pivot.x;
  45396. this._vertex.y += this._particle.pivot.y;
  45397. this._vertex.z += this._particle.pivot.z;
  45398. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45399. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45400. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45401. 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;
  45402. 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;
  45403. 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;
  45404. if (this._computeBoundingBox) {
  45405. if (this._positions32[idx] < this._minimum.x) {
  45406. this._minimum.x = this._positions32[idx];
  45407. }
  45408. if (this._positions32[idx] > this._maximum.x) {
  45409. this._maximum.x = this._positions32[idx];
  45410. }
  45411. if (this._positions32[idx + 1] < this._minimum.y) {
  45412. this._minimum.y = this._positions32[idx + 1];
  45413. }
  45414. if (this._positions32[idx + 1] > this._maximum.y) {
  45415. this._maximum.y = this._positions32[idx + 1];
  45416. }
  45417. if (this._positions32[idx + 2] < this._minimum.z) {
  45418. this._minimum.z = this._positions32[idx + 2];
  45419. }
  45420. if (this._positions32[idx + 2] > this._maximum.z) {
  45421. this._maximum.z = this._positions32[idx + 2];
  45422. }
  45423. }
  45424. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45425. if (!this._computeParticleVertex) {
  45426. this._normal.x = this._fixedNormal32[idx];
  45427. this._normal.y = this._fixedNormal32[idx + 1];
  45428. this._normal.z = this._fixedNormal32[idx + 2];
  45429. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45430. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45431. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45432. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45433. 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;
  45434. 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;
  45435. }
  45436. if (this._computeParticleColor && this._particle.color) {
  45437. this._colors32[colidx] = this._particle.color.r;
  45438. this._colors32[colidx + 1] = this._particle.color.g;
  45439. this._colors32[colidx + 2] = this._particle.color.b;
  45440. this._colors32[colidx + 3] = this._particle.color.a;
  45441. }
  45442. if (this._computeParticleTexture) {
  45443. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45444. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45445. }
  45446. }
  45447. }
  45448. else {
  45449. this._particle._stillInvisible = true; // mark the particle as invisible
  45450. for (pt = 0; pt < this._shape.length; pt++) {
  45451. idx = index + pt * 3;
  45452. colidx = colorIndex + pt * 4;
  45453. uvidx = uvIndex + pt * 2;
  45454. this._positions32[idx] = 0.0;
  45455. this._positions32[idx + 1] = 0.0;
  45456. this._positions32[idx + 2] = 0.0;
  45457. this._normals32[idx] = 0.0;
  45458. this._normals32[idx + 1] = 0.0;
  45459. this._normals32[idx + 2] = 0.0;
  45460. if (this._computeParticleColor && this._particle.color) {
  45461. this._colors32[colidx] = this._particle.color.r;
  45462. this._colors32[colidx + 1] = this._particle.color.g;
  45463. this._colors32[colidx + 2] = this._particle.color.b;
  45464. this._colors32[colidx + 3] = this._particle.color.a;
  45465. }
  45466. if (this._computeParticleTexture) {
  45467. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45468. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45469. }
  45470. }
  45471. }
  45472. // if the particle intersections must be computed : update the bbInfo
  45473. if (this._particlesIntersect) {
  45474. var bInfo = this._particle._boundingInfo;
  45475. var bBox = bInfo.boundingBox;
  45476. var bSphere = bInfo.boundingSphere;
  45477. if (!this._bSphereOnly) {
  45478. // place, scale and rotate the particle bbox within the SPS local system, then update it
  45479. for (var b = 0; b < bBox.vectors.length; b++) {
  45480. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  45481. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  45482. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  45483. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45484. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45485. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45486. 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;
  45487. 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;
  45488. 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;
  45489. }
  45490. bBox._update(this.mesh._worldMatrix);
  45491. }
  45492. // place and scale the particle bouding sphere in the SPS local system, then update it
  45493. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  45494. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  45495. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  45496. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  45497. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  45498. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  45499. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  45500. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  45501. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  45502. 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));
  45503. bSphere._update(this.mesh._worldMatrix);
  45504. }
  45505. // increment indexes for the next particle
  45506. index = idx + 3;
  45507. colorIndex = colidx + 4;
  45508. uvIndex = uvidx + 2;
  45509. }
  45510. // if the VBO must be updated
  45511. if (update) {
  45512. if (this._computeParticleColor) {
  45513. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  45514. }
  45515. if (this._computeParticleTexture) {
  45516. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  45517. }
  45518. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45519. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  45520. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  45521. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  45522. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  45523. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  45524. for (var i = 0; i < this._normals32.length; i++) {
  45525. this._fixedNormal32[i] = this._normals32[i];
  45526. }
  45527. }
  45528. if (!this.mesh.areNormalsFrozen) {
  45529. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  45530. }
  45531. }
  45532. if (this._depthSort && this._depthSortParticles) {
  45533. this.depthSortedParticles.sort(this._depthSortFunction);
  45534. var dspl = this.depthSortedParticles.length;
  45535. var sorted = 0;
  45536. var lind = 0;
  45537. var sind = 0;
  45538. var sid = 0;
  45539. for (sorted = 0; sorted < dspl; sorted++) {
  45540. lind = this.depthSortedParticles[sorted].indicesLength;
  45541. sind = this.depthSortedParticles[sorted].ind;
  45542. for (var i = 0; i < lind; i++) {
  45543. this._indices32[sid] = this._indices[sind + i];
  45544. sid++;
  45545. }
  45546. }
  45547. this.mesh.updateIndices(this._indices32);
  45548. }
  45549. }
  45550. if (this._computeBoundingBox) {
  45551. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  45552. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  45553. }
  45554. this.afterUpdateParticles(start, end, update);
  45555. return this;
  45556. };
  45557. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  45558. this._halfroll = this._roll * 0.5;
  45559. this._halfpitch = this._pitch * 0.5;
  45560. this._halfyaw = this._yaw * 0.5;
  45561. this._sinRoll = Math.sin(this._halfroll);
  45562. this._cosRoll = Math.cos(this._halfroll);
  45563. this._sinPitch = Math.sin(this._halfpitch);
  45564. this._cosPitch = Math.cos(this._halfpitch);
  45565. this._sinYaw = Math.sin(this._halfyaw);
  45566. this._cosYaw = Math.cos(this._halfyaw);
  45567. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  45568. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  45569. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  45570. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  45571. };
  45572. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  45573. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  45574. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  45575. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  45576. this._rotMatrix.m[3] = 0;
  45577. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  45578. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  45579. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  45580. this._rotMatrix.m[7] = 0;
  45581. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  45582. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  45583. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  45584. this._rotMatrix.m[11] = 0;
  45585. this._rotMatrix.m[12] = 0;
  45586. this._rotMatrix.m[13] = 0;
  45587. this._rotMatrix.m[14] = 0;
  45588. this._rotMatrix.m[15] = 1.0;
  45589. };
  45590. /**
  45591. * Disposes the SPS.
  45592. * Returns nothing.
  45593. */
  45594. SolidParticleSystem.prototype.dispose = function () {
  45595. this.mesh.dispose();
  45596. this.vars = null;
  45597. // drop references to internal big arrays for the GC
  45598. this._positions = null;
  45599. this._indices = null;
  45600. this._normals = null;
  45601. this._uvs = null;
  45602. this._colors = null;
  45603. this._indices32 = null;
  45604. this._positions32 = null;
  45605. this._normals32 = null;
  45606. this._fixedNormal32 = null;
  45607. this._uvs32 = null;
  45608. this._colors32 = null;
  45609. this.pickedParticles = null;
  45610. };
  45611. /**
  45612. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  45613. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45614. * Returns the SPS.
  45615. */
  45616. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  45617. if (!this._isVisibilityBoxLocked) {
  45618. this.mesh.refreshBoundingInfo();
  45619. }
  45620. return this;
  45621. };
  45622. /**
  45623. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  45624. * @param size the size (float) of the visibility box
  45625. * note : this doesn't lock the SPS mesh bounding box.
  45626. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45627. */
  45628. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  45629. var vis = size / 2;
  45630. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  45631. };
  45632. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  45633. // getter and setter
  45634. get: function () {
  45635. return this._alwaysVisible;
  45636. },
  45637. /**
  45638. * Sets the SPS as always visible or not
  45639. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45640. */
  45641. set: function (val) {
  45642. this._alwaysVisible = val;
  45643. this.mesh.alwaysSelectAsActiveMesh = val;
  45644. },
  45645. enumerable: true,
  45646. configurable: true
  45647. });
  45648. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  45649. get: function () {
  45650. return this._isVisibilityBoxLocked;
  45651. },
  45652. /**
  45653. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  45654. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45655. */
  45656. set: function (val) {
  45657. this._isVisibilityBoxLocked = val;
  45658. var boundingInfo = this.mesh.getBoundingInfo();
  45659. if (boundingInfo) {
  45660. boundingInfo.isLocked = val;
  45661. }
  45662. },
  45663. enumerable: true,
  45664. configurable: true
  45665. });
  45666. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  45667. // getters
  45668. get: function () {
  45669. return this._computeParticleRotation;
  45670. },
  45671. // Optimizer setters
  45672. /**
  45673. * Tells to `setParticles()` to compute the particle rotations or not.
  45674. * Default value : true. The SPS is faster when it's set to false.
  45675. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  45676. */
  45677. set: function (val) {
  45678. this._computeParticleRotation = val;
  45679. },
  45680. enumerable: true,
  45681. configurable: true
  45682. });
  45683. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  45684. get: function () {
  45685. return this._computeParticleColor;
  45686. },
  45687. /**
  45688. * Tells to `setParticles()` to compute the particle colors or not.
  45689. * Default value : true. The SPS is faster when it's set to false.
  45690. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  45691. */
  45692. set: function (val) {
  45693. this._computeParticleColor = val;
  45694. },
  45695. enumerable: true,
  45696. configurable: true
  45697. });
  45698. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  45699. get: function () {
  45700. return this._computeParticleTexture;
  45701. },
  45702. /**
  45703. * Tells to `setParticles()` to compute the particle textures or not.
  45704. * Default value : true. The SPS is faster when it's set to false.
  45705. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  45706. */
  45707. set: function (val) {
  45708. this._computeParticleTexture = val;
  45709. },
  45710. enumerable: true,
  45711. configurable: true
  45712. });
  45713. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  45714. get: function () {
  45715. return this._computeParticleVertex;
  45716. },
  45717. /**
  45718. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  45719. * Default value : false. The SPS is faster when it's set to false.
  45720. * Note : the particle custom vertex positions aren't stored values.
  45721. */
  45722. set: function (val) {
  45723. this._computeParticleVertex = val;
  45724. },
  45725. enumerable: true,
  45726. configurable: true
  45727. });
  45728. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  45729. get: function () {
  45730. return this._computeBoundingBox;
  45731. },
  45732. /**
  45733. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  45734. */
  45735. set: function (val) {
  45736. this._computeBoundingBox = val;
  45737. },
  45738. enumerable: true,
  45739. configurable: true
  45740. });
  45741. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  45742. get: function () {
  45743. return this._depthSortParticles;
  45744. },
  45745. /**
  45746. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  45747. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  45748. * Default : `true`
  45749. */
  45750. set: function (val) {
  45751. this._depthSortParticles = val;
  45752. },
  45753. enumerable: true,
  45754. configurable: true
  45755. });
  45756. // =======================================================================
  45757. // Particle behavior logic
  45758. // these following methods may be overwritten by the user to fit his needs
  45759. /**
  45760. * This function does nothing. It may be overwritten to set all the particle first values.
  45761. * The SPS doesn't call this function, you may have to call it by your own.
  45762. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45763. */
  45764. SolidParticleSystem.prototype.initParticles = function () {
  45765. };
  45766. /**
  45767. * This function does nothing. It may be overwritten to recycle a particle.
  45768. * The SPS doesn't call this function, you may have to call it by your own.
  45769. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45770. */
  45771. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  45772. return particle;
  45773. };
  45774. /**
  45775. * Updates a particle : this function should be overwritten by the user.
  45776. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  45777. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45778. * ex : just set a particle position or velocity and recycle conditions
  45779. */
  45780. SolidParticleSystem.prototype.updateParticle = function (particle) {
  45781. return particle;
  45782. };
  45783. /**
  45784. * Updates a vertex of a particle : it can be overwritten by the user.
  45785. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  45786. * @param particle the current particle
  45787. * @param vertex the current index of the current particle
  45788. * @param pt the index of the current vertex in the particle shape
  45789. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  45790. * ex : just set a vertex particle position
  45791. */
  45792. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  45793. return vertex;
  45794. };
  45795. /**
  45796. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  45797. * This does nothing and may be overwritten by the user.
  45798. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45799. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45800. * @param update the boolean update value actually passed to setParticles()
  45801. */
  45802. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  45803. };
  45804. /**
  45805. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  45806. * This will be passed three parameters.
  45807. * This does nothing and may be overwritten by the user.
  45808. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45809. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45810. * @param update the boolean update value actually passed to setParticles()
  45811. */
  45812. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  45813. };
  45814. return SolidParticleSystem;
  45815. }());
  45816. BABYLON.SolidParticleSystem = SolidParticleSystem;
  45817. })(BABYLON || (BABYLON = {}));
  45818. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  45819. var BABYLON;
  45820. (function (BABYLON) {
  45821. var GroundMesh = /** @class */ (function (_super) {
  45822. __extends(GroundMesh, _super);
  45823. function GroundMesh(name, scene) {
  45824. var _this = _super.call(this, name, scene) || this;
  45825. _this.generateOctree = false;
  45826. return _this;
  45827. }
  45828. GroundMesh.prototype.getClassName = function () {
  45829. return "GroundMesh";
  45830. };
  45831. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  45832. get: function () {
  45833. return Math.min(this._subdivisionsX, this._subdivisionsY);
  45834. },
  45835. enumerable: true,
  45836. configurable: true
  45837. });
  45838. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  45839. get: function () {
  45840. return this._subdivisionsX;
  45841. },
  45842. enumerable: true,
  45843. configurable: true
  45844. });
  45845. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  45846. get: function () {
  45847. return this._subdivisionsY;
  45848. },
  45849. enumerable: true,
  45850. configurable: true
  45851. });
  45852. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  45853. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  45854. this._subdivisionsX = chunksCount;
  45855. this._subdivisionsY = chunksCount;
  45856. this.subdivide(chunksCount);
  45857. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  45858. };
  45859. /**
  45860. * Returns a height (y) value in the Worl system :
  45861. * the ground altitude at the coordinates (x, z) expressed in the World system.
  45862. * Returns the ground y position if (x, z) are outside the ground surface.
  45863. */
  45864. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  45865. var world = this.getWorldMatrix();
  45866. var invMat = BABYLON.Tmp.Matrix[5];
  45867. world.invertToRef(invMat);
  45868. var tmpVect = BABYLON.Tmp.Vector3[8];
  45869. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  45870. x = tmpVect.x;
  45871. z = tmpVect.z;
  45872. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45873. return this.position.y;
  45874. }
  45875. if (!this._heightQuads || this._heightQuads.length == 0) {
  45876. this._initHeightQuads();
  45877. this._computeHeightQuads();
  45878. }
  45879. var facet = this._getFacetAt(x, z);
  45880. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  45881. // return y in the World system
  45882. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  45883. return tmpVect.y;
  45884. };
  45885. /**
  45886. * Returns a normalized vector (Vector3) orthogonal to the ground
  45887. * at the ground coordinates (x, z) expressed in the World system.
  45888. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  45889. */
  45890. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  45891. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  45892. this.getNormalAtCoordinatesToRef(x, z, normal);
  45893. return normal;
  45894. };
  45895. /**
  45896. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  45897. * at the ground coordinates (x, z) expressed in the World system.
  45898. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  45899. * Returns the GroundMesh.
  45900. */
  45901. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  45902. var world = this.getWorldMatrix();
  45903. var tmpMat = BABYLON.Tmp.Matrix[5];
  45904. world.invertToRef(tmpMat);
  45905. var tmpVect = BABYLON.Tmp.Vector3[8];
  45906. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  45907. x = tmpVect.x;
  45908. z = tmpVect.z;
  45909. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45910. return this;
  45911. }
  45912. if (!this._heightQuads || this._heightQuads.length == 0) {
  45913. this._initHeightQuads();
  45914. this._computeHeightQuads();
  45915. }
  45916. var facet = this._getFacetAt(x, z);
  45917. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  45918. return this;
  45919. };
  45920. /**
  45921. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  45922. * if the ground has been updated.
  45923. * This can be used in the render loop.
  45924. * Returns the GroundMesh.
  45925. */
  45926. GroundMesh.prototype.updateCoordinateHeights = function () {
  45927. if (!this._heightQuads || this._heightQuads.length == 0) {
  45928. this._initHeightQuads();
  45929. }
  45930. this._computeHeightQuads();
  45931. return this;
  45932. };
  45933. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  45934. GroundMesh.prototype._getFacetAt = function (x, z) {
  45935. // retrieve col and row from x, z coordinates in the ground local system
  45936. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  45937. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  45938. var quad = this._heightQuads[row * this._subdivisionsX + col];
  45939. var facet;
  45940. if (z < quad.slope.x * x + quad.slope.y) {
  45941. facet = quad.facet1;
  45942. }
  45943. else {
  45944. facet = quad.facet2;
  45945. }
  45946. return facet;
  45947. };
  45948. // Creates and populates the heightMap array with "facet" elements :
  45949. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  45950. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45951. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45952. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45953. // Returns the GroundMesh.
  45954. GroundMesh.prototype._initHeightQuads = function () {
  45955. var subdivisionsX = this._subdivisionsX;
  45956. var subdivisionsY = this._subdivisionsY;
  45957. this._heightQuads = new Array();
  45958. for (var row = 0; row < subdivisionsY; row++) {
  45959. for (var col = 0; col < subdivisionsX; col++) {
  45960. 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) };
  45961. this._heightQuads[row * subdivisionsX + col] = quad;
  45962. }
  45963. }
  45964. return this;
  45965. };
  45966. // Compute each quad element values and update the the heightMap array :
  45967. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45968. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45969. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45970. // Returns the GroundMesh.
  45971. GroundMesh.prototype._computeHeightQuads = function () {
  45972. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45973. if (!positions) {
  45974. return this;
  45975. }
  45976. var v1 = BABYLON.Tmp.Vector3[3];
  45977. var v2 = BABYLON.Tmp.Vector3[2];
  45978. var v3 = BABYLON.Tmp.Vector3[1];
  45979. var v4 = BABYLON.Tmp.Vector3[0];
  45980. var v1v2 = BABYLON.Tmp.Vector3[4];
  45981. var v1v3 = BABYLON.Tmp.Vector3[5];
  45982. var v1v4 = BABYLON.Tmp.Vector3[6];
  45983. var norm1 = BABYLON.Tmp.Vector3[7];
  45984. var norm2 = BABYLON.Tmp.Vector3[8];
  45985. var i = 0;
  45986. var j = 0;
  45987. var k = 0;
  45988. var cd = 0; // 2D slope coefficient : z = cd * x + h
  45989. var h = 0;
  45990. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  45991. var d2 = 0;
  45992. var subdivisionsX = this._subdivisionsX;
  45993. var subdivisionsY = this._subdivisionsY;
  45994. for (var row = 0; row < subdivisionsY; row++) {
  45995. for (var col = 0; col < subdivisionsX; col++) {
  45996. i = col * 3;
  45997. j = row * (subdivisionsX + 1) * 3;
  45998. k = (row + 1) * (subdivisionsX + 1) * 3;
  45999. v1.x = positions[j + i];
  46000. v1.y = positions[j + i + 1];
  46001. v1.z = positions[j + i + 2];
  46002. v2.x = positions[j + i + 3];
  46003. v2.y = positions[j + i + 4];
  46004. v2.z = positions[j + i + 5];
  46005. v3.x = positions[k + i];
  46006. v3.y = positions[k + i + 1];
  46007. v3.z = positions[k + i + 2];
  46008. v4.x = positions[k + i + 3];
  46009. v4.y = positions[k + i + 4];
  46010. v4.z = positions[k + i + 5];
  46011. // 2D slope V1V4
  46012. cd = (v4.z - v1.z) / (v4.x - v1.x);
  46013. h = v1.z - cd * v1.x; // v1 belongs to the slope
  46014. // facet equations :
  46015. // we compute each facet normal vector
  46016. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  46017. // we compute the value d by applying the equation to v1 which belongs to the plane
  46018. // then we store the facet equation in a Vector4
  46019. v2.subtractToRef(v1, v1v2);
  46020. v3.subtractToRef(v1, v1v3);
  46021. v4.subtractToRef(v1, v1v4);
  46022. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  46023. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  46024. norm1.normalize();
  46025. norm2.normalize();
  46026. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  46027. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  46028. var quad = this._heightQuads[row * subdivisionsX + col];
  46029. quad.slope.copyFromFloats(cd, h);
  46030. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  46031. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  46032. }
  46033. }
  46034. return this;
  46035. };
  46036. GroundMesh.prototype.serialize = function (serializationObject) {
  46037. _super.prototype.serialize.call(this, serializationObject);
  46038. serializationObject.subdivisionsX = this._subdivisionsX;
  46039. serializationObject.subdivisionsY = this._subdivisionsY;
  46040. serializationObject.minX = this._minX;
  46041. serializationObject.maxX = this._maxX;
  46042. serializationObject.minZ = this._minZ;
  46043. serializationObject.maxZ = this._maxZ;
  46044. serializationObject.width = this._width;
  46045. serializationObject.height = this._height;
  46046. };
  46047. GroundMesh.Parse = function (parsedMesh, scene) {
  46048. var result = new GroundMesh(parsedMesh.name, scene);
  46049. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  46050. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  46051. result._minX = parsedMesh.minX;
  46052. result._maxX = parsedMesh.maxX;
  46053. result._minZ = parsedMesh.minZ;
  46054. result._maxZ = parsedMesh.maxZ;
  46055. result._width = parsedMesh.width;
  46056. result._height = parsedMesh.height;
  46057. return result;
  46058. };
  46059. return GroundMesh;
  46060. }(BABYLON.Mesh));
  46061. BABYLON.GroundMesh = GroundMesh;
  46062. })(BABYLON || (BABYLON = {}));
  46063. //# sourceMappingURL=babylon.groundMesh.js.map
  46064. var BABYLON;
  46065. (function (BABYLON) {
  46066. /**
  46067. * Creates an instance based on a source mesh.
  46068. */
  46069. var InstancedMesh = /** @class */ (function (_super) {
  46070. __extends(InstancedMesh, _super);
  46071. function InstancedMesh(name, source) {
  46072. var _this = _super.call(this, name, source.getScene()) || this;
  46073. source.instances.push(_this);
  46074. _this._sourceMesh = source;
  46075. _this.position.copyFrom(source.position);
  46076. _this.rotation.copyFrom(source.rotation);
  46077. _this.scaling.copyFrom(source.scaling);
  46078. if (source.rotationQuaternion) {
  46079. _this.rotationQuaternion = source.rotationQuaternion.clone();
  46080. }
  46081. _this.infiniteDistance = source.infiniteDistance;
  46082. _this.setPivotMatrix(source.getPivotMatrix());
  46083. _this.refreshBoundingInfo();
  46084. _this._syncSubMeshes();
  46085. return _this;
  46086. }
  46087. /**
  46088. * Returns the string "InstancedMesh".
  46089. */
  46090. InstancedMesh.prototype.getClassName = function () {
  46091. return "InstancedMesh";
  46092. };
  46093. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46094. // Methods
  46095. get: function () {
  46096. return this._sourceMesh.receiveShadows;
  46097. },
  46098. enumerable: true,
  46099. configurable: true
  46100. });
  46101. Object.defineProperty(InstancedMesh.prototype, "material", {
  46102. get: function () {
  46103. return this._sourceMesh.material;
  46104. },
  46105. enumerable: true,
  46106. configurable: true
  46107. });
  46108. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46109. get: function () {
  46110. return this._sourceMesh.visibility;
  46111. },
  46112. enumerable: true,
  46113. configurable: true
  46114. });
  46115. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46116. get: function () {
  46117. return this._sourceMesh.skeleton;
  46118. },
  46119. enumerable: true,
  46120. configurable: true
  46121. });
  46122. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46123. get: function () {
  46124. return this._sourceMesh.renderingGroupId;
  46125. },
  46126. enumerable: true,
  46127. configurable: true
  46128. });
  46129. /**
  46130. * Returns the total number of vertices (integer).
  46131. */
  46132. InstancedMesh.prototype.getTotalVertices = function () {
  46133. return this._sourceMesh.getTotalVertices();
  46134. };
  46135. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46136. get: function () {
  46137. return this._sourceMesh;
  46138. },
  46139. enumerable: true,
  46140. configurable: true
  46141. });
  46142. /**
  46143. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46144. */
  46145. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46146. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46147. };
  46148. /**
  46149. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46150. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46151. * The `data` are either a numeric array either a Float32Array.
  46152. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46153. * 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).
  46154. * Note that a new underlying VertexBuffer object is created each call.
  46155. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46156. *
  46157. * Possible `kind` values :
  46158. * - BABYLON.VertexBuffer.PositionKind
  46159. * - BABYLON.VertexBuffer.UVKind
  46160. * - BABYLON.VertexBuffer.UV2Kind
  46161. * - BABYLON.VertexBuffer.UV3Kind
  46162. * - BABYLON.VertexBuffer.UV4Kind
  46163. * - BABYLON.VertexBuffer.UV5Kind
  46164. * - BABYLON.VertexBuffer.UV6Kind
  46165. * - BABYLON.VertexBuffer.ColorKind
  46166. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46167. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46168. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46169. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46170. *
  46171. * Returns the Mesh.
  46172. */
  46173. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46174. if (this.sourceMesh) {
  46175. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46176. }
  46177. return this.sourceMesh;
  46178. };
  46179. /**
  46180. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46181. * If the mesh has no geometry, it is simply returned as it is.
  46182. * The `data` are either a numeric array either a Float32Array.
  46183. * No new underlying VertexBuffer object is created.
  46184. * 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.
  46185. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46186. *
  46187. * Possible `kind` values :
  46188. * - BABYLON.VertexBuffer.PositionKind
  46189. * - BABYLON.VertexBuffer.UVKind
  46190. * - BABYLON.VertexBuffer.UV2Kind
  46191. * - BABYLON.VertexBuffer.UV3Kind
  46192. * - BABYLON.VertexBuffer.UV4Kind
  46193. * - BABYLON.VertexBuffer.UV5Kind
  46194. * - BABYLON.VertexBuffer.UV6Kind
  46195. * - BABYLON.VertexBuffer.ColorKind
  46196. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46197. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46198. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46199. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46200. *
  46201. * Returns the Mesh.
  46202. */
  46203. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46204. if (this.sourceMesh) {
  46205. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46206. }
  46207. return this.sourceMesh;
  46208. };
  46209. /**
  46210. * Sets the mesh indices.
  46211. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46212. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46213. * This method creates a new index buffer each call.
  46214. * Returns the Mesh.
  46215. */
  46216. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46217. if (totalVertices === void 0) { totalVertices = null; }
  46218. if (this.sourceMesh) {
  46219. this.sourceMesh.setIndices(indices, totalVertices);
  46220. }
  46221. return this.sourceMesh;
  46222. };
  46223. /**
  46224. * Boolean : True if the mesh owns the requested kind of data.
  46225. */
  46226. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46227. return this._sourceMesh.isVerticesDataPresent(kind);
  46228. };
  46229. /**
  46230. * Returns an array of indices (IndicesArray).
  46231. */
  46232. InstancedMesh.prototype.getIndices = function () {
  46233. return this._sourceMesh.getIndices();
  46234. };
  46235. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46236. get: function () {
  46237. return this._sourceMesh._positions;
  46238. },
  46239. enumerable: true,
  46240. configurable: true
  46241. });
  46242. /**
  46243. * Sets a new updated BoundingInfo to the mesh.
  46244. * Returns the mesh.
  46245. */
  46246. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46247. var meshBB = this._sourceMesh.getBoundingInfo();
  46248. if (meshBB) {
  46249. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46250. }
  46251. this._updateBoundingInfo();
  46252. return this;
  46253. };
  46254. InstancedMesh.prototype._preActivate = function () {
  46255. if (this._currentLOD) {
  46256. this._currentLOD._preActivate();
  46257. }
  46258. return this;
  46259. };
  46260. InstancedMesh.prototype._activate = function (renderId) {
  46261. if (this._currentLOD) {
  46262. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46263. }
  46264. return this;
  46265. };
  46266. /**
  46267. * Returns the current associated LOD AbstractMesh.
  46268. */
  46269. InstancedMesh.prototype.getLOD = function (camera) {
  46270. if (!camera) {
  46271. return this;
  46272. }
  46273. var boundingInfo = this.getBoundingInfo();
  46274. if (!boundingInfo) {
  46275. return this;
  46276. }
  46277. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46278. if (this._currentLOD === this.sourceMesh) {
  46279. return this;
  46280. }
  46281. return this._currentLOD;
  46282. };
  46283. InstancedMesh.prototype._syncSubMeshes = function () {
  46284. this.releaseSubMeshes();
  46285. if (this._sourceMesh.subMeshes) {
  46286. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46287. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46288. }
  46289. }
  46290. return this;
  46291. };
  46292. InstancedMesh.prototype._generatePointsArray = function () {
  46293. return this._sourceMesh._generatePointsArray();
  46294. };
  46295. /**
  46296. * Creates a new InstancedMesh from the current mesh.
  46297. * - name (string) : the cloned mesh name
  46298. * - newParent (optional Node) : the optional Node to parent the clone to.
  46299. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46300. *
  46301. * Returns the clone.
  46302. */
  46303. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46304. var result = this._sourceMesh.createInstance(name);
  46305. // Deep copy
  46306. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46307. // Bounding info
  46308. this.refreshBoundingInfo();
  46309. // Parent
  46310. if (newParent) {
  46311. result.parent = newParent;
  46312. }
  46313. if (!doNotCloneChildren) {
  46314. // Children
  46315. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46316. var mesh = this.getScene().meshes[index];
  46317. if (mesh.parent === this) {
  46318. mesh.clone(mesh.name, result);
  46319. }
  46320. }
  46321. }
  46322. result.computeWorldMatrix(true);
  46323. return result;
  46324. };
  46325. /**
  46326. * Disposes the InstancedMesh.
  46327. * Returns nothing.
  46328. */
  46329. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46330. // Remove from mesh
  46331. var index = this._sourceMesh.instances.indexOf(this);
  46332. this._sourceMesh.instances.splice(index, 1);
  46333. _super.prototype.dispose.call(this, doNotRecurse);
  46334. };
  46335. return InstancedMesh;
  46336. }(BABYLON.AbstractMesh));
  46337. BABYLON.InstancedMesh = InstancedMesh;
  46338. })(BABYLON || (BABYLON = {}));
  46339. //# sourceMappingURL=babylon.instancedMesh.js.map
  46340. var BABYLON;
  46341. (function (BABYLON) {
  46342. var LinesMesh = /** @class */ (function (_super) {
  46343. __extends(LinesMesh, _super);
  46344. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  46345. if (scene === void 0) { scene = null; }
  46346. if (parent === void 0) { parent = null; }
  46347. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46348. _this.useVertexColor = useVertexColor;
  46349. _this.color = new BABYLON.Color3(1, 1, 1);
  46350. _this.alpha = 1;
  46351. if (source) {
  46352. _this.color = source.color.clone();
  46353. _this.alpha = source.alpha;
  46354. _this.useVertexColor = source.useVertexColor;
  46355. }
  46356. _this._intersectionThreshold = 0.1;
  46357. var options = {
  46358. attributes: [BABYLON.VertexBuffer.PositionKind],
  46359. uniforms: ["world", "viewProjection"],
  46360. needAlphaBlending: false,
  46361. };
  46362. if (!useVertexColor) {
  46363. options.uniforms.push("color");
  46364. options.needAlphaBlending = true;
  46365. }
  46366. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46367. return _this;
  46368. }
  46369. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46370. /**
  46371. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46372. * This margin is expressed in world space coordinates, so its value may vary.
  46373. * Default value is 0.1
  46374. * @returns the intersection Threshold value.
  46375. */
  46376. get: function () {
  46377. return this._intersectionThreshold;
  46378. },
  46379. /**
  46380. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46381. * This margin is expressed in world space coordinates, so its value may vary.
  46382. * @param value the new threshold to apply
  46383. */
  46384. set: function (value) {
  46385. if (this._intersectionThreshold === value) {
  46386. return;
  46387. }
  46388. this._intersectionThreshold = value;
  46389. if (this.geometry) {
  46390. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46391. }
  46392. },
  46393. enumerable: true,
  46394. configurable: true
  46395. });
  46396. /**
  46397. * Returns the string "LineMesh"
  46398. */
  46399. LinesMesh.prototype.getClassName = function () {
  46400. return "LinesMesh";
  46401. };
  46402. Object.defineProperty(LinesMesh.prototype, "material", {
  46403. get: function () {
  46404. return this._colorShader;
  46405. },
  46406. set: function (value) {
  46407. // Do nothing
  46408. },
  46409. enumerable: true,
  46410. configurable: true
  46411. });
  46412. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46413. get: function () {
  46414. return false;
  46415. },
  46416. enumerable: true,
  46417. configurable: true
  46418. });
  46419. LinesMesh.prototype.createInstance = function (name) {
  46420. throw new Error("LinesMeshes do not support createInstance.");
  46421. };
  46422. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46423. if (!this._geometry) {
  46424. return this;
  46425. }
  46426. // VBOs
  46427. this._geometry._bind(this._colorShader.getEffect());
  46428. // Color
  46429. if (!this.useVertexColor) {
  46430. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46431. }
  46432. return this;
  46433. };
  46434. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46435. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46436. return this;
  46437. }
  46438. var engine = this.getScene().getEngine();
  46439. // Draw order
  46440. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46441. return this;
  46442. };
  46443. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46444. this._colorShader.dispose();
  46445. _super.prototype.dispose.call(this, doNotRecurse);
  46446. };
  46447. /**
  46448. * Returns a new LineMesh object cloned from the current one.
  46449. */
  46450. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46451. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  46452. };
  46453. return LinesMesh;
  46454. }(BABYLON.Mesh));
  46455. BABYLON.LinesMesh = LinesMesh;
  46456. })(BABYLON || (BABYLON = {}));
  46457. //# sourceMappingURL=babylon.linesMesh.js.map
  46458. var BABYLON;
  46459. (function (BABYLON) {
  46460. var ShaderMaterial = /** @class */ (function (_super) {
  46461. __extends(ShaderMaterial, _super);
  46462. function ShaderMaterial(name, scene, shaderPath, options) {
  46463. var _this = _super.call(this, name, scene) || this;
  46464. _this._textures = {};
  46465. _this._textureArrays = {};
  46466. _this._floats = {};
  46467. _this._floatsArrays = {};
  46468. _this._colors3 = {};
  46469. _this._colors3Arrays = {};
  46470. _this._colors4 = {};
  46471. _this._vectors2 = {};
  46472. _this._vectors3 = {};
  46473. _this._vectors4 = {};
  46474. _this._matrices = {};
  46475. _this._matrices3x3 = {};
  46476. _this._matrices2x2 = {};
  46477. _this._vectors3Arrays = {};
  46478. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46479. _this._shaderPath = shaderPath;
  46480. options.needAlphaBlending = options.needAlphaBlending || false;
  46481. options.needAlphaTesting = options.needAlphaTesting || false;
  46482. options.attributes = options.attributes || ["position", "normal", "uv"];
  46483. options.uniforms = options.uniforms || ["worldViewProjection"];
  46484. options.uniformBuffers = options.uniformBuffers || [];
  46485. options.samplers = options.samplers || [];
  46486. options.defines = options.defines || [];
  46487. _this._options = options;
  46488. return _this;
  46489. }
  46490. ShaderMaterial.prototype.getClassName = function () {
  46491. return "ShaderMaterial";
  46492. };
  46493. ShaderMaterial.prototype.needAlphaBlending = function () {
  46494. return this._options.needAlphaBlending;
  46495. };
  46496. ShaderMaterial.prototype.needAlphaTesting = function () {
  46497. return this._options.needAlphaTesting;
  46498. };
  46499. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46500. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46501. this._options.uniforms.push(uniformName);
  46502. }
  46503. };
  46504. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46505. if (this._options.samplers.indexOf(name) === -1) {
  46506. this._options.samplers.push(name);
  46507. }
  46508. this._textures[name] = texture;
  46509. return this;
  46510. };
  46511. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46512. if (this._options.samplers.indexOf(name) === -1) {
  46513. this._options.samplers.push(name);
  46514. }
  46515. this._checkUniform(name);
  46516. this._textureArrays[name] = textures;
  46517. return this;
  46518. };
  46519. ShaderMaterial.prototype.setFloat = function (name, value) {
  46520. this._checkUniform(name);
  46521. this._floats[name] = value;
  46522. return this;
  46523. };
  46524. ShaderMaterial.prototype.setFloats = function (name, value) {
  46525. this._checkUniform(name);
  46526. this._floatsArrays[name] = value;
  46527. return this;
  46528. };
  46529. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46530. this._checkUniform(name);
  46531. this._colors3[name] = value;
  46532. return this;
  46533. };
  46534. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  46535. this._checkUniform(name);
  46536. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  46537. color.toArray(arr, arr.length);
  46538. return arr;
  46539. }, []);
  46540. return this;
  46541. };
  46542. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46543. this._checkUniform(name);
  46544. this._colors4[name] = value;
  46545. return this;
  46546. };
  46547. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46548. this._checkUniform(name);
  46549. this._vectors2[name] = value;
  46550. return this;
  46551. };
  46552. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46553. this._checkUniform(name);
  46554. this._vectors3[name] = value;
  46555. return this;
  46556. };
  46557. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46558. this._checkUniform(name);
  46559. this._vectors4[name] = value;
  46560. return this;
  46561. };
  46562. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46563. this._checkUniform(name);
  46564. this._matrices[name] = value;
  46565. return this;
  46566. };
  46567. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46568. this._checkUniform(name);
  46569. this._matrices3x3[name] = value;
  46570. return this;
  46571. };
  46572. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46573. this._checkUniform(name);
  46574. this._matrices2x2[name] = value;
  46575. return this;
  46576. };
  46577. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46578. this._checkUniform(name);
  46579. this._vectors3Arrays[name] = value;
  46580. return this;
  46581. };
  46582. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46583. if (!mesh) {
  46584. return true;
  46585. }
  46586. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46587. return false;
  46588. }
  46589. return false;
  46590. };
  46591. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46592. var scene = this.getScene();
  46593. var engine = scene.getEngine();
  46594. if (!this.checkReadyOnEveryCall) {
  46595. if (this._renderId === scene.getRenderId()) {
  46596. if (this._checkCache(scene, mesh, useInstances)) {
  46597. return true;
  46598. }
  46599. }
  46600. }
  46601. // Instances
  46602. var defines = [];
  46603. var attribs = [];
  46604. var fallbacks = new BABYLON.EffectFallbacks();
  46605. if (useInstances) {
  46606. defines.push("#define INSTANCES");
  46607. }
  46608. for (var index = 0; index < this._options.defines.length; index++) {
  46609. defines.push(this._options.defines[index]);
  46610. }
  46611. for (var index = 0; index < this._options.attributes.length; index++) {
  46612. attribs.push(this._options.attributes[index]);
  46613. }
  46614. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  46615. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46616. defines.push("#define VERTEXCOLOR");
  46617. }
  46618. // Bones
  46619. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  46620. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46621. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46622. if (mesh.numBoneInfluencers > 4) {
  46623. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46624. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46625. }
  46626. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46627. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46628. fallbacks.addCPUSkinningFallback(0, mesh);
  46629. if (this._options.uniforms.indexOf("mBones") === -1) {
  46630. this._options.uniforms.push("mBones");
  46631. }
  46632. }
  46633. else {
  46634. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46635. }
  46636. // Textures
  46637. for (var name in this._textures) {
  46638. if (!this._textures[name].isReady()) {
  46639. return false;
  46640. }
  46641. }
  46642. // Alpha test
  46643. if (engine.getAlphaTesting()) {
  46644. defines.push("#define ALPHATEST");
  46645. }
  46646. var previousEffect = this._effect;
  46647. var join = defines.join("\n");
  46648. this._effect = engine.createEffect(this._shaderPath, {
  46649. attributes: attribs,
  46650. uniformsNames: this._options.uniforms,
  46651. uniformBuffersNames: this._options.uniformBuffers,
  46652. samplers: this._options.samplers,
  46653. defines: join,
  46654. fallbacks: fallbacks,
  46655. onCompiled: this.onCompiled,
  46656. onError: this.onError
  46657. }, engine);
  46658. if (!this._effect.isReady()) {
  46659. return false;
  46660. }
  46661. if (previousEffect !== this._effect) {
  46662. scene.resetCachedMaterial();
  46663. }
  46664. this._renderId = scene.getRenderId();
  46665. return true;
  46666. };
  46667. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46668. var scene = this.getScene();
  46669. if (!this._effect) {
  46670. return;
  46671. }
  46672. if (this._options.uniforms.indexOf("world") !== -1) {
  46673. this._effect.setMatrix("world", world);
  46674. }
  46675. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46676. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46677. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46678. }
  46679. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46680. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46681. }
  46682. };
  46683. ShaderMaterial.prototype.bind = function (world, mesh) {
  46684. // Std values
  46685. this.bindOnlyWorldMatrix(world);
  46686. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  46687. if (this._options.uniforms.indexOf("view") !== -1) {
  46688. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46689. }
  46690. if (this._options.uniforms.indexOf("projection") !== -1) {
  46691. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46692. }
  46693. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46694. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46695. }
  46696. // Bones
  46697. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46698. var name;
  46699. // Texture
  46700. for (name in this._textures) {
  46701. this._effect.setTexture(name, this._textures[name]);
  46702. }
  46703. // Texture arrays
  46704. for (name in this._textureArrays) {
  46705. this._effect.setTextureArray(name, this._textureArrays[name]);
  46706. }
  46707. // Float
  46708. for (name in this._floats) {
  46709. this._effect.setFloat(name, this._floats[name]);
  46710. }
  46711. // Float s
  46712. for (name in this._floatsArrays) {
  46713. this._effect.setArray(name, this._floatsArrays[name]);
  46714. }
  46715. // Color3
  46716. for (name in this._colors3) {
  46717. this._effect.setColor3(name, this._colors3[name]);
  46718. }
  46719. for (name in this._colors3Arrays) {
  46720. this._effect.setArray3(name, this._colors3Arrays[name]);
  46721. }
  46722. // Color4
  46723. for (name in this._colors4) {
  46724. var color = this._colors4[name];
  46725. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46726. }
  46727. // Vector2
  46728. for (name in this._vectors2) {
  46729. this._effect.setVector2(name, this._vectors2[name]);
  46730. }
  46731. // Vector3
  46732. for (name in this._vectors3) {
  46733. this._effect.setVector3(name, this._vectors3[name]);
  46734. }
  46735. // Vector4
  46736. for (name in this._vectors4) {
  46737. this._effect.setVector4(name, this._vectors4[name]);
  46738. }
  46739. // Matrix
  46740. for (name in this._matrices) {
  46741. this._effect.setMatrix(name, this._matrices[name]);
  46742. }
  46743. // Matrix 3x3
  46744. for (name in this._matrices3x3) {
  46745. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46746. }
  46747. // Matrix 2x2
  46748. for (name in this._matrices2x2) {
  46749. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46750. }
  46751. // Vector3Array
  46752. for (name in this._vectors3Arrays) {
  46753. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46754. }
  46755. }
  46756. this._afterBind(mesh);
  46757. };
  46758. ShaderMaterial.prototype.getActiveTextures = function () {
  46759. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46760. for (var name in this._textures) {
  46761. activeTextures.push(this._textures[name]);
  46762. }
  46763. for (var name in this._textureArrays) {
  46764. var array = this._textureArrays[name];
  46765. for (var index = 0; index < array.length; index++) {
  46766. activeTextures.push(array[index]);
  46767. }
  46768. }
  46769. return activeTextures;
  46770. };
  46771. ShaderMaterial.prototype.hasTexture = function (texture) {
  46772. if (_super.prototype.hasTexture.call(this, texture)) {
  46773. return true;
  46774. }
  46775. for (var name in this._textures) {
  46776. if (this._textures[name] === texture) {
  46777. return true;
  46778. }
  46779. }
  46780. for (var name in this._textureArrays) {
  46781. var array = this._textureArrays[name];
  46782. for (var index = 0; index < array.length; index++) {
  46783. if (array[index] === texture) {
  46784. return true;
  46785. }
  46786. }
  46787. }
  46788. return false;
  46789. };
  46790. ShaderMaterial.prototype.clone = function (name) {
  46791. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46792. return newShaderMaterial;
  46793. };
  46794. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46795. if (forceDisposeTextures) {
  46796. var name;
  46797. for (name in this._textures) {
  46798. this._textures[name].dispose();
  46799. }
  46800. for (name in this._textureArrays) {
  46801. var array = this._textureArrays[name];
  46802. for (var index = 0; index < array.length; index++) {
  46803. array[index].dispose();
  46804. }
  46805. }
  46806. }
  46807. this._textures = {};
  46808. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46809. };
  46810. ShaderMaterial.prototype.serialize = function () {
  46811. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46812. serializationObject.customType = "BABYLON.ShaderMaterial";
  46813. serializationObject.options = this._options;
  46814. serializationObject.shaderPath = this._shaderPath;
  46815. var name;
  46816. // Texture
  46817. serializationObject.textures = {};
  46818. for (name in this._textures) {
  46819. serializationObject.textures[name] = this._textures[name].serialize();
  46820. }
  46821. // Texture arrays
  46822. serializationObject.textureArrays = {};
  46823. for (name in this._textureArrays) {
  46824. serializationObject.textureArrays[name] = [];
  46825. var array = this._textureArrays[name];
  46826. for (var index = 0; index < array.length; index++) {
  46827. serializationObject.textureArrays[name].push(array[index].serialize());
  46828. }
  46829. }
  46830. // Float
  46831. serializationObject.floats = {};
  46832. for (name in this._floats) {
  46833. serializationObject.floats[name] = this._floats[name];
  46834. }
  46835. // Float s
  46836. serializationObject.FloatArrays = {};
  46837. for (name in this._floatsArrays) {
  46838. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  46839. }
  46840. // Color3
  46841. serializationObject.colors3 = {};
  46842. for (name in this._colors3) {
  46843. serializationObject.colors3[name] = this._colors3[name].asArray();
  46844. }
  46845. // Color3 array
  46846. serializationObject.colors3Arrays = {};
  46847. for (name in this._colors3Arrays) {
  46848. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  46849. }
  46850. // Color4
  46851. serializationObject.colors4 = {};
  46852. for (name in this._colors4) {
  46853. serializationObject.colors4[name] = this._colors4[name].asArray();
  46854. }
  46855. // Vector2
  46856. serializationObject.vectors2 = {};
  46857. for (name in this._vectors2) {
  46858. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46859. }
  46860. // Vector3
  46861. serializationObject.vectors3 = {};
  46862. for (name in this._vectors3) {
  46863. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46864. }
  46865. // Vector4
  46866. serializationObject.vectors4 = {};
  46867. for (name in this._vectors4) {
  46868. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46869. }
  46870. // Matrix
  46871. serializationObject.matrices = {};
  46872. for (name in this._matrices) {
  46873. serializationObject.matrices[name] = this._matrices[name].asArray();
  46874. }
  46875. // Matrix 3x3
  46876. serializationObject.matrices3x3 = {};
  46877. for (name in this._matrices3x3) {
  46878. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46879. }
  46880. // Matrix 2x2
  46881. serializationObject.matrices2x2 = {};
  46882. for (name in this._matrices2x2) {
  46883. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46884. }
  46885. // Vector3Array
  46886. serializationObject.vectors3Arrays = {};
  46887. for (name in this._vectors3Arrays) {
  46888. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46889. }
  46890. return serializationObject;
  46891. };
  46892. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46893. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46894. var name;
  46895. // Texture
  46896. for (name in source.textures) {
  46897. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46898. }
  46899. // Texture arrays
  46900. for (name in source.textureArrays) {
  46901. var array = source.textureArrays[name];
  46902. var textureArray = new Array();
  46903. for (var index = 0; index < array.length; index++) {
  46904. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46905. }
  46906. material.setTextureArray(name, textureArray);
  46907. }
  46908. // Float
  46909. for (name in source.floats) {
  46910. material.setFloat(name, source.floats[name]);
  46911. }
  46912. // Float s
  46913. for (name in source.floatsArrays) {
  46914. material.setFloats(name, source.floatsArrays[name]);
  46915. }
  46916. // Color3
  46917. for (name in source.colors3) {
  46918. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46919. }
  46920. // Color3 arrays
  46921. for (name in source.colors3Arrays) {
  46922. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  46923. if (i % 3 === 0) {
  46924. arr.push([num]);
  46925. }
  46926. else {
  46927. arr[arr.length - 1].push(num);
  46928. }
  46929. return arr;
  46930. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  46931. material.setColor3Array(name, colors);
  46932. }
  46933. // Color4
  46934. for (name in source.colors4) {
  46935. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46936. }
  46937. // Vector2
  46938. for (name in source.vectors2) {
  46939. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46940. }
  46941. // Vector3
  46942. for (name in source.vectors3) {
  46943. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46944. }
  46945. // Vector4
  46946. for (name in source.vectors4) {
  46947. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46948. }
  46949. // Matrix
  46950. for (name in source.matrices) {
  46951. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46952. }
  46953. // Matrix 3x3
  46954. for (name in source.matrices3x3) {
  46955. material.setMatrix3x3(name, source.matrices3x3[name]);
  46956. }
  46957. // Matrix 2x2
  46958. for (name in source.matrices2x2) {
  46959. material.setMatrix2x2(name, source.matrices2x2[name]);
  46960. }
  46961. // Vector3Array
  46962. for (name in source.vectors3Arrays) {
  46963. material.setArray3(name, source.vectors3Arrays[name]);
  46964. }
  46965. return material;
  46966. };
  46967. return ShaderMaterial;
  46968. }(BABYLON.Material));
  46969. BABYLON.ShaderMaterial = ShaderMaterial;
  46970. })(BABYLON || (BABYLON = {}));
  46971. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46972. var BABYLON;
  46973. (function (BABYLON) {
  46974. var MeshBuilder = /** @class */ (function () {
  46975. function MeshBuilder() {
  46976. }
  46977. MeshBuilder.updateSideOrientation = function (orientation) {
  46978. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  46979. return BABYLON.Mesh.DOUBLESIDE;
  46980. }
  46981. if (orientation === undefined || orientation === null) {
  46982. return BABYLON.Mesh.FRONTSIDE;
  46983. }
  46984. return orientation;
  46985. };
  46986. /**
  46987. * Creates a box mesh.
  46988. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  46989. * The parameter `size` sets the size (float) of each box side (default 1).
  46990. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  46991. * 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).
  46992. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46994. * 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).
  46995. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46997. */
  46998. MeshBuilder.CreateBox = function (name, options, scene) {
  46999. if (scene === void 0) { scene = null; }
  47000. var box = new BABYLON.Mesh(name, scene);
  47001. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47002. box._originalBuilderSideOrientation = options.sideOrientation;
  47003. var vertexData = BABYLON.VertexData.CreateBox(options);
  47004. vertexData.applyToMesh(box, options.updatable);
  47005. return box;
  47006. };
  47007. /**
  47008. * Creates a sphere mesh.
  47009. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  47010. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  47011. * 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`).
  47012. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  47013. * 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
  47014. * 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).
  47015. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47016. * 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).
  47017. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47019. */
  47020. MeshBuilder.CreateSphere = function (name, options, scene) {
  47021. var sphere = new BABYLON.Mesh(name, scene);
  47022. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47023. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47024. var vertexData = BABYLON.VertexData.CreateSphere(options);
  47025. vertexData.applyToMesh(sphere, options.updatable);
  47026. return sphere;
  47027. };
  47028. /**
  47029. * Creates a plane polygonal mesh. By default, this is a disc.
  47030. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  47031. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  47032. * 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.
  47033. * 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
  47034. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47035. * 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).
  47036. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47037. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47038. */
  47039. MeshBuilder.CreateDisc = function (name, options, scene) {
  47040. if (scene === void 0) { scene = null; }
  47041. var disc = new BABYLON.Mesh(name, scene);
  47042. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47043. disc._originalBuilderSideOrientation = options.sideOrientation;
  47044. var vertexData = BABYLON.VertexData.CreateDisc(options);
  47045. vertexData.applyToMesh(disc, options.updatable);
  47046. return disc;
  47047. };
  47048. /**
  47049. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  47050. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  47051. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  47052. * 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`).
  47053. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  47054. * 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.
  47055. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47056. * 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).
  47057. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47058. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47059. */
  47060. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  47061. var sphere = new BABYLON.Mesh(name, scene);
  47062. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47063. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47064. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  47065. vertexData.applyToMesh(sphere, options.updatable);
  47066. return sphere;
  47067. };
  47068. ;
  47069. /**
  47070. * Creates a ribbon mesh.
  47071. * 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.
  47072. *
  47073. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  47074. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  47075. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  47076. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  47077. * 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.
  47078. * 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.
  47079. * 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
  47080. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47081. * 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).
  47082. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47083. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47084. * 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.
  47085. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  47086. * 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
  47087. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47088. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47090. */
  47091. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47092. if (scene === void 0) { scene = null; }
  47093. var pathArray = options.pathArray;
  47094. var closeArray = options.closeArray;
  47095. var closePath = options.closePath;
  47096. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47097. var instance = options.instance;
  47098. var updatable = options.updatable;
  47099. if (instance) {
  47100. // positionFunction : ribbon case
  47101. // only pathArray and sideOrientation parameters are taken into account for positions update
  47102. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47103. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47104. var positionFunction = function (positions) {
  47105. var minlg = pathArray[0].length;
  47106. var i = 0;
  47107. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47108. for (var si = 1; si <= ns; si++) {
  47109. for (var p = 0; p < pathArray.length; p++) {
  47110. var path = pathArray[p];
  47111. var l = path.length;
  47112. minlg = (minlg < l) ? minlg : l;
  47113. var j = 0;
  47114. while (j < minlg) {
  47115. positions[i] = path[j].x;
  47116. positions[i + 1] = path[j].y;
  47117. positions[i + 2] = path[j].z;
  47118. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47119. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47120. }
  47121. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47122. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47123. }
  47124. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47125. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47126. }
  47127. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47128. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47129. }
  47130. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47131. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47132. }
  47133. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47134. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47135. }
  47136. j++;
  47137. i += 3;
  47138. }
  47139. if (instance._closePath) {
  47140. positions[i] = path[0].x;
  47141. positions[i + 1] = path[0].y;
  47142. positions[i + 2] = path[0].z;
  47143. i += 3;
  47144. }
  47145. }
  47146. }
  47147. };
  47148. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47149. positionFunction(positions);
  47150. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  47151. instance._boundingInfo.update(instance._worldMatrix);
  47152. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47153. if (options.colors) {
  47154. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47155. for (var c = 0; c < options.colors.length; c++) {
  47156. colors[c * 4] = options.colors[c].r;
  47157. colors[c * 4 + 1] = options.colors[c].g;
  47158. colors[c * 4 + 2] = options.colors[c].b;
  47159. colors[c * 4 + 3] = options.colors[c].a;
  47160. }
  47161. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  47162. }
  47163. if (options.uvs) {
  47164. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47165. for (var i = 0; i < options.uvs.length; i++) {
  47166. uvs[i * 2] = options.uvs[i].x;
  47167. uvs[i * 2 + 1] = options.uvs[i].y;
  47168. }
  47169. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  47170. }
  47171. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  47172. var indices = instance.getIndices();
  47173. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47174. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47175. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47176. if (instance._closePath) {
  47177. var indexFirst = 0;
  47178. var indexLast = 0;
  47179. for (var p = 0; p < pathArray.length; p++) {
  47180. indexFirst = instance._idx[p] * 3;
  47181. if (p + 1 < pathArray.length) {
  47182. indexLast = (instance._idx[p + 1] - 1) * 3;
  47183. }
  47184. else {
  47185. indexLast = normals.length - 3;
  47186. }
  47187. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47188. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47189. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47190. normals[indexLast] = normals[indexFirst];
  47191. normals[indexLast + 1] = normals[indexFirst + 1];
  47192. normals[indexLast + 2] = normals[indexFirst + 2];
  47193. }
  47194. }
  47195. if (!(instance.areNormalsFrozen)) {
  47196. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47197. }
  47198. }
  47199. return instance;
  47200. }
  47201. else {
  47202. var ribbon = new BABYLON.Mesh(name, scene);
  47203. ribbon._originalBuilderSideOrientation = sideOrientation;
  47204. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47205. if (closePath) {
  47206. ribbon._idx = vertexData._idx;
  47207. }
  47208. ribbon._closePath = closePath;
  47209. ribbon._closeArray = closeArray;
  47210. vertexData.applyToMesh(ribbon, updatable);
  47211. return ribbon;
  47212. }
  47213. };
  47214. /**
  47215. * Creates a cylinder or a cone mesh.
  47216. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  47217. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  47218. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  47219. * 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.
  47220. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  47221. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  47222. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  47223. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  47224. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  47225. * 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).
  47226. * 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
  47227. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  47228. * 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
  47229. * 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.
  47230. * If `enclose` is false, a ring surface is one element.
  47231. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  47232. * 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
  47233. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47234. * 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).
  47235. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47236. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47237. */
  47238. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47239. var cylinder = new BABYLON.Mesh(name, scene);
  47240. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47241. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47242. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47243. vertexData.applyToMesh(cylinder, options.updatable);
  47244. return cylinder;
  47245. };
  47246. /**
  47247. * Creates a torus mesh.
  47248. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47249. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47250. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47251. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47252. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47253. * 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).
  47254. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47256. */
  47257. MeshBuilder.CreateTorus = function (name, options, scene) {
  47258. var torus = new BABYLON.Mesh(name, scene);
  47259. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47260. torus._originalBuilderSideOrientation = options.sideOrientation;
  47261. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47262. vertexData.applyToMesh(torus, options.updatable);
  47263. return torus;
  47264. };
  47265. /**
  47266. * Creates a torus knot mesh.
  47267. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47268. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47269. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47270. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47271. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47272. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47273. * 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).
  47274. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47275. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47276. */
  47277. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47278. var torusKnot = new BABYLON.Mesh(name, scene);
  47279. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47280. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47281. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47282. vertexData.applyToMesh(torusKnot, options.updatable);
  47283. return torusKnot;
  47284. };
  47285. /**
  47286. * Creates a line system mesh.
  47287. * A line system is a pool of many lines gathered in a single mesh.
  47288. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47289. * 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.
  47290. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47291. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47292. * 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
  47293. * 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
  47294. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47295. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47296. */
  47297. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47298. var instance = options.instance;
  47299. var lines = options.lines;
  47300. if (instance) {
  47301. var positionFunction = function (positions) {
  47302. var i = 0;
  47303. for (var l = 0; l < lines.length; l++) {
  47304. var points = lines[l];
  47305. for (var p = 0; p < points.length; p++) {
  47306. positions[i] = points[p].x;
  47307. positions[i + 1] = points[p].y;
  47308. positions[i + 2] = points[p].z;
  47309. i += 3;
  47310. }
  47311. }
  47312. };
  47313. instance.updateMeshPositions(positionFunction, false);
  47314. return instance;
  47315. }
  47316. // line system creation
  47317. var lineSystem = new BABYLON.LinesMesh(name, scene);
  47318. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47319. vertexData.applyToMesh(lineSystem, options.updatable);
  47320. return lineSystem;
  47321. };
  47322. /**
  47323. * Creates a line mesh.
  47324. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47325. * 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.
  47326. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47327. * The parameter `points` is an array successive Vector3.
  47328. * 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
  47329. * When updating an instance, remember that only point positions can change, not the number of points.
  47330. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47331. */
  47332. MeshBuilder.CreateLines = function (name, options, scene) {
  47333. if (scene === void 0) { scene = null; }
  47334. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  47335. return lines;
  47336. };
  47337. /**
  47338. * Creates a dashed line mesh.
  47339. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47340. * 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.
  47341. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47342. * The parameter `points` is an array successive Vector3.
  47343. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47344. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47345. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47346. * 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
  47347. * When updating an instance, remember that only point positions can change, not the number of points.
  47348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47349. */
  47350. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47351. if (scene === void 0) { scene = null; }
  47352. var points = options.points;
  47353. var instance = options.instance;
  47354. var gapSize = options.gapSize || 1;
  47355. var dashSize = options.dashSize || 3;
  47356. if (instance) {
  47357. var positionFunction = function (positions) {
  47358. var curvect = BABYLON.Vector3.Zero();
  47359. var nbSeg = positions.length / 6;
  47360. var lg = 0;
  47361. var nb = 0;
  47362. var shft = 0;
  47363. var dashshft = 0;
  47364. var curshft = 0;
  47365. var p = 0;
  47366. var i = 0;
  47367. var j = 0;
  47368. for (i = 0; i < points.length - 1; i++) {
  47369. points[i + 1].subtractToRef(points[i], curvect);
  47370. lg += curvect.length();
  47371. }
  47372. shft = lg / nbSeg;
  47373. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47374. for (i = 0; i < points.length - 1; i++) {
  47375. points[i + 1].subtractToRef(points[i], curvect);
  47376. nb = Math.floor(curvect.length() / shft);
  47377. curvect.normalize();
  47378. j = 0;
  47379. while (j < nb && p < positions.length) {
  47380. curshft = shft * j;
  47381. positions[p] = points[i].x + curshft * curvect.x;
  47382. positions[p + 1] = points[i].y + curshft * curvect.y;
  47383. positions[p + 2] = points[i].z + curshft * curvect.z;
  47384. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47385. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47386. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47387. p += 6;
  47388. j++;
  47389. }
  47390. }
  47391. while (p < positions.length) {
  47392. positions[p] = points[i].x;
  47393. positions[p + 1] = points[i].y;
  47394. positions[p + 2] = points[i].z;
  47395. p += 3;
  47396. }
  47397. };
  47398. instance.updateMeshPositions(positionFunction, false);
  47399. return instance;
  47400. }
  47401. // dashed lines creation
  47402. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47403. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47404. vertexData.applyToMesh(dashedLines, options.updatable);
  47405. dashedLines.dashSize = dashSize;
  47406. dashedLines.gapSize = gapSize;
  47407. return dashedLines;
  47408. };
  47409. /**
  47410. * Creates an extruded shape mesh.
  47411. * 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.
  47412. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47413. *
  47414. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47415. * 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
  47416. * extruded along the Z axis.
  47417. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47418. * 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.
  47419. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47420. * 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
  47421. * 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
  47422. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47423. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47424. * 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).
  47425. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47426. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47427. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47428. */
  47429. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  47430. if (scene === void 0) { scene = null; }
  47431. var path = options.path;
  47432. var shape = options.shape;
  47433. var scale = options.scale || 1;
  47434. var rotation = options.rotation || 0;
  47435. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47436. var updatable = options.updatable;
  47437. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47438. var instance = options.instance || null;
  47439. var invertUV = options.invertUV || false;
  47440. 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);
  47441. };
  47442. /**
  47443. * Creates an custom extruded shape mesh.
  47444. * 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.
  47445. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  47446. *
  47447. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47448. * 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
  47449. * extruded along the Z axis.
  47450. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47451. * 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
  47452. * and the distance of this point from the begining of the path :
  47453. * ```javascript
  47454. * var rotationFunction = function(i, distance) {
  47455. * // do things
  47456. * return rotationValue; }
  47457. * ```
  47458. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  47459. * 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
  47460. * and the distance of this point from the begining of the path :
  47461. * ```javascript
  47462. * var scaleFunction = function(i, distance) {
  47463. * // do things
  47464. * return scaleValue;}
  47465. * ```
  47466. * It must returns a float value that will be the scale value applied to the shape on each path point.
  47467. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  47468. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  47469. * 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
  47470. * 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
  47471. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47472. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47473. * 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).
  47474. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47475. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47476. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47477. */
  47478. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  47479. var path = options.path;
  47480. var shape = options.shape;
  47481. var scaleFunction = options.scaleFunction || (function () { return 1; });
  47482. var rotationFunction = options.rotationFunction || (function () { return 0; });
  47483. var ribbonCloseArray = options.ribbonCloseArray || false;
  47484. var ribbonClosePath = options.ribbonClosePath || false;
  47485. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47486. var updatable = options.updatable;
  47487. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47488. var instance = options.instance;
  47489. var invertUV = options.invertUV || false;
  47490. 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);
  47491. };
  47492. /**
  47493. * Creates lathe mesh.
  47494. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  47495. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  47496. *
  47497. * 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
  47498. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  47499. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  47500. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  47501. * 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.
  47502. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  47503. * 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
  47504. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47505. * 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).
  47506. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47507. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47508. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47509. */
  47510. MeshBuilder.CreateLathe = function (name, options, scene) {
  47511. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  47512. var closed = (options.closed === undefined) ? true : options.closed;
  47513. var shape = options.shape;
  47514. var radius = options.radius || 1;
  47515. var tessellation = options.tessellation || 64;
  47516. var updatable = options.updatable;
  47517. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47518. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47519. var pi2 = Math.PI * 2;
  47520. var paths = new Array();
  47521. var invertUV = options.invertUV || false;
  47522. var i = 0;
  47523. var p = 0;
  47524. var step = pi2 / tessellation * arc;
  47525. var rotated;
  47526. var path = new Array();
  47527. ;
  47528. for (i = 0; i <= tessellation; i++) {
  47529. var path = [];
  47530. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  47531. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  47532. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  47533. }
  47534. for (p = 0; p < shape.length; p++) {
  47535. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  47536. path.push(rotated);
  47537. }
  47538. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  47539. 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));
  47540. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  47541. }
  47542. paths.push(path);
  47543. }
  47544. // lathe ribbon
  47545. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47546. return lathe;
  47547. };
  47548. /**
  47549. * Creates a plane mesh.
  47550. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47551. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  47552. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  47553. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  47554. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47555. * 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).
  47556. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47557. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47558. */
  47559. MeshBuilder.CreatePlane = function (name, options, scene) {
  47560. var plane = new BABYLON.Mesh(name, scene);
  47561. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47562. plane._originalBuilderSideOrientation = options.sideOrientation;
  47563. var vertexData = BABYLON.VertexData.CreatePlane(options);
  47564. vertexData.applyToMesh(plane, options.updatable);
  47565. if (options.sourcePlane) {
  47566. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  47567. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  47568. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  47569. plane.rotate(vectorProduct, product);
  47570. }
  47571. return plane;
  47572. };
  47573. /**
  47574. * Creates a ground mesh.
  47575. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47576. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  47577. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  47578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47579. */
  47580. MeshBuilder.CreateGround = function (name, options, scene) {
  47581. var ground = new BABYLON.GroundMesh(name, scene);
  47582. ground._setReady(false);
  47583. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  47584. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  47585. ground._width = options.width || 1;
  47586. ground._height = options.height || 1;
  47587. ground._maxX = ground._width / 2;
  47588. ground._maxZ = ground._height / 2;
  47589. ground._minX = -ground._maxX;
  47590. ground._minZ = -ground._maxZ;
  47591. var vertexData = BABYLON.VertexData.CreateGround(options);
  47592. vertexData.applyToMesh(ground, options.updatable);
  47593. ground._setReady(true);
  47594. return ground;
  47595. };
  47596. /**
  47597. * Creates a tiled ground mesh.
  47598. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  47599. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  47600. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  47601. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  47602. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  47603. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  47604. * numbers of subdivisions on the ground width and height of each tile.
  47605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47606. */
  47607. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  47608. var tiledGround = new BABYLON.Mesh(name, scene);
  47609. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  47610. vertexData.applyToMesh(tiledGround, options.updatable);
  47611. return tiledGround;
  47612. };
  47613. /**
  47614. * Creates a ground mesh from a height map.
  47615. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  47616. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  47617. * The parameter `url` sets the URL of the height map image resource.
  47618. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  47619. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  47620. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  47621. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  47622. * 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.
  47623. * 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).
  47624. * This function is passed the newly built mesh :
  47625. * ```javascript
  47626. * function(mesh) { // do things
  47627. * return; }
  47628. * ```
  47629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47630. */
  47631. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  47632. var width = options.width || 10.0;
  47633. var height = options.height || 10.0;
  47634. var subdivisions = options.subdivisions || 1 | 0;
  47635. var minHeight = options.minHeight || 0.0;
  47636. var maxHeight = options.maxHeight || 1.0;
  47637. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  47638. var updatable = options.updatable;
  47639. var onReady = options.onReady;
  47640. var ground = new BABYLON.GroundMesh(name, scene);
  47641. ground._subdivisionsX = subdivisions;
  47642. ground._subdivisionsY = subdivisions;
  47643. ground._width = width;
  47644. ground._height = height;
  47645. ground._maxX = ground._width / 2.0;
  47646. ground._maxZ = ground._height / 2.0;
  47647. ground._minX = -ground._maxX;
  47648. ground._minZ = -ground._maxZ;
  47649. ground._setReady(false);
  47650. var onload = function (img) {
  47651. // Getting height map data
  47652. var canvas = document.createElement("canvas");
  47653. var context = canvas.getContext("2d");
  47654. if (!context) {
  47655. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  47656. }
  47657. var bufferWidth = img.width;
  47658. var bufferHeight = img.height;
  47659. canvas.width = bufferWidth;
  47660. canvas.height = bufferHeight;
  47661. context.drawImage(img, 0, 0);
  47662. // Create VertexData from map data
  47663. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  47664. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  47665. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  47666. width: width, height: height,
  47667. subdivisions: subdivisions,
  47668. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  47669. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  47670. });
  47671. vertexData.applyToMesh(ground, updatable);
  47672. ground._setReady(true);
  47673. //execute ready callback, if set
  47674. if (onReady) {
  47675. onReady(ground);
  47676. }
  47677. };
  47678. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  47679. return ground;
  47680. };
  47681. /**
  47682. * Creates a polygon mesh.
  47683. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  47684. * 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.
  47685. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47687. * 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).
  47688. * Remember you can only change the shape positions, not their number when updating a polygon.
  47689. */
  47690. MeshBuilder.CreatePolygon = function (name, options, scene) {
  47691. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47692. var shape = options.shape;
  47693. var holes = options.holes || [];
  47694. var depth = options.depth || 0;
  47695. var contours = [];
  47696. var hole = [];
  47697. for (var i = 0; i < shape.length; i++) {
  47698. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  47699. }
  47700. var epsilon = 0.00000001;
  47701. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  47702. contours.pop();
  47703. }
  47704. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  47705. for (var hNb = 0; hNb < holes.length; hNb++) {
  47706. hole = [];
  47707. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  47708. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  47709. }
  47710. polygonTriangulation.addHole(hole);
  47711. }
  47712. var polygon = polygonTriangulation.build(options.updatable, depth);
  47713. polygon._originalBuilderSideOrientation = options.sideOrientation;
  47714. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  47715. vertexData.applyToMesh(polygon, options.updatable);
  47716. return polygon;
  47717. };
  47718. ;
  47719. /**
  47720. * Creates an extruded polygon mesh, with depth in the Y direction.
  47721. * 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).
  47722. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47723. */
  47724. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  47725. return MeshBuilder.CreatePolygon(name, options, scene);
  47726. };
  47727. ;
  47728. /**
  47729. * Creates a tube mesh.
  47730. * 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.
  47731. *
  47732. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  47733. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  47734. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  47735. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  47736. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  47737. * 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.
  47738. * It must return a radius value (positive float) :
  47739. * ```javascript
  47740. * var radiusFunction = function(i, distance) {
  47741. * // do things
  47742. * return radius; }
  47743. * ```
  47744. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  47745. * 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
  47746. * 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
  47747. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47748. * 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).
  47749. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47750. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47752. */
  47753. MeshBuilder.CreateTube = function (name, options, scene) {
  47754. var path = options.path;
  47755. var instance = options.instance;
  47756. var radius = 1.0;
  47757. if (instance) {
  47758. radius = instance.radius;
  47759. }
  47760. if (options.radius !== undefined) {
  47761. radius = options.radius;
  47762. }
  47763. ;
  47764. var tessellation = options.tessellation || 64 | 0;
  47765. var radiusFunction = options.radiusFunction || null;
  47766. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47767. var invertUV = options.invertUV || false;
  47768. var updatable = options.updatable;
  47769. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47770. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  47771. // tube geometry
  47772. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  47773. var tangents = path3D.getTangents();
  47774. var normals = path3D.getNormals();
  47775. var distances = path3D.getDistances();
  47776. var pi2 = Math.PI * 2;
  47777. var step = pi2 / tessellation * arc;
  47778. var returnRadius = function () { return radius; };
  47779. var radiusFunctionFinal = radiusFunction || returnRadius;
  47780. var circlePath;
  47781. var rad;
  47782. var normal;
  47783. var rotated;
  47784. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47785. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47786. for (var i = 0; i < path.length; i++) {
  47787. rad = radiusFunctionFinal(i, distances[i]); // current radius
  47788. circlePath = Array(); // current circle array
  47789. normal = normals[i]; // current normal
  47790. for (var t = 0; t < tessellation; t++) {
  47791. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  47792. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  47793. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  47794. rotated.scaleInPlace(rad).addInPlace(path[i]);
  47795. circlePath[t] = rotated;
  47796. }
  47797. circlePaths[index] = circlePath;
  47798. index++;
  47799. }
  47800. // cap
  47801. var capPath = function (nbPoints, pathIndex) {
  47802. var pointCap = Array();
  47803. for (var i = 0; i < nbPoints; i++) {
  47804. pointCap.push(path[pathIndex]);
  47805. }
  47806. return pointCap;
  47807. };
  47808. switch (cap) {
  47809. case BABYLON.Mesh.NO_CAP:
  47810. break;
  47811. case BABYLON.Mesh.CAP_START:
  47812. circlePaths[0] = capPath(tessellation, 0);
  47813. circlePaths[1] = circlePaths[2].slice(0);
  47814. break;
  47815. case BABYLON.Mesh.CAP_END:
  47816. circlePaths[index] = circlePaths[index - 1].slice(0);
  47817. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47818. break;
  47819. case BABYLON.Mesh.CAP_ALL:
  47820. circlePaths[0] = capPath(tessellation, 0);
  47821. circlePaths[1] = circlePaths[2].slice(0);
  47822. circlePaths[index] = circlePaths[index - 1].slice(0);
  47823. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47824. break;
  47825. default:
  47826. break;
  47827. }
  47828. return circlePaths;
  47829. };
  47830. var path3D;
  47831. var pathArray;
  47832. if (instance) {
  47833. var arc = options.arc || instance.arc;
  47834. path3D = (instance.path3D).update(path);
  47835. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  47836. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  47837. instance.path3D = path3D;
  47838. instance.pathArray = pathArray;
  47839. instance.arc = arc;
  47840. instance.radius = radius;
  47841. return instance;
  47842. }
  47843. // tube creation
  47844. path3D = new BABYLON.Path3D(path);
  47845. var newPathArray = new Array();
  47846. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47847. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  47848. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47849. tube.pathArray = pathArray;
  47850. tube.path3D = path3D;
  47851. tube.tessellation = tessellation;
  47852. tube.cap = cap;
  47853. tube.arc = options.arc;
  47854. tube.radius = radius;
  47855. return tube;
  47856. };
  47857. /**
  47858. * Creates a polyhedron mesh.
  47859. *
  47860. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  47861. * 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
  47862. * to choose the wanted type.
  47863. * The parameter `size` (positive float, default 1) sets the polygon size.
  47864. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  47865. * 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`.
  47866. * 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
  47867. * 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)`).
  47868. * 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
  47869. * 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.
  47870. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47871. * 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).
  47872. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47874. */
  47875. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  47876. var polyhedron = new BABYLON.Mesh(name, scene);
  47877. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47878. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  47879. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  47880. vertexData.applyToMesh(polyhedron, options.updatable);
  47881. return polyhedron;
  47882. };
  47883. /**
  47884. * Creates a decal mesh.
  47885. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  47886. * 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.
  47887. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  47888. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  47889. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  47890. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  47891. */
  47892. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  47893. var indices = sourceMesh.getIndices();
  47894. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47895. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47896. var position = options.position || BABYLON.Vector3.Zero();
  47897. var normal = options.normal || BABYLON.Vector3.Up();
  47898. var size = options.size || BABYLON.Vector3.One();
  47899. var angle = options.angle || 0;
  47900. // Getting correct rotation
  47901. if (!normal) {
  47902. var target = new BABYLON.Vector3(0, 0, 1);
  47903. var camera = sourceMesh.getScene().activeCamera;
  47904. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  47905. normal = camera.globalPosition.subtract(cameraWorldTarget);
  47906. }
  47907. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  47908. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  47909. var pitch = Math.atan2(normal.y, len);
  47910. // Matrix
  47911. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  47912. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  47913. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  47914. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  47915. var vertexData = new BABYLON.VertexData();
  47916. vertexData.indices = [];
  47917. vertexData.positions = [];
  47918. vertexData.normals = [];
  47919. vertexData.uvs = [];
  47920. var currentVertexDataIndex = 0;
  47921. var extractDecalVector3 = function (indexId) {
  47922. var result = new BABYLON.PositionNormalVertex();
  47923. if (!indices || !positions || !normals) {
  47924. return result;
  47925. }
  47926. var vertexId = indices[indexId];
  47927. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  47928. // Send vector to decal local world
  47929. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  47930. // Get normal
  47931. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  47932. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  47933. return result;
  47934. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  47935. var clip = function (vertices, axis) {
  47936. if (vertices.length === 0) {
  47937. return vertices;
  47938. }
  47939. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  47940. var clipVertices = function (v0, v1) {
  47941. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  47942. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  47943. };
  47944. var result = new Array();
  47945. for (var index = 0; index < vertices.length; index += 3) {
  47946. var v1Out;
  47947. var v2Out;
  47948. var v3Out;
  47949. var total = 0;
  47950. var nV1 = null;
  47951. var nV2 = null;
  47952. var nV3 = null;
  47953. var nV4 = null;
  47954. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  47955. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  47956. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  47957. v1Out = d1 > 0;
  47958. v2Out = d2 > 0;
  47959. v3Out = d3 > 0;
  47960. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  47961. switch (total) {
  47962. case 0:
  47963. result.push(vertices[index]);
  47964. result.push(vertices[index + 1]);
  47965. result.push(vertices[index + 2]);
  47966. break;
  47967. case 1:
  47968. if (v1Out) {
  47969. nV1 = vertices[index + 1];
  47970. nV2 = vertices[index + 2];
  47971. nV3 = clipVertices(vertices[index], nV1);
  47972. nV4 = clipVertices(vertices[index], nV2);
  47973. }
  47974. if (v2Out) {
  47975. nV1 = vertices[index];
  47976. nV2 = vertices[index + 2];
  47977. nV3 = clipVertices(vertices[index + 1], nV1);
  47978. nV4 = clipVertices(vertices[index + 1], nV2);
  47979. result.push(nV3);
  47980. result.push(nV2.clone());
  47981. result.push(nV1.clone());
  47982. result.push(nV2.clone());
  47983. result.push(nV3.clone());
  47984. result.push(nV4);
  47985. break;
  47986. }
  47987. if (v3Out) {
  47988. nV1 = vertices[index];
  47989. nV2 = vertices[index + 1];
  47990. nV3 = clipVertices(vertices[index + 2], nV1);
  47991. nV4 = clipVertices(vertices[index + 2], nV2);
  47992. }
  47993. if (nV1 && nV2 && nV3 && nV4) {
  47994. result.push(nV1.clone());
  47995. result.push(nV2.clone());
  47996. result.push(nV3);
  47997. result.push(nV4);
  47998. result.push(nV3.clone());
  47999. result.push(nV2.clone());
  48000. }
  48001. break;
  48002. case 2:
  48003. if (!v1Out) {
  48004. nV1 = vertices[index].clone();
  48005. nV2 = clipVertices(nV1, vertices[index + 1]);
  48006. nV3 = clipVertices(nV1, vertices[index + 2]);
  48007. result.push(nV1);
  48008. result.push(nV2);
  48009. result.push(nV3);
  48010. }
  48011. if (!v2Out) {
  48012. nV1 = vertices[index + 1].clone();
  48013. nV2 = clipVertices(nV1, vertices[index + 2]);
  48014. nV3 = clipVertices(nV1, vertices[index]);
  48015. result.push(nV1);
  48016. result.push(nV2);
  48017. result.push(nV3);
  48018. }
  48019. if (!v3Out) {
  48020. nV1 = vertices[index + 2].clone();
  48021. nV2 = clipVertices(nV1, vertices[index]);
  48022. nV3 = clipVertices(nV1, vertices[index + 1]);
  48023. result.push(nV1);
  48024. result.push(nV2);
  48025. result.push(nV3);
  48026. }
  48027. break;
  48028. case 3:
  48029. break;
  48030. }
  48031. }
  48032. return result;
  48033. };
  48034. for (var index = 0; index < indices.length; index += 3) {
  48035. var faceVertices = new Array();
  48036. faceVertices.push(extractDecalVector3(index));
  48037. faceVertices.push(extractDecalVector3(index + 1));
  48038. faceVertices.push(extractDecalVector3(index + 2));
  48039. // Clip
  48040. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  48041. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  48042. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  48043. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  48044. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  48045. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  48046. if (faceVertices.length === 0) {
  48047. continue;
  48048. }
  48049. // Add UVs and get back to world
  48050. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  48051. var vertex = faceVertices[vIndex];
  48052. //TODO check for Int32Array | Uint32Array | Uint16Array
  48053. vertexData.indices.push(currentVertexDataIndex);
  48054. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  48055. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  48056. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  48057. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  48058. currentVertexDataIndex++;
  48059. }
  48060. }
  48061. // Return mesh
  48062. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  48063. vertexData.applyToMesh(decal);
  48064. decal.position = position.clone();
  48065. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  48066. return decal;
  48067. };
  48068. // Privates
  48069. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  48070. // extrusion geometry
  48071. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  48072. var tangents = path3D.getTangents();
  48073. var normals = path3D.getNormals();
  48074. var binormals = path3D.getBinormals();
  48075. var distances = path3D.getDistances();
  48076. var angle = 0;
  48077. var returnScale = function () { return scale !== null ? scale : 1; };
  48078. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  48079. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  48080. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  48081. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48082. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48083. for (var i = 0; i < curve.length; i++) {
  48084. var shapePath = new Array();
  48085. var angleStep = rotate(i, distances[i]);
  48086. var scaleRatio = scl(i, distances[i]);
  48087. for (var p = 0; p < shape.length; p++) {
  48088. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48089. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48090. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48091. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48092. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48093. shapePath[p] = rotated;
  48094. }
  48095. shapePaths[index] = shapePath;
  48096. angle += angleStep;
  48097. index++;
  48098. }
  48099. // cap
  48100. var capPath = function (shapePath) {
  48101. var pointCap = Array();
  48102. var barycenter = BABYLON.Vector3.Zero();
  48103. var i;
  48104. for (i = 0; i < shapePath.length; i++) {
  48105. barycenter.addInPlace(shapePath[i]);
  48106. }
  48107. barycenter.scaleInPlace(1.0 / shapePath.length);
  48108. for (i = 0; i < shapePath.length; i++) {
  48109. pointCap.push(barycenter);
  48110. }
  48111. return pointCap;
  48112. };
  48113. switch (cap) {
  48114. case BABYLON.Mesh.NO_CAP:
  48115. break;
  48116. case BABYLON.Mesh.CAP_START:
  48117. shapePaths[0] = capPath(shapePaths[2]);
  48118. shapePaths[1] = shapePaths[2];
  48119. break;
  48120. case BABYLON.Mesh.CAP_END:
  48121. shapePaths[index] = shapePaths[index - 1];
  48122. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48123. break;
  48124. case BABYLON.Mesh.CAP_ALL:
  48125. shapePaths[0] = capPath(shapePaths[2]);
  48126. shapePaths[1] = shapePaths[2];
  48127. shapePaths[index] = shapePaths[index - 1];
  48128. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48129. break;
  48130. default:
  48131. break;
  48132. }
  48133. return shapePaths;
  48134. };
  48135. var path3D;
  48136. var pathArray;
  48137. if (instance) {
  48138. path3D = (instance.path3D).update(curve);
  48139. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  48140. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  48141. return instance;
  48142. }
  48143. // extruded shape creation
  48144. path3D = new BABYLON.Path3D(curve);
  48145. var newShapePaths = new Array();
  48146. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48147. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  48148. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  48149. extrudedGeneric.pathArray = pathArray;
  48150. extrudedGeneric.path3D = path3D;
  48151. extrudedGeneric.cap = cap;
  48152. return extrudedGeneric;
  48153. };
  48154. return MeshBuilder;
  48155. }());
  48156. BABYLON.MeshBuilder = MeshBuilder;
  48157. })(BABYLON || (BABYLON = {}));
  48158. //# sourceMappingURL=babylon.meshBuilder.js.map
  48159. var BABYLON;
  48160. (function (BABYLON) {
  48161. var AudioEngine = /** @class */ (function () {
  48162. function AudioEngine() {
  48163. this._audioContext = null;
  48164. this._audioContextInitialized = false;
  48165. this.canUseWebAudio = false;
  48166. this.WarnedWebAudioUnsupported = false;
  48167. this.unlocked = false;
  48168. this.isMP3supported = false;
  48169. this.isOGGsupported = false;
  48170. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  48171. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  48172. this.canUseWebAudio = true;
  48173. }
  48174. var audioElem = document.createElement('audio');
  48175. try {
  48176. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48177. this.isMP3supported = true;
  48178. }
  48179. }
  48180. catch (e) {
  48181. // protect error during capability check.
  48182. }
  48183. try {
  48184. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48185. this.isOGGsupported = true;
  48186. }
  48187. }
  48188. catch (e) {
  48189. // protect error during capability check.
  48190. }
  48191. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  48192. this._unlockiOSaudio();
  48193. }
  48194. else {
  48195. this.unlocked = true;
  48196. }
  48197. }
  48198. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  48199. get: function () {
  48200. if (!this._audioContextInitialized) {
  48201. this._initializeAudioContext();
  48202. }
  48203. return this._audioContext;
  48204. },
  48205. enumerable: true,
  48206. configurable: true
  48207. });
  48208. AudioEngine.prototype._unlockiOSaudio = function () {
  48209. var _this = this;
  48210. var unlockaudio = function () {
  48211. if (!_this.audioContext) {
  48212. return;
  48213. }
  48214. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  48215. var source = _this.audioContext.createBufferSource();
  48216. source.buffer = buffer;
  48217. source.connect(_this.audioContext.destination);
  48218. source.start(0);
  48219. setTimeout(function () {
  48220. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  48221. _this.unlocked = true;
  48222. window.removeEventListener('touchend', unlockaudio, false);
  48223. if (_this.onAudioUnlocked) {
  48224. _this.onAudioUnlocked();
  48225. }
  48226. }
  48227. }, 0);
  48228. };
  48229. window.addEventListener('touchend', unlockaudio, false);
  48230. };
  48231. AudioEngine.prototype._initializeAudioContext = function () {
  48232. try {
  48233. if (this.canUseWebAudio) {
  48234. this._audioContext = new AudioContext();
  48235. // create a global volume gain node
  48236. this.masterGain = this._audioContext.createGain();
  48237. this.masterGain.gain.value = 1;
  48238. this.masterGain.connect(this._audioContext.destination);
  48239. this._audioContextInitialized = true;
  48240. }
  48241. }
  48242. catch (e) {
  48243. this.canUseWebAudio = false;
  48244. BABYLON.Tools.Error("Web Audio: " + e.message);
  48245. }
  48246. };
  48247. AudioEngine.prototype.dispose = function () {
  48248. if (this.canUseWebAudio && this._audioContextInitialized) {
  48249. if (this._connectedAnalyser && this._audioContext) {
  48250. this._connectedAnalyser.stopDebugCanvas();
  48251. this._connectedAnalyser.dispose();
  48252. this.masterGain.disconnect();
  48253. this.masterGain.connect(this._audioContext.destination);
  48254. this._connectedAnalyser = null;
  48255. }
  48256. this.masterGain.gain.value = 1;
  48257. }
  48258. this.WarnedWebAudioUnsupported = false;
  48259. };
  48260. AudioEngine.prototype.getGlobalVolume = function () {
  48261. if (this.canUseWebAudio && this._audioContextInitialized) {
  48262. return this.masterGain.gain.value;
  48263. }
  48264. else {
  48265. return -1;
  48266. }
  48267. };
  48268. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48269. if (this.canUseWebAudio && this._audioContextInitialized) {
  48270. this.masterGain.gain.value = newVolume;
  48271. }
  48272. };
  48273. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48274. if (this._connectedAnalyser) {
  48275. this._connectedAnalyser.stopDebugCanvas();
  48276. }
  48277. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48278. this._connectedAnalyser = analyser;
  48279. this.masterGain.disconnect();
  48280. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48281. }
  48282. };
  48283. return AudioEngine;
  48284. }());
  48285. BABYLON.AudioEngine = AudioEngine;
  48286. })(BABYLON || (BABYLON = {}));
  48287. //# sourceMappingURL=babylon.audioEngine.js.map
  48288. var BABYLON;
  48289. (function (BABYLON) {
  48290. var Sound = /** @class */ (function () {
  48291. /**
  48292. * Create a sound and attach it to a scene
  48293. * @param name Name of your sound
  48294. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48295. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48296. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48297. */
  48298. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48299. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48300. var _this = this;
  48301. this.autoplay = false;
  48302. this.loop = false;
  48303. this.useCustomAttenuation = false;
  48304. this.spatialSound = false;
  48305. this.refDistance = 1;
  48306. this.rolloffFactor = 1;
  48307. this.maxDistance = 100;
  48308. this.distanceModel = "linear";
  48309. this._panningModel = "equalpower";
  48310. this._playbackRate = 1;
  48311. this._streaming = false;
  48312. this._startTime = 0;
  48313. this._startOffset = 0;
  48314. this._position = BABYLON.Vector3.Zero();
  48315. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48316. this._volume = 1;
  48317. this._isLoaded = false;
  48318. this._isReadyToPlay = false;
  48319. this.isPlaying = false;
  48320. this.isPaused = false;
  48321. this._isDirectional = false;
  48322. // Used if you'd like to create a directional sound.
  48323. // If not set, the sound will be omnidirectional
  48324. this._coneInnerAngle = 360;
  48325. this._coneOuterAngle = 360;
  48326. this._coneOuterGain = 0;
  48327. this._isOutputConnected = false;
  48328. this._urlType = "Unknown";
  48329. this.name = name;
  48330. this._scene = scene;
  48331. this._readyToPlayCallback = readyToPlayCallback;
  48332. // Default custom attenuation function is a linear attenuation
  48333. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48334. if (currentDistance < maxDistance) {
  48335. return currentVolume * (1 - currentDistance / maxDistance);
  48336. }
  48337. else {
  48338. return 0;
  48339. }
  48340. };
  48341. if (options) {
  48342. this.autoplay = options.autoplay || false;
  48343. this.loop = options.loop || false;
  48344. // if volume === 0, we need another way to check this option
  48345. if (options.volume !== undefined) {
  48346. this._volume = options.volume;
  48347. }
  48348. this.spatialSound = options.spatialSound || false;
  48349. this.maxDistance = options.maxDistance || 100;
  48350. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48351. this.rolloffFactor = options.rolloffFactor || 1;
  48352. this.refDistance = options.refDistance || 1;
  48353. this.distanceModel = options.distanceModel || "linear";
  48354. this._playbackRate = options.playbackRate || 1;
  48355. this._streaming = options.streaming || false;
  48356. }
  48357. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48358. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48359. this._soundGain.gain.value = this._volume;
  48360. this._inputAudioNode = this._soundGain;
  48361. this._ouputAudioNode = this._soundGain;
  48362. if (this.spatialSound) {
  48363. this._createSpatialParameters();
  48364. }
  48365. this._scene.mainSoundTrack.AddSound(this);
  48366. var validParameter = true;
  48367. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48368. if (urlOrArrayBuffer) {
  48369. if (typeof (urlOrArrayBuffer) === "string")
  48370. this._urlType = "String";
  48371. if (Array.isArray(urlOrArrayBuffer))
  48372. this._urlType = "Array";
  48373. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48374. this._urlType = "ArrayBuffer";
  48375. var urls = [];
  48376. var codecSupportedFound = false;
  48377. switch (this._urlType) {
  48378. case "ArrayBuffer":
  48379. if (urlOrArrayBuffer.byteLength > 0) {
  48380. codecSupportedFound = true;
  48381. this._soundLoaded(urlOrArrayBuffer);
  48382. }
  48383. break;
  48384. case "String":
  48385. urls.push(urlOrArrayBuffer);
  48386. case "Array":
  48387. if (urls.length === 0)
  48388. urls = urlOrArrayBuffer;
  48389. // If we found a supported format, we load it immediately and stop the loop
  48390. for (var i = 0; i < urls.length; i++) {
  48391. var url = urls[i];
  48392. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48393. codecSupportedFound = true;
  48394. }
  48395. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48396. codecSupportedFound = true;
  48397. }
  48398. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48399. codecSupportedFound = true;
  48400. }
  48401. if (url.indexOf("blob:") !== -1) {
  48402. codecSupportedFound = true;
  48403. }
  48404. if (codecSupportedFound) {
  48405. // Loading sound using XHR2
  48406. if (!this._streaming) {
  48407. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48408. }
  48409. else {
  48410. this._htmlAudioElement = new Audio(url);
  48411. this._htmlAudioElement.controls = false;
  48412. this._htmlAudioElement.loop = this.loop;
  48413. this._htmlAudioElement.crossOrigin = "anonymous";
  48414. this._htmlAudioElement.preload = "auto";
  48415. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48416. _this._isReadyToPlay = true;
  48417. if (_this.autoplay) {
  48418. _this.play();
  48419. }
  48420. if (_this._readyToPlayCallback) {
  48421. _this._readyToPlayCallback();
  48422. }
  48423. });
  48424. document.body.appendChild(this._htmlAudioElement);
  48425. }
  48426. break;
  48427. }
  48428. }
  48429. break;
  48430. default:
  48431. validParameter = false;
  48432. break;
  48433. }
  48434. if (!validParameter) {
  48435. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  48436. }
  48437. else {
  48438. if (!codecSupportedFound) {
  48439. this._isReadyToPlay = true;
  48440. // Simulating a ready to play event to avoid breaking code path
  48441. if (this._readyToPlayCallback) {
  48442. window.setTimeout(function () {
  48443. if (_this._readyToPlayCallback) {
  48444. _this._readyToPlayCallback();
  48445. }
  48446. }, 1000);
  48447. }
  48448. }
  48449. }
  48450. }
  48451. }
  48452. else {
  48453. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  48454. this._scene.mainSoundTrack.AddSound(this);
  48455. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  48456. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  48457. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  48458. }
  48459. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  48460. if (this._readyToPlayCallback) {
  48461. window.setTimeout(function () {
  48462. if (_this._readyToPlayCallback) {
  48463. _this._readyToPlayCallback();
  48464. }
  48465. }, 1000);
  48466. }
  48467. }
  48468. }
  48469. Sound.prototype.dispose = function () {
  48470. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  48471. if (this.isPlaying) {
  48472. this.stop();
  48473. }
  48474. this._isReadyToPlay = false;
  48475. if (this.soundTrackId === -1) {
  48476. this._scene.mainSoundTrack.RemoveSound(this);
  48477. }
  48478. else {
  48479. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  48480. }
  48481. if (this._soundGain) {
  48482. this._soundGain.disconnect();
  48483. this._soundGain = null;
  48484. }
  48485. if (this._soundPanner) {
  48486. this._soundPanner.disconnect();
  48487. this._soundPanner = null;
  48488. }
  48489. if (this._soundSource) {
  48490. this._soundSource.disconnect();
  48491. this._soundSource = null;
  48492. }
  48493. this._audioBuffer = null;
  48494. if (this._htmlAudioElement) {
  48495. this._htmlAudioElement.pause();
  48496. this._htmlAudioElement.src = "";
  48497. document.body.removeChild(this._htmlAudioElement);
  48498. }
  48499. if (this._connectedMesh && this._registerFunc) {
  48500. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48501. this._connectedMesh = null;
  48502. }
  48503. }
  48504. };
  48505. Sound.prototype.isReady = function () {
  48506. return this._isReadyToPlay;
  48507. };
  48508. Sound.prototype._soundLoaded = function (audioData) {
  48509. var _this = this;
  48510. this._isLoaded = true;
  48511. if (!BABYLON.Engine.audioEngine.audioContext) {
  48512. return;
  48513. }
  48514. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  48515. _this._audioBuffer = buffer;
  48516. _this._isReadyToPlay = true;
  48517. if (_this.autoplay) {
  48518. _this.play();
  48519. }
  48520. if (_this._readyToPlayCallback) {
  48521. _this._readyToPlayCallback();
  48522. }
  48523. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  48524. };
  48525. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  48526. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48527. this._audioBuffer = audioBuffer;
  48528. this._isReadyToPlay = true;
  48529. }
  48530. };
  48531. Sound.prototype.updateOptions = function (options) {
  48532. if (options) {
  48533. this.loop = options.loop || this.loop;
  48534. this.maxDistance = options.maxDistance || this.maxDistance;
  48535. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  48536. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  48537. this.refDistance = options.refDistance || this.refDistance;
  48538. this.distanceModel = options.distanceModel || this.distanceModel;
  48539. this._playbackRate = options.playbackRate || this._playbackRate;
  48540. this._updateSpatialParameters();
  48541. if (this.isPlaying) {
  48542. if (this._streaming) {
  48543. this._htmlAudioElement.playbackRate = this._playbackRate;
  48544. }
  48545. else {
  48546. if (this._soundSource) {
  48547. this._soundSource.playbackRate.value = this._playbackRate;
  48548. }
  48549. }
  48550. }
  48551. }
  48552. };
  48553. Sound.prototype._createSpatialParameters = function () {
  48554. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48555. if (this._scene.headphone) {
  48556. this._panningModel = "HRTF";
  48557. }
  48558. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  48559. this._updateSpatialParameters();
  48560. this._soundPanner.connect(this._ouputAudioNode);
  48561. this._inputAudioNode = this._soundPanner;
  48562. }
  48563. };
  48564. Sound.prototype._updateSpatialParameters = function () {
  48565. if (this.spatialSound && this._soundPanner) {
  48566. if (this.useCustomAttenuation) {
  48567. // Tricks to disable in a way embedded Web Audio attenuation
  48568. this._soundPanner.distanceModel = "linear";
  48569. this._soundPanner.maxDistance = Number.MAX_VALUE;
  48570. this._soundPanner.refDistance = 1;
  48571. this._soundPanner.rolloffFactor = 1;
  48572. this._soundPanner.panningModel = this._panningModel;
  48573. }
  48574. else {
  48575. this._soundPanner.distanceModel = this.distanceModel;
  48576. this._soundPanner.maxDistance = this.maxDistance;
  48577. this._soundPanner.refDistance = this.refDistance;
  48578. this._soundPanner.rolloffFactor = this.rolloffFactor;
  48579. this._soundPanner.panningModel = this._panningModel;
  48580. }
  48581. }
  48582. };
  48583. Sound.prototype.switchPanningModelToHRTF = function () {
  48584. this._panningModel = "HRTF";
  48585. this._switchPanningModel();
  48586. };
  48587. Sound.prototype.switchPanningModelToEqualPower = function () {
  48588. this._panningModel = "equalpower";
  48589. this._switchPanningModel();
  48590. };
  48591. Sound.prototype._switchPanningModel = function () {
  48592. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48593. this._soundPanner.panningModel = this._panningModel;
  48594. }
  48595. };
  48596. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  48597. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48598. if (this._isOutputConnected) {
  48599. this._ouputAudioNode.disconnect();
  48600. }
  48601. this._ouputAudioNode.connect(soundTrackAudioNode);
  48602. this._isOutputConnected = true;
  48603. }
  48604. };
  48605. /**
  48606. * Transform this sound into a directional source
  48607. * @param coneInnerAngle Size of the inner cone in degree
  48608. * @param coneOuterAngle Size of the outer cone in degree
  48609. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  48610. */
  48611. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  48612. if (coneOuterAngle < coneInnerAngle) {
  48613. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  48614. return;
  48615. }
  48616. this._coneInnerAngle = coneInnerAngle;
  48617. this._coneOuterAngle = coneOuterAngle;
  48618. this._coneOuterGain = coneOuterGain;
  48619. this._isDirectional = true;
  48620. if (this.isPlaying && this.loop) {
  48621. this.stop();
  48622. this.play();
  48623. }
  48624. };
  48625. Sound.prototype.setPosition = function (newPosition) {
  48626. this._position = newPosition;
  48627. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48628. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48629. }
  48630. };
  48631. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  48632. this._localDirection = newLocalDirection;
  48633. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  48634. this._updateDirection();
  48635. }
  48636. };
  48637. Sound.prototype._updateDirection = function () {
  48638. if (!this._connectedMesh || !this._soundPanner) {
  48639. return;
  48640. }
  48641. var mat = this._connectedMesh.getWorldMatrix();
  48642. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  48643. direction.normalize();
  48644. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  48645. };
  48646. Sound.prototype.updateDistanceFromListener = function () {
  48647. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  48648. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  48649. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  48650. }
  48651. };
  48652. Sound.prototype.setAttenuationFunction = function (callback) {
  48653. this._customAttenuationFunction = callback;
  48654. };
  48655. /**
  48656. * Play the sound
  48657. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  48658. * @param offset (optional) Start the sound setting it at a specific time
  48659. */
  48660. Sound.prototype.play = function (time, offset) {
  48661. var _this = this;
  48662. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  48663. try {
  48664. if (this._startOffset < 0) {
  48665. time = -this._startOffset;
  48666. this._startOffset = 0;
  48667. }
  48668. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48669. if (!this._soundSource || !this._streamingSource) {
  48670. if (this.spatialSound && this._soundPanner) {
  48671. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48672. if (this._isDirectional) {
  48673. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  48674. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  48675. this._soundPanner.coneOuterGain = this._coneOuterGain;
  48676. if (this._connectedMesh) {
  48677. this._updateDirection();
  48678. }
  48679. else {
  48680. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  48681. }
  48682. }
  48683. }
  48684. }
  48685. if (this._streaming) {
  48686. if (!this._streamingSource) {
  48687. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  48688. this._htmlAudioElement.onended = function () { _this._onended(); };
  48689. this._htmlAudioElement.playbackRate = this._playbackRate;
  48690. }
  48691. this._streamingSource.disconnect();
  48692. this._streamingSource.connect(this._inputAudioNode);
  48693. this._htmlAudioElement.play();
  48694. }
  48695. else {
  48696. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  48697. this._soundSource.buffer = this._audioBuffer;
  48698. this._soundSource.connect(this._inputAudioNode);
  48699. this._soundSource.loop = this.loop;
  48700. this._soundSource.playbackRate.value = this._playbackRate;
  48701. this._soundSource.onended = function () { _this._onended(); };
  48702. if (this._soundSource.buffer) {
  48703. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  48704. }
  48705. }
  48706. this._startTime = startTime;
  48707. this.isPlaying = true;
  48708. this.isPaused = false;
  48709. }
  48710. catch (ex) {
  48711. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  48712. }
  48713. }
  48714. };
  48715. Sound.prototype._onended = function () {
  48716. this.isPlaying = false;
  48717. if (this.onended) {
  48718. this.onended();
  48719. }
  48720. };
  48721. /**
  48722. * Stop the sound
  48723. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  48724. */
  48725. Sound.prototype.stop = function (time) {
  48726. if (this.isPlaying) {
  48727. if (this._streaming) {
  48728. this._htmlAudioElement.pause();
  48729. // Test needed for Firefox or it will generate an Invalid State Error
  48730. if (this._htmlAudioElement.currentTime > 0) {
  48731. this._htmlAudioElement.currentTime = 0;
  48732. }
  48733. }
  48734. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  48735. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48736. this._soundSource.stop(stopTime);
  48737. this._soundSource.onended = function () { };
  48738. if (!this.isPaused) {
  48739. this._startOffset = 0;
  48740. }
  48741. }
  48742. this.isPlaying = false;
  48743. }
  48744. };
  48745. Sound.prototype.pause = function () {
  48746. if (this.isPlaying) {
  48747. this.isPaused = true;
  48748. if (this._streaming) {
  48749. this._htmlAudioElement.pause();
  48750. }
  48751. else if (BABYLON.Engine.audioEngine.audioContext) {
  48752. this.stop(0);
  48753. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  48754. }
  48755. }
  48756. };
  48757. Sound.prototype.setVolume = function (newVolume, time) {
  48758. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  48759. if (time && BABYLON.Engine.audioEngine.audioContext) {
  48760. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  48761. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  48762. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  48763. }
  48764. else {
  48765. this._soundGain.gain.value = newVolume;
  48766. }
  48767. }
  48768. this._volume = newVolume;
  48769. };
  48770. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  48771. this._playbackRate = newPlaybackRate;
  48772. if (this.isPlaying) {
  48773. if (this._streaming) {
  48774. this._htmlAudioElement.playbackRate = this._playbackRate;
  48775. }
  48776. else if (this._soundSource) {
  48777. this._soundSource.playbackRate.value = this._playbackRate;
  48778. }
  48779. }
  48780. };
  48781. Sound.prototype.getVolume = function () {
  48782. return this._volume;
  48783. };
  48784. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  48785. var _this = this;
  48786. if (this._connectedMesh && this._registerFunc) {
  48787. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48788. this._registerFunc = null;
  48789. }
  48790. this._connectedMesh = meshToConnectTo;
  48791. if (!this.spatialSound) {
  48792. this.spatialSound = true;
  48793. this._createSpatialParameters();
  48794. if (this.isPlaying && this.loop) {
  48795. this.stop();
  48796. this.play();
  48797. }
  48798. }
  48799. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  48800. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  48801. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  48802. };
  48803. Sound.prototype.detachFromMesh = function () {
  48804. if (this._connectedMesh && this._registerFunc) {
  48805. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48806. this._registerFunc = null;
  48807. this._connectedMesh = null;
  48808. }
  48809. };
  48810. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  48811. var boundingInfo = connectedMesh.getBoundingInfo();
  48812. if (!boundingInfo) {
  48813. return;
  48814. }
  48815. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  48816. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  48817. this._updateDirection();
  48818. }
  48819. };
  48820. Sound.prototype.clone = function () {
  48821. var _this = this;
  48822. if (!this._streaming) {
  48823. var setBufferAndRun = function () {
  48824. if (_this._isReadyToPlay) {
  48825. clonedSound._audioBuffer = _this.getAudioBuffer();
  48826. clonedSound._isReadyToPlay = true;
  48827. if (clonedSound.autoplay) {
  48828. clonedSound.play();
  48829. }
  48830. }
  48831. else {
  48832. window.setTimeout(setBufferAndRun, 300);
  48833. }
  48834. };
  48835. var currentOptions = {
  48836. autoplay: this.autoplay, loop: this.loop,
  48837. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  48838. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  48839. refDistance: this.refDistance, distanceModel: this.distanceModel
  48840. };
  48841. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  48842. if (this.useCustomAttenuation) {
  48843. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  48844. }
  48845. clonedSound.setPosition(this._position);
  48846. clonedSound.setPlaybackRate(this._playbackRate);
  48847. setBufferAndRun();
  48848. return clonedSound;
  48849. }
  48850. else {
  48851. return null;
  48852. }
  48853. };
  48854. Sound.prototype.getAudioBuffer = function () {
  48855. return this._audioBuffer;
  48856. };
  48857. Sound.prototype.serialize = function () {
  48858. var serializationObject = {
  48859. name: this.name,
  48860. url: this.name,
  48861. autoplay: this.autoplay,
  48862. loop: this.loop,
  48863. volume: this._volume,
  48864. spatialSound: this.spatialSound,
  48865. maxDistance: this.maxDistance,
  48866. rolloffFactor: this.rolloffFactor,
  48867. refDistance: this.refDistance,
  48868. distanceModel: this.distanceModel,
  48869. playbackRate: this._playbackRate,
  48870. panningModel: this._panningModel,
  48871. soundTrackId: this.soundTrackId
  48872. };
  48873. if (this.spatialSound) {
  48874. if (this._connectedMesh)
  48875. serializationObject.connectedMeshId = this._connectedMesh.id;
  48876. serializationObject.position = this._position.asArray();
  48877. serializationObject.refDistance = this.refDistance;
  48878. serializationObject.distanceModel = this.distanceModel;
  48879. serializationObject.isDirectional = this._isDirectional;
  48880. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  48881. serializationObject.coneInnerAngle = this._coneInnerAngle;
  48882. serializationObject.coneOuterAngle = this._coneOuterAngle;
  48883. serializationObject.coneOuterGain = this._coneOuterGain;
  48884. }
  48885. return serializationObject;
  48886. };
  48887. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  48888. var soundName = parsedSound.name;
  48889. var soundUrl;
  48890. if (parsedSound.url) {
  48891. soundUrl = rootUrl + parsedSound.url;
  48892. }
  48893. else {
  48894. soundUrl = rootUrl + soundName;
  48895. }
  48896. var options = {
  48897. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  48898. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  48899. rolloffFactor: parsedSound.rolloffFactor,
  48900. refDistance: parsedSound.refDistance,
  48901. distanceModel: parsedSound.distanceModel,
  48902. playbackRate: parsedSound.playbackRate
  48903. };
  48904. var newSound;
  48905. if (!sourceSound) {
  48906. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  48907. scene._addPendingData(newSound);
  48908. }
  48909. else {
  48910. var setBufferAndRun = function () {
  48911. if (sourceSound._isReadyToPlay) {
  48912. newSound._audioBuffer = sourceSound.getAudioBuffer();
  48913. newSound._isReadyToPlay = true;
  48914. if (newSound.autoplay) {
  48915. newSound.play();
  48916. }
  48917. }
  48918. else {
  48919. window.setTimeout(setBufferAndRun, 300);
  48920. }
  48921. };
  48922. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  48923. setBufferAndRun();
  48924. }
  48925. if (parsedSound.position) {
  48926. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  48927. newSound.setPosition(soundPosition);
  48928. }
  48929. if (parsedSound.isDirectional) {
  48930. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  48931. if (parsedSound.localDirectionToMesh) {
  48932. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  48933. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  48934. }
  48935. }
  48936. if (parsedSound.connectedMeshId) {
  48937. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  48938. if (connectedMesh) {
  48939. newSound.attachToMesh(connectedMesh);
  48940. }
  48941. }
  48942. return newSound;
  48943. };
  48944. return Sound;
  48945. }());
  48946. BABYLON.Sound = Sound;
  48947. })(BABYLON || (BABYLON = {}));
  48948. //# sourceMappingURL=babylon.sound.js.map
  48949. var BABYLON;
  48950. (function (BABYLON) {
  48951. var SoundTrack = /** @class */ (function () {
  48952. function SoundTrack(scene, options) {
  48953. this.id = -1;
  48954. this._isMainTrack = false;
  48955. this._isInitialized = false;
  48956. this._scene = scene;
  48957. this.soundCollection = new Array();
  48958. this._options = options;
  48959. if (!this._isMainTrack) {
  48960. this._scene.soundTracks.push(this);
  48961. this.id = this._scene.soundTracks.length - 1;
  48962. }
  48963. }
  48964. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  48965. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48966. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  48967. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  48968. if (this._options) {
  48969. if (this._options.volume) {
  48970. this._outputAudioNode.gain.value = this._options.volume;
  48971. }
  48972. if (this._options.mainTrack) {
  48973. this._isMainTrack = this._options.mainTrack;
  48974. }
  48975. }
  48976. this._isInitialized = true;
  48977. }
  48978. };
  48979. SoundTrack.prototype.dispose = function () {
  48980. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48981. if (this._connectedAnalyser) {
  48982. this._connectedAnalyser.stopDebugCanvas();
  48983. }
  48984. while (this.soundCollection.length) {
  48985. this.soundCollection[0].dispose();
  48986. }
  48987. if (this._outputAudioNode) {
  48988. this._outputAudioNode.disconnect();
  48989. }
  48990. this._outputAudioNode = null;
  48991. }
  48992. };
  48993. SoundTrack.prototype.AddSound = function (sound) {
  48994. if (!this._isInitialized) {
  48995. this._initializeSoundTrackAudioGraph();
  48996. }
  48997. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48998. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  48999. }
  49000. if (sound.soundTrackId) {
  49001. if (sound.soundTrackId === -1) {
  49002. this._scene.mainSoundTrack.RemoveSound(sound);
  49003. }
  49004. else {
  49005. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  49006. }
  49007. }
  49008. this.soundCollection.push(sound);
  49009. sound.soundTrackId = this.id;
  49010. };
  49011. SoundTrack.prototype.RemoveSound = function (sound) {
  49012. var index = this.soundCollection.indexOf(sound);
  49013. if (index !== -1) {
  49014. this.soundCollection.splice(index, 1);
  49015. }
  49016. };
  49017. SoundTrack.prototype.setVolume = function (newVolume) {
  49018. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49019. this._outputAudioNode.gain.value = newVolume;
  49020. }
  49021. };
  49022. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  49023. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49024. for (var i = 0; i < this.soundCollection.length; i++) {
  49025. this.soundCollection[i].switchPanningModelToHRTF();
  49026. }
  49027. }
  49028. };
  49029. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  49030. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49031. for (var i = 0; i < this.soundCollection.length; i++) {
  49032. this.soundCollection[i].switchPanningModelToEqualPower();
  49033. }
  49034. }
  49035. };
  49036. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  49037. if (this._connectedAnalyser) {
  49038. this._connectedAnalyser.stopDebugCanvas();
  49039. }
  49040. this._connectedAnalyser = analyser;
  49041. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49042. this._outputAudioNode.disconnect();
  49043. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  49044. }
  49045. };
  49046. return SoundTrack;
  49047. }());
  49048. BABYLON.SoundTrack = SoundTrack;
  49049. })(BABYLON || (BABYLON = {}));
  49050. //# sourceMappingURL=babylon.soundtrack.js.map
  49051. var BABYLON;
  49052. (function (BABYLON) {
  49053. var Analyser = /** @class */ (function () {
  49054. function Analyser(scene) {
  49055. this.SMOOTHING = 0.75;
  49056. this.FFT_SIZE = 512;
  49057. this.BARGRAPHAMPLITUDE = 256;
  49058. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  49059. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  49060. this._scene = scene;
  49061. this._audioEngine = BABYLON.Engine.audioEngine;
  49062. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  49063. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  49064. this._webAudioAnalyser.minDecibels = -140;
  49065. this._webAudioAnalyser.maxDecibels = 0;
  49066. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49067. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49068. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49069. }
  49070. }
  49071. Analyser.prototype.getFrequencyBinCount = function () {
  49072. if (this._audioEngine.canUseWebAudio) {
  49073. return this._webAudioAnalyser.frequencyBinCount;
  49074. }
  49075. else {
  49076. return 0;
  49077. }
  49078. };
  49079. Analyser.prototype.getByteFrequencyData = function () {
  49080. if (this._audioEngine.canUseWebAudio) {
  49081. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49082. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49083. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49084. }
  49085. return this._byteFreqs;
  49086. };
  49087. Analyser.prototype.getByteTimeDomainData = function () {
  49088. if (this._audioEngine.canUseWebAudio) {
  49089. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49090. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49091. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49092. }
  49093. return this._byteTime;
  49094. };
  49095. Analyser.prototype.getFloatFrequencyData = function () {
  49096. if (this._audioEngine.canUseWebAudio) {
  49097. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49098. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49099. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49100. }
  49101. return this._floatFreqs;
  49102. };
  49103. Analyser.prototype.drawDebugCanvas = function () {
  49104. var _this = this;
  49105. if (this._audioEngine.canUseWebAudio) {
  49106. if (!this._debugCanvas) {
  49107. this._debugCanvas = document.createElement("canvas");
  49108. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49109. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49110. this._debugCanvas.style.position = "absolute";
  49111. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49112. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49113. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49114. document.body.appendChild(this._debugCanvas);
  49115. this._registerFunc = function () {
  49116. _this.drawDebugCanvas();
  49117. };
  49118. this._scene.registerBeforeRender(this._registerFunc);
  49119. }
  49120. if (this._registerFunc && this._debugCanvasContext) {
  49121. var workingArray = this.getByteFrequencyData();
  49122. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49123. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49124. // Draw the frequency domain chart.
  49125. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49126. var value = workingArray[i];
  49127. var percent = value / this.BARGRAPHAMPLITUDE;
  49128. var height = this.DEBUGCANVASSIZE.height * percent;
  49129. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49130. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49131. var hue = i / this.getFrequencyBinCount() * 360;
  49132. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49133. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49134. }
  49135. }
  49136. }
  49137. };
  49138. Analyser.prototype.stopDebugCanvas = function () {
  49139. if (this._debugCanvas) {
  49140. if (this._registerFunc) {
  49141. this._scene.unregisterBeforeRender(this._registerFunc);
  49142. this._registerFunc = null;
  49143. }
  49144. document.body.removeChild(this._debugCanvas);
  49145. this._debugCanvas = null;
  49146. this._debugCanvasContext = null;
  49147. }
  49148. };
  49149. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49150. if (this._audioEngine.canUseWebAudio) {
  49151. inputAudioNode.connect(this._webAudioAnalyser);
  49152. this._webAudioAnalyser.connect(outputAudioNode);
  49153. }
  49154. };
  49155. Analyser.prototype.dispose = function () {
  49156. if (this._audioEngine.canUseWebAudio) {
  49157. this._webAudioAnalyser.disconnect();
  49158. }
  49159. };
  49160. return Analyser;
  49161. }());
  49162. BABYLON.Analyser = Analyser;
  49163. })(BABYLON || (BABYLON = {}));
  49164. //# sourceMappingURL=babylon.analyser.js.map
  49165. var BABYLON;
  49166. (function (BABYLON) {
  49167. var CubeTexture = /** @class */ (function (_super) {
  49168. __extends(CubeTexture, _super);
  49169. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  49170. if (extensions === void 0) { extensions = null; }
  49171. if (noMipmap === void 0) { noMipmap = false; }
  49172. if (files === void 0) { files = null; }
  49173. if (onLoad === void 0) { onLoad = null; }
  49174. if (onError === void 0) { onError = null; }
  49175. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49176. if (prefiltered === void 0) { prefiltered = false; }
  49177. if (forcedExtension === void 0) { forcedExtension = null; }
  49178. var _this = _super.call(this, scene) || this;
  49179. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49180. _this.name = rootUrl;
  49181. _this.url = rootUrl;
  49182. _this._noMipmap = noMipmap;
  49183. _this.hasAlpha = false;
  49184. _this._format = format;
  49185. _this._prefiltered = prefiltered;
  49186. _this.isCube = true;
  49187. _this._textureMatrix = BABYLON.Matrix.Identity();
  49188. if (prefiltered) {
  49189. _this.gammaSpace = false;
  49190. }
  49191. if (!rootUrl && !files) {
  49192. return _this;
  49193. }
  49194. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  49195. if (!files) {
  49196. if (!extensions) {
  49197. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  49198. }
  49199. files = [];
  49200. for (var index = 0; index < extensions.length; index++) {
  49201. files.push(rootUrl + extensions[index]);
  49202. }
  49203. _this._extensions = extensions;
  49204. }
  49205. _this._files = files;
  49206. if (!_this._texture) {
  49207. if (!scene.useDelayedTextureLoading) {
  49208. if (prefiltered) {
  49209. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  49210. }
  49211. else {
  49212. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  49213. }
  49214. }
  49215. else {
  49216. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49217. }
  49218. }
  49219. else if (onLoad) {
  49220. if (_this._texture.isReady) {
  49221. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  49222. }
  49223. else {
  49224. _this._texture.onLoadedObservable.add(onLoad);
  49225. }
  49226. }
  49227. return _this;
  49228. }
  49229. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  49230. return new CubeTexture("", scene, null, noMipmap, files);
  49231. };
  49232. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  49233. if (forcedExtension === void 0) { forcedExtension = null; }
  49234. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  49235. };
  49236. // Methods
  49237. CubeTexture.prototype.delayLoad = function () {
  49238. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49239. return;
  49240. }
  49241. var scene = this.getScene();
  49242. if (!scene) {
  49243. return;
  49244. }
  49245. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49246. this._texture = this._getFromCache(this.url, this._noMipmap);
  49247. if (!this._texture) {
  49248. if (this._prefiltered) {
  49249. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49250. }
  49251. else {
  49252. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49253. }
  49254. }
  49255. };
  49256. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49257. return this._textureMatrix;
  49258. };
  49259. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49260. this._textureMatrix = value;
  49261. };
  49262. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49263. var texture = BABYLON.SerializationHelper.Parse(function () {
  49264. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49265. }, parsedTexture, scene);
  49266. // Animations
  49267. if (parsedTexture.animations) {
  49268. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49269. var parsedAnimation = parsedTexture.animations[animationIndex];
  49270. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49271. }
  49272. }
  49273. return texture;
  49274. };
  49275. CubeTexture.prototype.clone = function () {
  49276. var _this = this;
  49277. return BABYLON.SerializationHelper.Clone(function () {
  49278. var scene = _this.getScene();
  49279. if (!scene) {
  49280. return _this;
  49281. }
  49282. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49283. }, this);
  49284. };
  49285. return CubeTexture;
  49286. }(BABYLON.BaseTexture));
  49287. BABYLON.CubeTexture = CubeTexture;
  49288. })(BABYLON || (BABYLON = {}));
  49289. //# sourceMappingURL=babylon.cubeTexture.js.map
  49290. var BABYLON;
  49291. (function (BABYLON) {
  49292. var RenderTargetTexture = /** @class */ (function (_super) {
  49293. __extends(RenderTargetTexture, _super);
  49294. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49295. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49296. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49297. if (isCube === void 0) { isCube = false; }
  49298. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49299. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49300. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49301. if (isMulti === void 0) { isMulti = false; }
  49302. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49303. _this.isCube = isCube;
  49304. /**
  49305. * Use this list to define the list of mesh you want to render.
  49306. */
  49307. _this.renderList = new Array();
  49308. _this.renderParticles = true;
  49309. _this.renderSprites = false;
  49310. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49311. _this.ignoreCameraViewport = false;
  49312. // Events
  49313. /**
  49314. * An event triggered when the texture is unbind.
  49315. * @type {BABYLON.Observable}
  49316. */
  49317. _this.onBeforeBindObservable = new BABYLON.Observable();
  49318. /**
  49319. * An event triggered when the texture is unbind.
  49320. * @type {BABYLON.Observable}
  49321. */
  49322. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49323. /**
  49324. * An event triggered before rendering the texture
  49325. * @type {BABYLON.Observable}
  49326. */
  49327. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49328. /**
  49329. * An event triggered after rendering the texture
  49330. * @type {BABYLON.Observable}
  49331. */
  49332. _this.onAfterRenderObservable = new BABYLON.Observable();
  49333. /**
  49334. * An event triggered after the texture clear
  49335. * @type {BABYLON.Observable}
  49336. */
  49337. _this.onClearObservable = new BABYLON.Observable();
  49338. _this._currentRefreshId = -1;
  49339. _this._refreshRate = 1;
  49340. _this._samples = 1;
  49341. scene = _this.getScene();
  49342. if (!scene) {
  49343. return _this;
  49344. }
  49345. _this._engine = scene.getEngine();
  49346. _this.name = name;
  49347. _this.isRenderTarget = true;
  49348. _this._initialSizeParameter = size;
  49349. _this._processSizeParameter(size);
  49350. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  49351. });
  49352. _this._generateMipMaps = generateMipMaps ? true : false;
  49353. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49354. // Rendering groups
  49355. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49356. if (isMulti) {
  49357. return _this;
  49358. }
  49359. _this._renderTargetOptions = {
  49360. generateMipMaps: generateMipMaps,
  49361. type: type,
  49362. samplingMode: samplingMode,
  49363. generateDepthBuffer: generateDepthBuffer,
  49364. generateStencilBuffer: generateStencilBuffer
  49365. };
  49366. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49367. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49368. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49369. }
  49370. if (isCube) {
  49371. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  49372. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49373. _this._textureMatrix = BABYLON.Matrix.Identity();
  49374. }
  49375. else {
  49376. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  49377. }
  49378. return _this;
  49379. }
  49380. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49381. get: function () {
  49382. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49383. },
  49384. enumerable: true,
  49385. configurable: true
  49386. });
  49387. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49388. get: function () {
  49389. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49390. },
  49391. enumerable: true,
  49392. configurable: true
  49393. });
  49394. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49395. get: function () {
  49396. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49397. },
  49398. enumerable: true,
  49399. configurable: true
  49400. });
  49401. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49402. set: function (callback) {
  49403. if (this._onAfterUnbindObserver) {
  49404. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49405. }
  49406. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49407. },
  49408. enumerable: true,
  49409. configurable: true
  49410. });
  49411. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  49412. set: function (callback) {
  49413. if (this._onBeforeRenderObserver) {
  49414. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49415. }
  49416. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49417. },
  49418. enumerable: true,
  49419. configurable: true
  49420. });
  49421. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49422. set: function (callback) {
  49423. if (this._onAfterRenderObserver) {
  49424. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49425. }
  49426. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49427. },
  49428. enumerable: true,
  49429. configurable: true
  49430. });
  49431. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  49432. set: function (callback) {
  49433. if (this._onClearObserver) {
  49434. this.onClearObservable.remove(this._onClearObserver);
  49435. }
  49436. this._onClearObserver = this.onClearObservable.add(callback);
  49437. },
  49438. enumerable: true,
  49439. configurable: true
  49440. });
  49441. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  49442. get: function () {
  49443. return this._renderTargetOptions;
  49444. },
  49445. enumerable: true,
  49446. configurable: true
  49447. });
  49448. RenderTargetTexture.prototype._onRatioRescale = function () {
  49449. if (this._sizeRatio) {
  49450. this.resize(this._initialSizeParameter);
  49451. }
  49452. };
  49453. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  49454. if (size.ratio) {
  49455. this._sizeRatio = size.ratio;
  49456. this._size = {
  49457. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  49458. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  49459. };
  49460. }
  49461. else {
  49462. this._size = size;
  49463. }
  49464. };
  49465. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  49466. get: function () {
  49467. return this._samples;
  49468. },
  49469. set: function (value) {
  49470. if (this._samples === value) {
  49471. return;
  49472. }
  49473. var scene = this.getScene();
  49474. if (!scene) {
  49475. return;
  49476. }
  49477. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  49478. },
  49479. enumerable: true,
  49480. configurable: true
  49481. });
  49482. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  49483. this._currentRefreshId = -1;
  49484. };
  49485. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  49486. get: function () {
  49487. return this._refreshRate;
  49488. },
  49489. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49490. set: function (value) {
  49491. this._refreshRate = value;
  49492. this.resetRefreshCounter();
  49493. },
  49494. enumerable: true,
  49495. configurable: true
  49496. });
  49497. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  49498. if (!this._postProcessManager) {
  49499. var scene = this.getScene();
  49500. if (!scene) {
  49501. return;
  49502. }
  49503. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  49504. this._postProcesses = new Array();
  49505. }
  49506. this._postProcesses.push(postProcess);
  49507. this._postProcesses[0].autoClear = false;
  49508. };
  49509. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  49510. if (!this._postProcesses) {
  49511. return;
  49512. }
  49513. if (dispose) {
  49514. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  49515. var postProcess = _a[_i];
  49516. postProcess.dispose();
  49517. }
  49518. }
  49519. this._postProcesses = [];
  49520. };
  49521. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  49522. if (!this._postProcesses) {
  49523. return;
  49524. }
  49525. var index = this._postProcesses.indexOf(postProcess);
  49526. if (index === -1) {
  49527. return;
  49528. }
  49529. this._postProcesses.splice(index, 1);
  49530. if (this._postProcesses.length > 0) {
  49531. this._postProcesses[0].autoClear = false;
  49532. }
  49533. };
  49534. RenderTargetTexture.prototype._shouldRender = function () {
  49535. if (this._currentRefreshId === -1) {
  49536. this._currentRefreshId = 1;
  49537. return true;
  49538. }
  49539. if (this.refreshRate === this._currentRefreshId) {
  49540. this._currentRefreshId = 1;
  49541. return true;
  49542. }
  49543. this._currentRefreshId++;
  49544. return false;
  49545. };
  49546. RenderTargetTexture.prototype.getRenderSize = function () {
  49547. if (this._size.width) {
  49548. return this._size.width;
  49549. }
  49550. return this._size;
  49551. };
  49552. RenderTargetTexture.prototype.getRenderWidth = function () {
  49553. if (this._size.width) {
  49554. return this._size.width;
  49555. }
  49556. return this._size;
  49557. };
  49558. RenderTargetTexture.prototype.getRenderHeight = function () {
  49559. if (this._size.width) {
  49560. return this._size.height;
  49561. }
  49562. return this._size;
  49563. };
  49564. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  49565. get: function () {
  49566. return true;
  49567. },
  49568. enumerable: true,
  49569. configurable: true
  49570. });
  49571. RenderTargetTexture.prototype.scale = function (ratio) {
  49572. var newSize = this.getRenderSize() * ratio;
  49573. this.resize(newSize);
  49574. };
  49575. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  49576. if (this.isCube) {
  49577. return this._textureMatrix;
  49578. }
  49579. return _super.prototype.getReflectionTextureMatrix.call(this);
  49580. };
  49581. RenderTargetTexture.prototype.resize = function (size) {
  49582. this.releaseInternalTexture();
  49583. var scene = this.getScene();
  49584. if (!scene) {
  49585. return;
  49586. }
  49587. this._processSizeParameter(size);
  49588. if (this.isCube) {
  49589. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  49590. }
  49591. else {
  49592. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  49593. }
  49594. };
  49595. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  49596. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  49597. if (dumpForDebug === void 0) { dumpForDebug = false; }
  49598. var scene = this.getScene();
  49599. if (!scene) {
  49600. return;
  49601. }
  49602. var engine = scene.getEngine();
  49603. if (this.useCameraPostProcesses !== undefined) {
  49604. useCameraPostProcess = this.useCameraPostProcesses;
  49605. }
  49606. if (this._waitingRenderList) {
  49607. this.renderList = [];
  49608. for (var index = 0; index < this._waitingRenderList.length; index++) {
  49609. var id = this._waitingRenderList[index];
  49610. var mesh_1 = scene.getMeshByID(id);
  49611. if (mesh_1) {
  49612. this.renderList.push(mesh_1);
  49613. }
  49614. }
  49615. delete this._waitingRenderList;
  49616. }
  49617. // Is predicate defined?
  49618. if (this.renderListPredicate) {
  49619. if (this.renderList) {
  49620. this.renderList.splice(0); // Clear previous renderList
  49621. }
  49622. else {
  49623. this.renderList = [];
  49624. }
  49625. var scene = this.getScene();
  49626. if (!scene) {
  49627. return;
  49628. }
  49629. var sceneMeshes = scene.meshes;
  49630. for (var index = 0; index < sceneMeshes.length; index++) {
  49631. var mesh = sceneMeshes[index];
  49632. if (this.renderListPredicate(mesh)) {
  49633. this.renderList.push(mesh);
  49634. }
  49635. }
  49636. }
  49637. this.onBeforeBindObservable.notifyObservers(this);
  49638. // Set custom projection.
  49639. // Needs to be before binding to prevent changing the aspect ratio.
  49640. var camera;
  49641. if (this.activeCamera) {
  49642. camera = this.activeCamera;
  49643. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  49644. if (this.activeCamera !== scene.activeCamera) {
  49645. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  49646. }
  49647. }
  49648. else {
  49649. camera = scene.activeCamera;
  49650. if (camera) {
  49651. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  49652. }
  49653. }
  49654. // Prepare renderingManager
  49655. this._renderingManager.reset();
  49656. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  49657. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  49658. var sceneRenderId = scene.getRenderId();
  49659. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  49660. var mesh = currentRenderList[meshIndex];
  49661. if (mesh) {
  49662. if (!mesh.isReady()) {
  49663. // Reset _currentRefreshId
  49664. this.resetRefreshCounter();
  49665. continue;
  49666. }
  49667. mesh._preActivateForIntermediateRendering(sceneRenderId);
  49668. var isMasked = void 0;
  49669. if (!this.renderList && camera) {
  49670. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  49671. }
  49672. else {
  49673. isMasked = false;
  49674. }
  49675. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  49676. mesh._activate(sceneRenderId);
  49677. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49678. var subMesh = mesh.subMeshes[subIndex];
  49679. scene._activeIndices.addCount(subMesh.indexCount, false);
  49680. this._renderingManager.dispatch(subMesh);
  49681. }
  49682. }
  49683. }
  49684. }
  49685. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  49686. var particleSystem = scene.particleSystems[particleIndex];
  49687. var emitter = particleSystem.emitter;
  49688. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  49689. continue;
  49690. }
  49691. if (currentRenderList.indexOf(emitter) >= 0) {
  49692. this._renderingManager.dispatchParticles(particleSystem);
  49693. }
  49694. }
  49695. if (this.isCube) {
  49696. for (var face = 0; face < 6; face++) {
  49697. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49698. scene.incrementRenderId();
  49699. scene.resetCachedMaterial();
  49700. }
  49701. }
  49702. else {
  49703. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49704. }
  49705. this.onAfterUnbindObservable.notifyObservers(this);
  49706. if (scene.activeCamera) {
  49707. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  49708. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  49709. }
  49710. engine.setViewport(scene.activeCamera.viewport);
  49711. }
  49712. scene.resetCachedMaterial();
  49713. };
  49714. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  49715. var minimum = 128;
  49716. var x = renderDimension * scale;
  49717. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  49718. // Ensure we don't exceed the render dimension (while staying POT)
  49719. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  49720. };
  49721. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  49722. var _this = this;
  49723. var scene = this.getScene();
  49724. if (!scene) {
  49725. return;
  49726. }
  49727. var engine = scene.getEngine();
  49728. if (!this._texture) {
  49729. return;
  49730. }
  49731. // Bind
  49732. if (this._postProcessManager) {
  49733. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  49734. }
  49735. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  49736. if (this._texture) {
  49737. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  49738. }
  49739. }
  49740. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  49741. // Clear
  49742. if (this.onClearObservable.hasObservers()) {
  49743. this.onClearObservable.notifyObservers(engine);
  49744. }
  49745. else {
  49746. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  49747. }
  49748. if (!this._doNotChangeAspectRatio) {
  49749. scene.updateTransformMatrix(true);
  49750. }
  49751. // Render
  49752. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  49753. if (this._postProcessManager) {
  49754. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  49755. }
  49756. else if (useCameraPostProcess) {
  49757. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  49758. }
  49759. if (!this._doNotChangeAspectRatio) {
  49760. scene.updateTransformMatrix(true);
  49761. }
  49762. // Dump ?
  49763. if (dumpForDebug) {
  49764. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  49765. }
  49766. // Unbind
  49767. if (!this.isCube || faceIndex === 5) {
  49768. if (this.isCube) {
  49769. if (faceIndex === 5) {
  49770. engine.generateMipMapsForCubemap(this._texture);
  49771. }
  49772. }
  49773. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  49774. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  49775. });
  49776. }
  49777. else {
  49778. this.onAfterRenderObservable.notifyObservers(faceIndex);
  49779. }
  49780. };
  49781. /**
  49782. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  49783. * This allowed control for front to back rendering or reversly depending of the special needs.
  49784. *
  49785. * @param renderingGroupId The rendering group id corresponding to its index
  49786. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  49787. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  49788. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  49789. */
  49790. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  49791. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  49792. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  49793. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  49794. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  49795. };
  49796. /**
  49797. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  49798. *
  49799. * @param renderingGroupId The rendering group id corresponding to its index
  49800. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  49801. */
  49802. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  49803. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  49804. };
  49805. RenderTargetTexture.prototype.clone = function () {
  49806. var textureSize = this.getSize();
  49807. 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);
  49808. // Base texture
  49809. newTexture.hasAlpha = this.hasAlpha;
  49810. newTexture.level = this.level;
  49811. // RenderTarget Texture
  49812. newTexture.coordinatesMode = this.coordinatesMode;
  49813. if (this.renderList) {
  49814. newTexture.renderList = this.renderList.slice(0);
  49815. }
  49816. return newTexture;
  49817. };
  49818. RenderTargetTexture.prototype.serialize = function () {
  49819. if (!this.name) {
  49820. return null;
  49821. }
  49822. var serializationObject = _super.prototype.serialize.call(this);
  49823. serializationObject.renderTargetSize = this.getRenderSize();
  49824. serializationObject.renderList = [];
  49825. if (this.renderList) {
  49826. for (var index = 0; index < this.renderList.length; index++) {
  49827. serializationObject.renderList.push(this.renderList[index].id);
  49828. }
  49829. }
  49830. return serializationObject;
  49831. };
  49832. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  49833. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  49834. var objBuffer = this.getInternalTexture();
  49835. var scene = this.getScene();
  49836. if (objBuffer && scene) {
  49837. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  49838. }
  49839. };
  49840. RenderTargetTexture.prototype.dispose = function () {
  49841. if (this._postProcessManager) {
  49842. this._postProcessManager.dispose();
  49843. this._postProcessManager = null;
  49844. }
  49845. this.clearPostProcesses(true);
  49846. if (this._resizeObserver) {
  49847. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  49848. this._resizeObserver = null;
  49849. }
  49850. this.renderList = null;
  49851. // Remove from custom render targets
  49852. var scene = this.getScene();
  49853. if (!scene) {
  49854. return;
  49855. }
  49856. var index = scene.customRenderTargets.indexOf(this);
  49857. if (index >= 0) {
  49858. scene.customRenderTargets.splice(index, 1);
  49859. }
  49860. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  49861. var camera = _a[_i];
  49862. index = camera.customRenderTargets.indexOf(this);
  49863. if (index >= 0) {
  49864. camera.customRenderTargets.splice(index, 1);
  49865. }
  49866. }
  49867. _super.prototype.dispose.call(this);
  49868. };
  49869. RenderTargetTexture.prototype._rebuild = function () {
  49870. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  49871. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  49872. }
  49873. if (this._postProcessManager) {
  49874. this._postProcessManager._rebuild();
  49875. }
  49876. };
  49877. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  49878. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  49879. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  49880. return RenderTargetTexture;
  49881. }(BABYLON.Texture));
  49882. BABYLON.RenderTargetTexture = RenderTargetTexture;
  49883. })(BABYLON || (BABYLON = {}));
  49884. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  49885. var BABYLON;
  49886. (function (BABYLON) {
  49887. ;
  49888. var MultiRenderTarget = /** @class */ (function (_super) {
  49889. __extends(MultiRenderTarget, _super);
  49890. function MultiRenderTarget(name, size, count, scene, options) {
  49891. var _this = this;
  49892. options = options || {};
  49893. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  49894. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  49895. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  49896. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  49897. _this._engine = scene.getEngine();
  49898. if (!_this.isSupported) {
  49899. _this.dispose();
  49900. return;
  49901. }
  49902. var types = [];
  49903. var samplingModes = [];
  49904. for (var i = 0; i < count; i++) {
  49905. if (options.types && options.types[i]) {
  49906. types.push(options.types[i]);
  49907. }
  49908. else {
  49909. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  49910. }
  49911. if (options.samplingModes && options.samplingModes[i]) {
  49912. samplingModes.push(options.samplingModes[i]);
  49913. }
  49914. else {
  49915. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49916. }
  49917. }
  49918. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  49919. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  49920. _this._count = count;
  49921. _this._size = size;
  49922. _this._multiRenderTargetOptions = {
  49923. samplingModes: samplingModes,
  49924. generateMipMaps: generateMipMaps,
  49925. generateDepthBuffer: generateDepthBuffer,
  49926. generateStencilBuffer: generateStencilBuffer,
  49927. generateDepthTexture: generateDepthTexture,
  49928. types: types,
  49929. textureCount: count
  49930. };
  49931. _this._createInternalTextures();
  49932. _this._createTextures();
  49933. return _this;
  49934. }
  49935. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  49936. get: function () {
  49937. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  49938. },
  49939. enumerable: true,
  49940. configurable: true
  49941. });
  49942. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  49943. get: function () {
  49944. return this._textures;
  49945. },
  49946. enumerable: true,
  49947. configurable: true
  49948. });
  49949. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  49950. get: function () {
  49951. return this._textures[this._textures.length - 1];
  49952. },
  49953. enumerable: true,
  49954. configurable: true
  49955. });
  49956. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  49957. set: function (wrap) {
  49958. if (this._textures) {
  49959. for (var i = 0; i < this._textures.length; i++) {
  49960. this._textures[i].wrapU = wrap;
  49961. }
  49962. }
  49963. },
  49964. enumerable: true,
  49965. configurable: true
  49966. });
  49967. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  49968. set: function (wrap) {
  49969. if (this._textures) {
  49970. for (var i = 0; i < this._textures.length; i++) {
  49971. this._textures[i].wrapV = wrap;
  49972. }
  49973. }
  49974. },
  49975. enumerable: true,
  49976. configurable: true
  49977. });
  49978. MultiRenderTarget.prototype._rebuild = function () {
  49979. this.releaseInternalTextures();
  49980. this._createInternalTextures();
  49981. for (var i = 0; i < this._internalTextures.length; i++) {
  49982. var texture = this._textures[i];
  49983. texture._texture = this._internalTextures[i];
  49984. }
  49985. // Keeps references to frame buffer and stencil/depth buffer
  49986. this._texture = this._internalTextures[0];
  49987. };
  49988. MultiRenderTarget.prototype._createInternalTextures = function () {
  49989. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  49990. };
  49991. MultiRenderTarget.prototype._createTextures = function () {
  49992. this._textures = [];
  49993. for (var i = 0; i < this._internalTextures.length; i++) {
  49994. var texture = new BABYLON.Texture(null, this.getScene());
  49995. texture._texture = this._internalTextures[i];
  49996. this._textures.push(texture);
  49997. }
  49998. // Keeps references to frame buffer and stencil/depth buffer
  49999. this._texture = this._internalTextures[0];
  50000. };
  50001. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  50002. get: function () {
  50003. return this._samples;
  50004. },
  50005. set: function (value) {
  50006. if (this._samples === value) {
  50007. return;
  50008. }
  50009. for (var i = 0; i < this._internalTextures.length; i++) {
  50010. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  50011. }
  50012. },
  50013. enumerable: true,
  50014. configurable: true
  50015. });
  50016. MultiRenderTarget.prototype.resize = function (size) {
  50017. this.releaseInternalTextures();
  50018. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  50019. this._createInternalTextures();
  50020. };
  50021. MultiRenderTarget.prototype.dispose = function () {
  50022. this.releaseInternalTextures();
  50023. _super.prototype.dispose.call(this);
  50024. };
  50025. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  50026. if (!this._internalTextures) {
  50027. return;
  50028. }
  50029. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  50030. if (this._internalTextures[i] !== undefined) {
  50031. this._internalTextures[i].dispose();
  50032. this._internalTextures.splice(i, 1);
  50033. }
  50034. }
  50035. };
  50036. return MultiRenderTarget;
  50037. }(BABYLON.RenderTargetTexture));
  50038. BABYLON.MultiRenderTarget = MultiRenderTarget;
  50039. })(BABYLON || (BABYLON = {}));
  50040. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  50041. var BABYLON;
  50042. (function (BABYLON) {
  50043. var MirrorTexture = /** @class */ (function (_super) {
  50044. __extends(MirrorTexture, _super);
  50045. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  50046. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50047. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50048. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50049. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  50050. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  50051. _this._transformMatrix = BABYLON.Matrix.Zero();
  50052. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  50053. _this._adaptiveBlurKernel = 0;
  50054. _this._blurKernelX = 0;
  50055. _this._blurKernelY = 0;
  50056. _this._blurRatio = 1.0;
  50057. _this.ignoreCameraViewport = true;
  50058. _this.onBeforeRenderObservable.add(function () {
  50059. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  50060. _this._savedViewMatrix = scene.getViewMatrix();
  50061. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  50062. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  50063. scene.clipPlane = _this.mirrorPlane;
  50064. scene.getEngine().cullBackFaces = false;
  50065. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  50066. });
  50067. _this.onAfterRenderObservable.add(function () {
  50068. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  50069. scene.getEngine().cullBackFaces = true;
  50070. scene._mirroredCameraPosition = null;
  50071. delete scene.clipPlane;
  50072. });
  50073. return _this;
  50074. }
  50075. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  50076. get: function () {
  50077. return this._blurRatio;
  50078. },
  50079. set: function (value) {
  50080. if (this._blurRatio === value) {
  50081. return;
  50082. }
  50083. this._blurRatio = value;
  50084. this._preparePostProcesses();
  50085. },
  50086. enumerable: true,
  50087. configurable: true
  50088. });
  50089. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  50090. set: function (value) {
  50091. this._adaptiveBlurKernel = value;
  50092. this._autoComputeBlurKernel();
  50093. },
  50094. enumerable: true,
  50095. configurable: true
  50096. });
  50097. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  50098. set: function (value) {
  50099. this.blurKernelX = value;
  50100. this.blurKernelY = value;
  50101. },
  50102. enumerable: true,
  50103. configurable: true
  50104. });
  50105. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  50106. get: function () {
  50107. return this._blurKernelX;
  50108. },
  50109. set: function (value) {
  50110. if (this._blurKernelX === value) {
  50111. return;
  50112. }
  50113. this._blurKernelX = value;
  50114. this._preparePostProcesses();
  50115. },
  50116. enumerable: true,
  50117. configurable: true
  50118. });
  50119. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  50120. get: function () {
  50121. return this._blurKernelY;
  50122. },
  50123. set: function (value) {
  50124. if (this._blurKernelY === value) {
  50125. return;
  50126. }
  50127. this._blurKernelY = value;
  50128. this._preparePostProcesses();
  50129. },
  50130. enumerable: true,
  50131. configurable: true
  50132. });
  50133. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  50134. var engine = this.getScene().getEngine();
  50135. var dw = this.getRenderWidth() / engine.getRenderWidth();
  50136. var dh = this.getRenderHeight() / engine.getRenderHeight();
  50137. this.blurKernelX = this._adaptiveBlurKernel * dw;
  50138. this.blurKernelY = this._adaptiveBlurKernel * dh;
  50139. };
  50140. MirrorTexture.prototype._onRatioRescale = function () {
  50141. if (this._sizeRatio) {
  50142. this.resize(this._initialSizeParameter);
  50143. if (!this._adaptiveBlurKernel) {
  50144. this._preparePostProcesses();
  50145. }
  50146. }
  50147. if (this._adaptiveBlurKernel) {
  50148. this._autoComputeBlurKernel();
  50149. }
  50150. };
  50151. MirrorTexture.prototype._preparePostProcesses = function () {
  50152. this.clearPostProcesses(true);
  50153. if (this._blurKernelX && this._blurKernelY) {
  50154. var engine = this.getScene().getEngine();
  50155. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50156. 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);
  50157. this._blurX.autoClear = false;
  50158. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  50159. this._blurX.outputTexture = this._texture;
  50160. }
  50161. else {
  50162. this._blurX.alwaysForcePOT = true;
  50163. }
  50164. 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);
  50165. this._blurY.autoClear = false;
  50166. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  50167. this.addPostProcess(this._blurX);
  50168. this.addPostProcess(this._blurY);
  50169. }
  50170. else {
  50171. if (this._blurY) {
  50172. this.removePostProcess(this._blurY);
  50173. this._blurY.dispose();
  50174. this._blurY = null;
  50175. }
  50176. if (this._blurX) {
  50177. this.removePostProcess(this._blurX);
  50178. this._blurX.dispose();
  50179. this._blurX = null;
  50180. }
  50181. }
  50182. };
  50183. MirrorTexture.prototype.clone = function () {
  50184. var scene = this.getScene();
  50185. if (!scene) {
  50186. return this;
  50187. }
  50188. var textureSize = this.getSize();
  50189. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  50190. // Base texture
  50191. newTexture.hasAlpha = this.hasAlpha;
  50192. newTexture.level = this.level;
  50193. // Mirror Texture
  50194. newTexture.mirrorPlane = this.mirrorPlane.clone();
  50195. if (this.renderList) {
  50196. newTexture.renderList = this.renderList.slice(0);
  50197. }
  50198. return newTexture;
  50199. };
  50200. MirrorTexture.prototype.serialize = function () {
  50201. if (!this.name) {
  50202. return null;
  50203. }
  50204. var serializationObject = _super.prototype.serialize.call(this);
  50205. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  50206. return serializationObject;
  50207. };
  50208. return MirrorTexture;
  50209. }(BABYLON.RenderTargetTexture));
  50210. BABYLON.MirrorTexture = MirrorTexture;
  50211. })(BABYLON || (BABYLON = {}));
  50212. //# sourceMappingURL=babylon.mirrorTexture.js.map
  50213. var BABYLON;
  50214. (function (BABYLON) {
  50215. /**
  50216. * Creates a refraction texture used by refraction channel of the standard material.
  50217. * @param name the texture name
  50218. * @param size size of the underlying texture
  50219. * @param scene root scene
  50220. */
  50221. var RefractionTexture = /** @class */ (function (_super) {
  50222. __extends(RefractionTexture, _super);
  50223. function RefractionTexture(name, size, scene, generateMipMaps) {
  50224. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  50225. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  50226. _this.depth = 2.0;
  50227. _this.onBeforeRenderObservable.add(function () {
  50228. scene.clipPlane = _this.refractionPlane;
  50229. });
  50230. _this.onAfterRenderObservable.add(function () {
  50231. delete scene.clipPlane;
  50232. });
  50233. return _this;
  50234. }
  50235. RefractionTexture.prototype.clone = function () {
  50236. var scene = this.getScene();
  50237. if (!scene) {
  50238. return this;
  50239. }
  50240. var textureSize = this.getSize();
  50241. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  50242. // Base texture
  50243. newTexture.hasAlpha = this.hasAlpha;
  50244. newTexture.level = this.level;
  50245. // Refraction Texture
  50246. newTexture.refractionPlane = this.refractionPlane.clone();
  50247. if (this.renderList) {
  50248. newTexture.renderList = this.renderList.slice(0);
  50249. }
  50250. newTexture.depth = this.depth;
  50251. return newTexture;
  50252. };
  50253. RefractionTexture.prototype.serialize = function () {
  50254. if (!this.name) {
  50255. return null;
  50256. }
  50257. var serializationObject = _super.prototype.serialize.call(this);
  50258. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  50259. serializationObject.depth = this.depth;
  50260. return serializationObject;
  50261. };
  50262. return RefractionTexture;
  50263. }(BABYLON.RenderTargetTexture));
  50264. BABYLON.RefractionTexture = RefractionTexture;
  50265. })(BABYLON || (BABYLON = {}));
  50266. //# sourceMappingURL=babylon.refractionTexture.js.map
  50267. var BABYLON;
  50268. (function (BABYLON) {
  50269. var DynamicTexture = /** @class */ (function (_super) {
  50270. __extends(DynamicTexture, _super);
  50271. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  50272. if (scene === void 0) { scene = null; }
  50273. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50274. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50275. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  50276. _this.name = name;
  50277. _this._engine = _this.getScene().getEngine();
  50278. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50279. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50280. _this._generateMipMaps = generateMipMaps;
  50281. if (options.getContext) {
  50282. _this._canvas = options;
  50283. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50284. }
  50285. else {
  50286. _this._canvas = document.createElement("canvas");
  50287. if (options.width) {
  50288. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50289. }
  50290. else {
  50291. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  50292. }
  50293. }
  50294. var textureSize = _this.getSize();
  50295. _this._canvas.width = textureSize.width;
  50296. _this._canvas.height = textureSize.height;
  50297. _this._context = _this._canvas.getContext("2d");
  50298. return _this;
  50299. }
  50300. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  50301. get: function () {
  50302. return true;
  50303. },
  50304. enumerable: true,
  50305. configurable: true
  50306. });
  50307. DynamicTexture.prototype._recreate = function (textureSize) {
  50308. this._canvas.width = textureSize.width;
  50309. this._canvas.height = textureSize.height;
  50310. this.releaseInternalTexture();
  50311. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  50312. };
  50313. DynamicTexture.prototype.scale = function (ratio) {
  50314. var textureSize = this.getSize();
  50315. textureSize.width *= ratio;
  50316. textureSize.height *= ratio;
  50317. this._recreate(textureSize);
  50318. };
  50319. DynamicTexture.prototype.scaleTo = function (width, height) {
  50320. var textureSize = this.getSize();
  50321. textureSize.width = width;
  50322. textureSize.height = height;
  50323. this._recreate(textureSize);
  50324. };
  50325. DynamicTexture.prototype.getContext = function () {
  50326. return this._context;
  50327. };
  50328. DynamicTexture.prototype.clear = function () {
  50329. var size = this.getSize();
  50330. this._context.fillRect(0, 0, size.width, size.height);
  50331. };
  50332. DynamicTexture.prototype.update = function (invertY) {
  50333. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50334. };
  50335. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50336. if (update === void 0) { update = true; }
  50337. var size = this.getSize();
  50338. if (clearColor) {
  50339. this._context.fillStyle = clearColor;
  50340. this._context.fillRect(0, 0, size.width, size.height);
  50341. }
  50342. this._context.font = font;
  50343. if (x === null || x === undefined) {
  50344. var textSize = this._context.measureText(text);
  50345. x = (size.width - textSize.width) / 2;
  50346. }
  50347. if (y === null || y === undefined) {
  50348. var fontSize = parseInt((font.replace(/\D/g, '')));
  50349. ;
  50350. y = (size.height / 2) + (fontSize / 3.65);
  50351. }
  50352. this._context.fillStyle = color;
  50353. this._context.fillText(text, x, y);
  50354. if (update) {
  50355. this.update(invertY);
  50356. }
  50357. };
  50358. DynamicTexture.prototype.clone = function () {
  50359. var scene = this.getScene();
  50360. if (!scene) {
  50361. return this;
  50362. }
  50363. var textureSize = this.getSize();
  50364. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50365. // Base texture
  50366. newTexture.hasAlpha = this.hasAlpha;
  50367. newTexture.level = this.level;
  50368. // Dynamic Texture
  50369. newTexture.wrapU = this.wrapU;
  50370. newTexture.wrapV = this.wrapV;
  50371. return newTexture;
  50372. };
  50373. DynamicTexture.prototype._rebuild = function () {
  50374. this.update();
  50375. };
  50376. return DynamicTexture;
  50377. }(BABYLON.Texture));
  50378. BABYLON.DynamicTexture = DynamicTexture;
  50379. })(BABYLON || (BABYLON = {}));
  50380. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50381. var BABYLON;
  50382. (function (BABYLON) {
  50383. var VideoTexture = /** @class */ (function (_super) {
  50384. __extends(VideoTexture, _super);
  50385. /**
  50386. * Creates a video texture.
  50387. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50388. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50389. * @param {BABYLON.Scene} scene is obviously the current scene.
  50390. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50391. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50392. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50393. */
  50394. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50395. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50396. if (invertY === void 0) { invertY = false; }
  50397. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50398. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50399. _this._autoLaunch = true;
  50400. var urls = null;
  50401. _this.name = name;
  50402. if (urlsOrVideo instanceof HTMLVideoElement) {
  50403. _this.video = urlsOrVideo;
  50404. }
  50405. else {
  50406. urls = urlsOrVideo;
  50407. _this.video = document.createElement("video");
  50408. _this.video.autoplay = false;
  50409. _this.video.loop = true;
  50410. }
  50411. _this._engine = _this.getScene().getEngine();
  50412. _this._generateMipMaps = generateMipMaps;
  50413. _this._samplingMode = samplingMode;
  50414. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  50415. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50416. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50417. }
  50418. else {
  50419. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50420. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50421. _this._generateMipMaps = false;
  50422. }
  50423. if (urls) {
  50424. _this.video.addEventListener("canplay", function () {
  50425. _this._createTexture();
  50426. });
  50427. urls.forEach(function (url) {
  50428. var source = document.createElement("source");
  50429. source.src = url;
  50430. _this.video.appendChild(source);
  50431. });
  50432. }
  50433. else {
  50434. _this._createTexture();
  50435. }
  50436. _this._lastUpdate = BABYLON.Tools.Now;
  50437. return _this;
  50438. }
  50439. VideoTexture.prototype.__setTextureReady = function () {
  50440. if (this._texture) {
  50441. this._texture.isReady = true;
  50442. }
  50443. };
  50444. VideoTexture.prototype._createTexture = function () {
  50445. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  50446. if (this._autoLaunch) {
  50447. this._autoLaunch = false;
  50448. this.video.play();
  50449. }
  50450. this._setTextureReady = this.__setTextureReady.bind(this);
  50451. this.video.addEventListener("playing", this._setTextureReady);
  50452. };
  50453. VideoTexture.prototype._rebuild = function () {
  50454. this.update();
  50455. };
  50456. VideoTexture.prototype.update = function () {
  50457. var now = BABYLON.Tools.Now;
  50458. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  50459. return false;
  50460. }
  50461. this._lastUpdate = now;
  50462. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  50463. return true;
  50464. };
  50465. VideoTexture.prototype.dispose = function () {
  50466. _super.prototype.dispose.call(this);
  50467. this.video.removeEventListener("playing", this._setTextureReady);
  50468. };
  50469. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  50470. var video = document.createElement("video");
  50471. var constraintsDeviceId;
  50472. if (constraints && constraints.deviceId) {
  50473. constraintsDeviceId = {
  50474. exact: constraints.deviceId
  50475. };
  50476. }
  50477. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  50478. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  50479. if (navigator.getUserMedia) {
  50480. navigator.getUserMedia({
  50481. video: {
  50482. deviceId: constraintsDeviceId,
  50483. width: {
  50484. min: (constraints && constraints.minWidth) || 256,
  50485. max: (constraints && constraints.maxWidth) || 640
  50486. },
  50487. height: {
  50488. min: (constraints && constraints.minHeight) || 256,
  50489. max: (constraints && constraints.maxHeight) || 480
  50490. }
  50491. }
  50492. }, function (stream) {
  50493. if (video.mozSrcObject !== undefined) {
  50494. video.mozSrcObject = stream;
  50495. }
  50496. else {
  50497. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  50498. }
  50499. video.play();
  50500. if (onReady) {
  50501. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  50502. }
  50503. }, function (e) {
  50504. BABYLON.Tools.Error(e.name);
  50505. });
  50506. }
  50507. };
  50508. return VideoTexture;
  50509. }(BABYLON.Texture));
  50510. BABYLON.VideoTexture = VideoTexture;
  50511. })(BABYLON || (BABYLON = {}));
  50512. //# sourceMappingURL=babylon.videoTexture.js.map
  50513. var BABYLON;
  50514. (function (BABYLON) {
  50515. var RawTexture = /** @class */ (function (_super) {
  50516. __extends(RawTexture, _super);
  50517. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50518. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50519. if (invertY === void 0) { invertY = false; }
  50520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50521. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50522. _this.format = format;
  50523. _this._engine = scene.getEngine();
  50524. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50525. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50526. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50527. return _this;
  50528. }
  50529. RawTexture.prototype.update = function (data) {
  50530. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  50531. };
  50532. // Statics
  50533. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50534. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50535. if (invertY === void 0) { invertY = false; }
  50536. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50537. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50538. };
  50539. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50540. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50541. if (invertY === void 0) { invertY = false; }
  50542. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50543. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50544. };
  50545. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50546. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50547. if (invertY === void 0) { invertY = false; }
  50548. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50549. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50550. };
  50551. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50552. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50553. if (invertY === void 0) { invertY = false; }
  50554. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50555. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50556. };
  50557. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50558. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50559. if (invertY === void 0) { invertY = false; }
  50560. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50561. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50562. };
  50563. return RawTexture;
  50564. }(BABYLON.Texture));
  50565. BABYLON.RawTexture = RawTexture;
  50566. })(BABYLON || (BABYLON = {}));
  50567. //# sourceMappingURL=babylon.rawTexture.js.map
  50568. var BABYLON;
  50569. (function (BABYLON) {
  50570. var PostProcess = /** @class */ (function () {
  50571. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  50572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  50573. if (defines === void 0) { defines = null; }
  50574. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50575. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  50576. if (blockCompilation === void 0) { blockCompilation = false; }
  50577. this.name = name;
  50578. this.width = -1;
  50579. this.height = -1;
  50580. this.autoClear = true;
  50581. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  50582. /*
  50583. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  50584. Can only be used on a single postprocess or on the last one of a chain.
  50585. */
  50586. this.enablePixelPerfectMode = false;
  50587. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  50588. this.alwaysForcePOT = false;
  50589. this.samples = 1;
  50590. this.adaptScaleToCurrentViewport = false;
  50591. this._reusable = false;
  50592. this._textures = new BABYLON.SmartArray(2);
  50593. this._currentRenderTextureInd = 0;
  50594. this._scaleRatio = new BABYLON.Vector2(1, 1);
  50595. this._texelSize = BABYLON.Vector2.Zero();
  50596. // Events
  50597. /**
  50598. * An event triggered when the postprocess is activated.
  50599. * @type {BABYLON.Observable}
  50600. */
  50601. this.onActivateObservable = new BABYLON.Observable();
  50602. /**
  50603. * An event triggered when the postprocess changes its size.
  50604. * @type {BABYLON.Observable}
  50605. */
  50606. this.onSizeChangedObservable = new BABYLON.Observable();
  50607. /**
  50608. * An event triggered when the postprocess applies its effect.
  50609. * @type {BABYLON.Observable}
  50610. */
  50611. this.onApplyObservable = new BABYLON.Observable();
  50612. /**
  50613. * An event triggered before rendering the postprocess
  50614. * @type {BABYLON.Observable}
  50615. */
  50616. this.onBeforeRenderObservable = new BABYLON.Observable();
  50617. /**
  50618. * An event triggered after rendering the postprocess
  50619. * @type {BABYLON.Observable}
  50620. */
  50621. this.onAfterRenderObservable = new BABYLON.Observable();
  50622. if (camera != null) {
  50623. this._camera = camera;
  50624. this._scene = camera.getScene();
  50625. camera.attachPostProcess(this);
  50626. this._engine = this._scene.getEngine();
  50627. this._scene.postProcesses.push(this);
  50628. }
  50629. else if (engine) {
  50630. this._engine = engine;
  50631. this._engine.postProcesses.push(this);
  50632. }
  50633. this._options = options;
  50634. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  50635. this._reusable = reusable || false;
  50636. this._textureType = textureType;
  50637. this._samplers = samplers || [];
  50638. this._samplers.push("textureSampler");
  50639. this._fragmentUrl = fragmentUrl;
  50640. this._vertexUrl = vertexUrl;
  50641. this._parameters = parameters || [];
  50642. this._parameters.push("scale");
  50643. this._indexParameters = indexParameters;
  50644. if (!blockCompilation) {
  50645. this.updateEffect(defines);
  50646. }
  50647. }
  50648. Object.defineProperty(PostProcess.prototype, "onActivate", {
  50649. set: function (callback) {
  50650. if (this._onActivateObserver) {
  50651. this.onActivateObservable.remove(this._onActivateObserver);
  50652. }
  50653. if (callback) {
  50654. this._onActivateObserver = this.onActivateObservable.add(callback);
  50655. }
  50656. },
  50657. enumerable: true,
  50658. configurable: true
  50659. });
  50660. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  50661. set: function (callback) {
  50662. if (this._onSizeChangedObserver) {
  50663. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  50664. }
  50665. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  50666. },
  50667. enumerable: true,
  50668. configurable: true
  50669. });
  50670. Object.defineProperty(PostProcess.prototype, "onApply", {
  50671. set: function (callback) {
  50672. if (this._onApplyObserver) {
  50673. this.onApplyObservable.remove(this._onApplyObserver);
  50674. }
  50675. this._onApplyObserver = this.onApplyObservable.add(callback);
  50676. },
  50677. enumerable: true,
  50678. configurable: true
  50679. });
  50680. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  50681. set: function (callback) {
  50682. if (this._onBeforeRenderObserver) {
  50683. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50684. }
  50685. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50686. },
  50687. enumerable: true,
  50688. configurable: true
  50689. });
  50690. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  50691. set: function (callback) {
  50692. if (this._onAfterRenderObserver) {
  50693. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50694. }
  50695. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50696. },
  50697. enumerable: true,
  50698. configurable: true
  50699. });
  50700. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  50701. get: function () {
  50702. return this._textures.data[this._currentRenderTextureInd];
  50703. },
  50704. set: function (value) {
  50705. this._forcedOutputTexture = value;
  50706. },
  50707. enumerable: true,
  50708. configurable: true
  50709. });
  50710. PostProcess.prototype.getCamera = function () {
  50711. return this._camera;
  50712. };
  50713. Object.defineProperty(PostProcess.prototype, "texelSize", {
  50714. get: function () {
  50715. if (this._shareOutputWithPostProcess) {
  50716. return this._shareOutputWithPostProcess.texelSize;
  50717. }
  50718. if (this._forcedOutputTexture) {
  50719. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  50720. }
  50721. return this._texelSize;
  50722. },
  50723. enumerable: true,
  50724. configurable: true
  50725. });
  50726. PostProcess.prototype.getEngine = function () {
  50727. return this._engine;
  50728. };
  50729. PostProcess.prototype.getEffect = function () {
  50730. return this._effect;
  50731. };
  50732. PostProcess.prototype.shareOutputWith = function (postProcess) {
  50733. this._disposeTextures();
  50734. this._shareOutputWithPostProcess = postProcess;
  50735. return this;
  50736. };
  50737. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  50738. if (defines === void 0) { defines = null; }
  50739. if (uniforms === void 0) { uniforms = null; }
  50740. if (samplers === void 0) { samplers = null; }
  50741. 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);
  50742. };
  50743. PostProcess.prototype.isReusable = function () {
  50744. return this._reusable;
  50745. };
  50746. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  50747. PostProcess.prototype.markTextureDirty = function () {
  50748. this.width = -1;
  50749. };
  50750. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  50751. var _this = this;
  50752. if (sourceTexture === void 0) { sourceTexture = null; }
  50753. camera = camera || this._camera;
  50754. var scene = camera.getScene();
  50755. var engine = scene.getEngine();
  50756. var maxSize = engine.getCaps().maxTextureSize;
  50757. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  50758. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  50759. var desiredWidth = (this._options.width || requiredWidth);
  50760. var desiredHeight = this._options.height || requiredHeight;
  50761. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  50762. if (this.adaptScaleToCurrentViewport) {
  50763. var currentViewport = engine.currentViewport;
  50764. if (currentViewport) {
  50765. desiredWidth *= currentViewport.width;
  50766. desiredHeight *= currentViewport.height;
  50767. }
  50768. }
  50769. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  50770. if (!this._options.width) {
  50771. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  50772. }
  50773. if (!this._options.height) {
  50774. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  50775. }
  50776. }
  50777. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  50778. if (this._textures.length > 0) {
  50779. for (var i = 0; i < this._textures.length; i++) {
  50780. this._engine._releaseTexture(this._textures.data[i]);
  50781. }
  50782. this._textures.reset();
  50783. }
  50784. this.width = desiredWidth;
  50785. this.height = desiredHeight;
  50786. var textureSize = { width: this.width, height: this.height };
  50787. var textureOptions = {
  50788. generateMipMaps: false,
  50789. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  50790. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  50791. samplingMode: this.renderTargetSamplingMode,
  50792. type: this._textureType
  50793. };
  50794. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50795. if (this._reusable) {
  50796. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50797. }
  50798. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  50799. this.onSizeChangedObservable.notifyObservers(this);
  50800. }
  50801. this._textures.forEach(function (texture) {
  50802. if (texture.samples !== _this.samples) {
  50803. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  50804. }
  50805. });
  50806. }
  50807. var target;
  50808. if (this._shareOutputWithPostProcess) {
  50809. target = this._shareOutputWithPostProcess.outputTexture;
  50810. }
  50811. else if (this._forcedOutputTexture) {
  50812. target = this._forcedOutputTexture;
  50813. this.width = this._forcedOutputTexture.width;
  50814. this.height = this._forcedOutputTexture.height;
  50815. }
  50816. else {
  50817. target = this.outputTexture;
  50818. }
  50819. if (this.enablePixelPerfectMode) {
  50820. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  50821. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  50822. }
  50823. else {
  50824. this._scaleRatio.copyFromFloats(1, 1);
  50825. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  50826. }
  50827. this.onActivateObservable.notifyObservers(camera);
  50828. // Clear
  50829. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  50830. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  50831. }
  50832. if (this._reusable) {
  50833. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  50834. }
  50835. };
  50836. Object.defineProperty(PostProcess.prototype, "isSupported", {
  50837. get: function () {
  50838. return this._effect.isSupported;
  50839. },
  50840. enumerable: true,
  50841. configurable: true
  50842. });
  50843. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  50844. get: function () {
  50845. if (this._shareOutputWithPostProcess) {
  50846. return this._shareOutputWithPostProcess.aspectRatio;
  50847. }
  50848. if (this._forcedOutputTexture) {
  50849. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  50850. }
  50851. return this.width / this.height;
  50852. },
  50853. enumerable: true,
  50854. configurable: true
  50855. });
  50856. PostProcess.prototype.apply = function () {
  50857. // Check
  50858. if (!this._effect || !this._effect.isReady())
  50859. return null;
  50860. // States
  50861. this._engine.enableEffect(this._effect);
  50862. this._engine.setState(false);
  50863. this._engine.setDepthBuffer(false);
  50864. this._engine.setDepthWrite(false);
  50865. // Alpha
  50866. this._engine.setAlphaMode(this.alphaMode);
  50867. if (this.alphaConstants) {
  50868. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  50869. }
  50870. // Texture
  50871. var source;
  50872. if (this._shareOutputWithPostProcess) {
  50873. source = this._shareOutputWithPostProcess.outputTexture;
  50874. }
  50875. else if (this._forcedOutputTexture) {
  50876. source = this._forcedOutputTexture;
  50877. }
  50878. else {
  50879. source = this.outputTexture;
  50880. }
  50881. this._effect._bindTexture("textureSampler", source);
  50882. // Parameters
  50883. this._effect.setVector2("scale", this._scaleRatio);
  50884. this.onApplyObservable.notifyObservers(this._effect);
  50885. return this._effect;
  50886. };
  50887. PostProcess.prototype._disposeTextures = function () {
  50888. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  50889. return;
  50890. }
  50891. if (this._textures.length > 0) {
  50892. for (var i = 0; i < this._textures.length; i++) {
  50893. this._engine._releaseTexture(this._textures.data[i]);
  50894. }
  50895. }
  50896. this._textures.dispose();
  50897. };
  50898. PostProcess.prototype.dispose = function (camera) {
  50899. camera = camera || this._camera;
  50900. this._disposeTextures();
  50901. if (this._scene) {
  50902. var index_1 = this._scene.postProcesses.indexOf(this);
  50903. if (index_1 !== -1) {
  50904. this._scene.postProcesses.splice(index_1, 1);
  50905. }
  50906. }
  50907. else {
  50908. var index_2 = this._engine.postProcesses.indexOf(this);
  50909. if (index_2 !== -1) {
  50910. this._engine.postProcesses.splice(index_2, 1);
  50911. }
  50912. }
  50913. if (!camera) {
  50914. return;
  50915. }
  50916. camera.detachPostProcess(this);
  50917. var index = camera._postProcesses.indexOf(this);
  50918. if (index === 0 && camera._postProcesses.length > 0) {
  50919. this._camera._postProcesses[0].markTextureDirty();
  50920. }
  50921. this.onActivateObservable.clear();
  50922. this.onAfterRenderObservable.clear();
  50923. this.onApplyObservable.clear();
  50924. this.onBeforeRenderObservable.clear();
  50925. this.onSizeChangedObservable.clear();
  50926. };
  50927. return PostProcess;
  50928. }());
  50929. BABYLON.PostProcess = PostProcess;
  50930. })(BABYLON || (BABYLON = {}));
  50931. //# sourceMappingURL=babylon.postProcess.js.map
  50932. var BABYLON;
  50933. (function (BABYLON) {
  50934. var PassPostProcess = /** @class */ (function (_super) {
  50935. __extends(PassPostProcess, _super);
  50936. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50937. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50938. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  50939. }
  50940. return PassPostProcess;
  50941. }(BABYLON.PostProcess));
  50942. BABYLON.PassPostProcess = PassPostProcess;
  50943. })(BABYLON || (BABYLON = {}));
  50944. //# sourceMappingURL=babylon.passPostProcess.js.map
  50945. var BABYLON;
  50946. (function (BABYLON) {
  50947. var ShadowGenerator = /** @class */ (function () {
  50948. /**
  50949. * Creates a ShadowGenerator object.
  50950. * A ShadowGenerator is the required tool to use the shadows.
  50951. * Each light casting shadows needs to use its own ShadowGenerator.
  50952. * Required parameters :
  50953. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  50954. * - `light`: the light object generating the shadows.
  50955. * - `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.
  50956. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  50957. */
  50958. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  50959. // Members
  50960. this._bias = 0.00005;
  50961. this._blurBoxOffset = 1;
  50962. this._blurScale = 2;
  50963. this._blurKernel = 1;
  50964. this._useKernelBlur = false;
  50965. this._filter = ShadowGenerator.FILTER_NONE;
  50966. this._darkness = 0;
  50967. this._transparencyShadow = false;
  50968. /**
  50969. * Controls the extent to which the shadows fade out at the edge of the frustum
  50970. * Used only by directionals and spots
  50971. */
  50972. this.frustumEdgeFalloff = 0;
  50973. this.forceBackFacesOnly = false;
  50974. this._lightDirection = BABYLON.Vector3.Zero();
  50975. this._viewMatrix = BABYLON.Matrix.Zero();
  50976. this._projectionMatrix = BABYLON.Matrix.Zero();
  50977. this._transformMatrix = BABYLON.Matrix.Zero();
  50978. this._currentFaceIndex = 0;
  50979. this._currentFaceIndexCache = 0;
  50980. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  50981. this._mapSize = mapSize;
  50982. this._light = light;
  50983. this._scene = light.getScene();
  50984. light._shadowGenerator = this;
  50985. // Texture type fallback from float to int if not supported.
  50986. var caps = this._scene.getEngine().getCaps();
  50987. if (!useFullFloatFirst) {
  50988. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50989. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50990. }
  50991. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50992. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50993. }
  50994. else {
  50995. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50996. }
  50997. }
  50998. else {
  50999. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51000. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51001. }
  51002. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51003. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51004. }
  51005. else {
  51006. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51007. }
  51008. }
  51009. this._initializeGenerator();
  51010. }
  51011. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  51012. // Static
  51013. get: function () {
  51014. return ShadowGenerator._FILTER_NONE;
  51015. },
  51016. enumerable: true,
  51017. configurable: true
  51018. });
  51019. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  51020. get: function () {
  51021. return ShadowGenerator._FILTER_POISSONSAMPLING;
  51022. },
  51023. enumerable: true,
  51024. configurable: true
  51025. });
  51026. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  51027. get: function () {
  51028. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  51029. },
  51030. enumerable: true,
  51031. configurable: true
  51032. });
  51033. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  51034. get: function () {
  51035. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  51036. },
  51037. enumerable: true,
  51038. configurable: true
  51039. });
  51040. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  51041. get: function () {
  51042. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51043. },
  51044. enumerable: true,
  51045. configurable: true
  51046. });
  51047. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  51048. get: function () {
  51049. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51050. },
  51051. enumerable: true,
  51052. configurable: true
  51053. });
  51054. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  51055. get: function () {
  51056. return this._bias;
  51057. },
  51058. set: function (bias) {
  51059. this._bias = bias;
  51060. },
  51061. enumerable: true,
  51062. configurable: true
  51063. });
  51064. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  51065. get: function () {
  51066. return this._blurBoxOffset;
  51067. },
  51068. set: function (value) {
  51069. if (this._blurBoxOffset === value) {
  51070. return;
  51071. }
  51072. this._blurBoxOffset = value;
  51073. this._disposeBlurPostProcesses();
  51074. },
  51075. enumerable: true,
  51076. configurable: true
  51077. });
  51078. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  51079. get: function () {
  51080. return this._blurScale;
  51081. },
  51082. set: function (value) {
  51083. if (this._blurScale === value) {
  51084. return;
  51085. }
  51086. this._blurScale = value;
  51087. this._disposeBlurPostProcesses();
  51088. },
  51089. enumerable: true,
  51090. configurable: true
  51091. });
  51092. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  51093. get: function () {
  51094. return this._blurKernel;
  51095. },
  51096. set: function (value) {
  51097. if (this._blurKernel === value) {
  51098. return;
  51099. }
  51100. this._blurKernel = value;
  51101. this._disposeBlurPostProcesses();
  51102. },
  51103. enumerable: true,
  51104. configurable: true
  51105. });
  51106. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  51107. get: function () {
  51108. return this._useKernelBlur;
  51109. },
  51110. set: function (value) {
  51111. if (this._useKernelBlur === value) {
  51112. return;
  51113. }
  51114. this._useKernelBlur = value;
  51115. this._disposeBlurPostProcesses();
  51116. },
  51117. enumerable: true,
  51118. configurable: true
  51119. });
  51120. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  51121. get: function () {
  51122. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  51123. },
  51124. set: function (value) {
  51125. this._depthScale = value;
  51126. },
  51127. enumerable: true,
  51128. configurable: true
  51129. });
  51130. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  51131. get: function () {
  51132. return this._filter;
  51133. },
  51134. set: function (value) {
  51135. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  51136. if (this._light.needCube()) {
  51137. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51138. this.useExponentialShadowMap = true;
  51139. return;
  51140. }
  51141. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51142. this.useCloseExponentialShadowMap = true;
  51143. return;
  51144. }
  51145. }
  51146. if (this._filter === value) {
  51147. return;
  51148. }
  51149. this._filter = value;
  51150. this._disposeBlurPostProcesses();
  51151. this._applyFilterValues();
  51152. this._light._markMeshesAsLightDirty();
  51153. },
  51154. enumerable: true,
  51155. configurable: true
  51156. });
  51157. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  51158. get: function () {
  51159. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  51160. },
  51161. set: function (value) {
  51162. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  51163. return;
  51164. }
  51165. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  51166. },
  51167. enumerable: true,
  51168. configurable: true
  51169. });
  51170. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  51171. get: function () {
  51172. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51173. return this.useExponentialShadowMap;
  51174. },
  51175. set: function (value) {
  51176. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51177. this.useExponentialShadowMap = value;
  51178. },
  51179. enumerable: true,
  51180. configurable: true
  51181. });
  51182. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  51183. get: function () {
  51184. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51185. return this.useBlurExponentialShadowMap;
  51186. },
  51187. set: function (value) {
  51188. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51189. this.useBlurExponentialShadowMap = value;
  51190. },
  51191. enumerable: true,
  51192. configurable: true
  51193. });
  51194. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  51195. get: function () {
  51196. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  51197. },
  51198. set: function (value) {
  51199. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  51200. return;
  51201. }
  51202. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51203. },
  51204. enumerable: true,
  51205. configurable: true
  51206. });
  51207. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  51208. get: function () {
  51209. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  51210. },
  51211. set: function (value) {
  51212. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51213. return;
  51214. }
  51215. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51216. },
  51217. enumerable: true,
  51218. configurable: true
  51219. });
  51220. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  51221. get: function () {
  51222. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51223. },
  51224. set: function (value) {
  51225. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  51226. return;
  51227. }
  51228. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51229. },
  51230. enumerable: true,
  51231. configurable: true
  51232. });
  51233. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  51234. get: function () {
  51235. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51236. },
  51237. set: function (value) {
  51238. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51239. return;
  51240. }
  51241. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51242. },
  51243. enumerable: true,
  51244. configurable: true
  51245. });
  51246. /**
  51247. * Returns the darkness value (float).
  51248. */
  51249. ShadowGenerator.prototype.getDarkness = function () {
  51250. return this._darkness;
  51251. };
  51252. /**
  51253. * Sets the ShadowGenerator darkness value (float <= 1.0).
  51254. * Returns the ShadowGenerator.
  51255. */
  51256. ShadowGenerator.prototype.setDarkness = function (darkness) {
  51257. if (darkness >= 1.0)
  51258. this._darkness = 1.0;
  51259. else if (darkness <= 0.0)
  51260. this._darkness = 0.0;
  51261. else
  51262. this._darkness = darkness;
  51263. return this;
  51264. };
  51265. /**
  51266. * Sets the ability to have transparent shadow (boolean).
  51267. * Returns the ShadowGenerator.
  51268. */
  51269. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  51270. this._transparencyShadow = hasShadow;
  51271. return this;
  51272. };
  51273. /**
  51274. * Returns a RenderTargetTexture object : the shadow map texture.
  51275. */
  51276. ShadowGenerator.prototype.getShadowMap = function () {
  51277. return this._shadowMap;
  51278. };
  51279. /**
  51280. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  51281. */
  51282. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  51283. if (this._shadowMap2) {
  51284. return this._shadowMap2;
  51285. }
  51286. return this._shadowMap;
  51287. };
  51288. /**
  51289. * Helper function to add a mesh and its descendants to the list of shadow casters
  51290. * @param mesh Mesh to add
  51291. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  51292. */
  51293. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  51294. if (includeDescendants === void 0) { includeDescendants = true; }
  51295. if (!this._shadowMap) {
  51296. return this;
  51297. }
  51298. if (!this._shadowMap.renderList) {
  51299. this._shadowMap.renderList = [];
  51300. }
  51301. this._shadowMap.renderList.push(mesh);
  51302. if (includeDescendants) {
  51303. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  51304. }
  51305. return this;
  51306. var _a;
  51307. };
  51308. /**
  51309. * Helper function to remove a mesh and its descendants from the list of shadow casters
  51310. * @param mesh Mesh to remove
  51311. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  51312. */
  51313. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  51314. if (includeDescendants === void 0) { includeDescendants = true; }
  51315. if (!this._shadowMap || !this._shadowMap.renderList) {
  51316. return this;
  51317. }
  51318. var index = this._shadowMap.renderList.indexOf(mesh);
  51319. if (index !== -1) {
  51320. this._shadowMap.renderList.splice(index, 1);
  51321. }
  51322. if (includeDescendants) {
  51323. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  51324. var child = _a[_i];
  51325. this.removeShadowCaster(child);
  51326. }
  51327. }
  51328. return this;
  51329. };
  51330. /**
  51331. * Returns the associated light object.
  51332. */
  51333. ShadowGenerator.prototype.getLight = function () {
  51334. return this._light;
  51335. };
  51336. ShadowGenerator.prototype._initializeGenerator = function () {
  51337. this._light._markMeshesAsLightDirty();
  51338. this._initializeShadowMap();
  51339. };
  51340. ShadowGenerator.prototype._initializeShadowMap = function () {
  51341. var _this = this;
  51342. // Render target
  51343. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51344. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51345. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51346. this._shadowMap.anisotropicFilteringLevel = 1;
  51347. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51348. this._shadowMap.renderParticles = false;
  51349. this._shadowMap.ignoreCameraViewport = true;
  51350. // Record Face Index before render.
  51351. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51352. _this._currentFaceIndex = faceIndex;
  51353. });
  51354. // Custom render function.
  51355. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51356. // Blur if required afer render.
  51357. this._shadowMap.onAfterUnbindObservable.add(function () {
  51358. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51359. return;
  51360. }
  51361. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51362. _this._initializeBlurRTTAndPostProcesses();
  51363. }
  51364. var shadowMap = _this.getShadowMapForRendering();
  51365. if (shadowMap) {
  51366. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51367. }
  51368. });
  51369. // Clear according to the chosen filter.
  51370. this._shadowMap.onClearObservable.add(function (engine) {
  51371. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51372. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51373. }
  51374. else {
  51375. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51376. }
  51377. });
  51378. };
  51379. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51380. var _this = this;
  51381. var engine = this._scene.getEngine();
  51382. var targetSize = this._mapSize / this.blurScale;
  51383. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51384. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51385. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51386. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51387. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51388. }
  51389. if (this.useKernelBlur) {
  51390. 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);
  51391. this._kernelBlurXPostprocess.width = targetSize;
  51392. this._kernelBlurXPostprocess.height = targetSize;
  51393. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51394. effect.setTexture("textureSampler", _this._shadowMap);
  51395. });
  51396. 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);
  51397. this._kernelBlurXPostprocess.autoClear = false;
  51398. this._kernelBlurYPostprocess.autoClear = false;
  51399. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51400. this._kernelBlurXPostprocess.packedFloat = true;
  51401. this._kernelBlurYPostprocess.packedFloat = true;
  51402. }
  51403. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51404. }
  51405. else {
  51406. 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);
  51407. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51408. effect.setFloat2("screenSize", targetSize, targetSize);
  51409. effect.setTexture("textureSampler", _this._shadowMap);
  51410. });
  51411. this._boxBlurPostprocess.autoClear = false;
  51412. this._blurPostProcesses = [this._boxBlurPostprocess];
  51413. }
  51414. };
  51415. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  51416. var index;
  51417. var engine = this._scene.getEngine();
  51418. if (depthOnlySubMeshes.length) {
  51419. engine.setColorWrite(false);
  51420. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  51421. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  51422. }
  51423. engine.setColorWrite(true);
  51424. }
  51425. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51426. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  51427. }
  51428. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51429. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  51430. }
  51431. if (this._transparencyShadow) {
  51432. for (index = 0; index < transparentSubMeshes.length; index++) {
  51433. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  51434. }
  51435. }
  51436. };
  51437. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  51438. var _this = this;
  51439. var mesh = subMesh.getRenderingMesh();
  51440. var scene = this._scene;
  51441. var engine = scene.getEngine();
  51442. var material = subMesh.getMaterial();
  51443. if (!material) {
  51444. return;
  51445. }
  51446. // Culling
  51447. engine.setState(material.backFaceCulling);
  51448. // Managing instances
  51449. var batch = mesh._getInstancesRenderList(subMesh._id);
  51450. if (batch.mustReturn) {
  51451. return;
  51452. }
  51453. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  51454. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  51455. engine.enableEffect(this._effect);
  51456. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  51457. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  51458. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  51459. this._effect.setVector3("lightPosition", this.getLight().position);
  51460. if (scene.activeCamera) {
  51461. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  51462. }
  51463. // Alpha test
  51464. if (material && material.needAlphaTesting()) {
  51465. var alphaTexture = material.getAlphaTestTexture();
  51466. if (alphaTexture) {
  51467. this._effect.setTexture("diffuseSampler", alphaTexture);
  51468. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  51469. }
  51470. }
  51471. // Bones
  51472. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51473. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  51474. }
  51475. if (this.forceBackFacesOnly) {
  51476. engine.setState(true, 0, false, true);
  51477. }
  51478. // Draw
  51479. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51480. if (this.forceBackFacesOnly) {
  51481. engine.setState(true, 0, false, false);
  51482. }
  51483. }
  51484. else {
  51485. // Need to reset refresh rate of the shadowMap
  51486. if (this._shadowMap) {
  51487. this._shadowMap.resetRefreshCounter();
  51488. }
  51489. }
  51490. };
  51491. ShadowGenerator.prototype._applyFilterValues = function () {
  51492. if (!this._shadowMap) {
  51493. return;
  51494. }
  51495. if (this.filter === ShadowGenerator.FILTER_NONE) {
  51496. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  51497. }
  51498. else {
  51499. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51500. }
  51501. };
  51502. /**
  51503. * Force shader compilation including textures ready check
  51504. */
  51505. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  51506. var _this = this;
  51507. var shadowMap = this.getShadowMap();
  51508. if (!shadowMap) {
  51509. return;
  51510. }
  51511. var subMeshes = new Array();
  51512. var currentIndex = 0;
  51513. var renderList = shadowMap.renderList;
  51514. if (!renderList) {
  51515. return;
  51516. }
  51517. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  51518. var mesh = renderList_1[_i];
  51519. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  51520. }
  51521. var checkReady = function () {
  51522. if (!_this._scene || !_this._scene.getEngine()) {
  51523. return;
  51524. }
  51525. while (_this.isReady(subMeshes[currentIndex], options ? options.useInstances : false)) {
  51526. currentIndex++;
  51527. if (currentIndex >= subMeshes.length) {
  51528. if (onCompiled) {
  51529. onCompiled(_this);
  51530. }
  51531. return;
  51532. }
  51533. }
  51534. setTimeout(checkReady, 16);
  51535. };
  51536. if (subMeshes.length > 0) {
  51537. checkReady();
  51538. }
  51539. };
  51540. /**
  51541. * Boolean : true when the ShadowGenerator is finally computed.
  51542. */
  51543. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  51544. var defines = [];
  51545. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51546. defines.push("#define FLOAT");
  51547. }
  51548. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51549. defines.push("#define ESM");
  51550. }
  51551. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51552. var mesh = subMesh.getMesh();
  51553. var material = subMesh.getMaterial();
  51554. // Alpha test
  51555. if (material && material.needAlphaTesting()) {
  51556. var alphaTexture = material.getAlphaTestTexture();
  51557. if (alphaTexture) {
  51558. defines.push("#define ALPHATEST");
  51559. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51560. attribs.push(BABYLON.VertexBuffer.UVKind);
  51561. defines.push("#define UV1");
  51562. }
  51563. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51564. if (alphaTexture.coordinatesIndex === 1) {
  51565. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51566. defines.push("#define UV2");
  51567. }
  51568. }
  51569. }
  51570. }
  51571. // Bones
  51572. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51573. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51574. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51575. if (mesh.numBoneInfluencers > 4) {
  51576. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51577. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51578. }
  51579. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51580. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51581. }
  51582. else {
  51583. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51584. }
  51585. // Instances
  51586. if (useInstances) {
  51587. defines.push("#define INSTANCES");
  51588. attribs.push("world0");
  51589. attribs.push("world1");
  51590. attribs.push("world2");
  51591. attribs.push("world3");
  51592. }
  51593. // Get correct effect
  51594. var join = defines.join("\n");
  51595. if (this._cachedDefines !== join) {
  51596. this._cachedDefines = join;
  51597. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  51598. }
  51599. return this._effect.isReady();
  51600. };
  51601. /**
  51602. * This creates the defines related to the standard BJS materials.
  51603. */
  51604. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  51605. var scene = this._scene;
  51606. var light = this._light;
  51607. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51608. return;
  51609. }
  51610. defines["SHADOW" + lightIndex] = true;
  51611. if (this.usePoissonSampling) {
  51612. defines["SHADOWPCF" + lightIndex] = true;
  51613. }
  51614. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51615. defines["SHADOWESM" + lightIndex] = true;
  51616. }
  51617. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  51618. defines["SHADOWCLOSEESM" + lightIndex] = true;
  51619. }
  51620. if (light.needCube()) {
  51621. defines["SHADOWCUBE" + lightIndex] = true;
  51622. }
  51623. };
  51624. /**
  51625. * This binds shadow lights related to the standard BJS materials.
  51626. * It implies the unifroms available on the materials are the standard BJS ones.
  51627. */
  51628. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  51629. var light = this._light;
  51630. var scene = this._scene;
  51631. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51632. return;
  51633. }
  51634. var camera = scene.activeCamera;
  51635. if (!camera) {
  51636. return;
  51637. }
  51638. var shadowMap = this.getShadowMap();
  51639. if (!shadowMap) {
  51640. return;
  51641. }
  51642. if (!light.needCube()) {
  51643. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  51644. }
  51645. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  51646. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  51647. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  51648. };
  51649. // Methods
  51650. /**
  51651. * Returns a Matrix object : the updated transformation matrix.
  51652. */
  51653. ShadowGenerator.prototype.getTransformMatrix = function () {
  51654. var scene = this._scene;
  51655. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  51656. return this._transformMatrix;
  51657. }
  51658. this._currentRenderID = scene.getRenderId();
  51659. this._currentFaceIndexCache = this._currentFaceIndex;
  51660. var lightPosition = this._light.position;
  51661. if (this._light.computeTransformedInformation()) {
  51662. lightPosition = this._light.transformedPosition;
  51663. }
  51664. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  51665. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  51666. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  51667. }
  51668. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  51669. this._cachedPosition = lightPosition.clone();
  51670. this._cachedDirection = this._lightDirection.clone();
  51671. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  51672. var shadowMap = this.getShadowMap();
  51673. if (shadowMap) {
  51674. var renderList = shadowMap.renderList;
  51675. if (renderList) {
  51676. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  51677. }
  51678. }
  51679. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  51680. }
  51681. return this._transformMatrix;
  51682. };
  51683. ShadowGenerator.prototype.recreateShadowMap = function () {
  51684. var shadowMap = this._shadowMap;
  51685. if (!shadowMap) {
  51686. return;
  51687. }
  51688. // Track render list.
  51689. var renderList = shadowMap.renderList;
  51690. // Clean up existing data.
  51691. this._disposeRTTandPostProcesses();
  51692. // Reinitializes.
  51693. this._initializeGenerator();
  51694. // Reaffect the filter to ensure a correct fallback if necessary.
  51695. this.filter = this.filter;
  51696. // Reaffect the filter.
  51697. this._applyFilterValues();
  51698. // Reaffect Render List.
  51699. this._shadowMap.renderList = renderList;
  51700. };
  51701. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  51702. if (this._shadowMap2) {
  51703. this._shadowMap2.dispose();
  51704. this._shadowMap2 = null;
  51705. }
  51706. if (this._downSamplePostprocess) {
  51707. this._downSamplePostprocess.dispose();
  51708. this._downSamplePostprocess = null;
  51709. }
  51710. if (this._boxBlurPostprocess) {
  51711. this._boxBlurPostprocess.dispose();
  51712. this._boxBlurPostprocess = null;
  51713. }
  51714. if (this._kernelBlurXPostprocess) {
  51715. this._kernelBlurXPostprocess.dispose();
  51716. this._kernelBlurXPostprocess = null;
  51717. }
  51718. if (this._kernelBlurYPostprocess) {
  51719. this._kernelBlurYPostprocess.dispose();
  51720. this._kernelBlurYPostprocess = null;
  51721. }
  51722. this._blurPostProcesses = [];
  51723. };
  51724. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  51725. if (this._shadowMap) {
  51726. this._shadowMap.dispose();
  51727. this._shadowMap = null;
  51728. }
  51729. this._disposeBlurPostProcesses();
  51730. };
  51731. /**
  51732. * Disposes the ShadowGenerator.
  51733. * Returns nothing.
  51734. */
  51735. ShadowGenerator.prototype.dispose = function () {
  51736. this._disposeRTTandPostProcesses();
  51737. if (this._light) {
  51738. this._light._shadowGenerator = null;
  51739. this._light._markMeshesAsLightDirty();
  51740. }
  51741. };
  51742. /**
  51743. * Serializes the ShadowGenerator and returns a serializationObject.
  51744. */
  51745. ShadowGenerator.prototype.serialize = function () {
  51746. var serializationObject = {};
  51747. var shadowMap = this.getShadowMap();
  51748. if (!shadowMap) {
  51749. return serializationObject;
  51750. }
  51751. serializationObject.lightId = this._light.id;
  51752. serializationObject.mapSize = shadowMap.getRenderSize();
  51753. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  51754. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  51755. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51756. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51757. serializationObject.usePoissonSampling = this.usePoissonSampling;
  51758. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  51759. serializationObject.depthScale = this.depthScale;
  51760. serializationObject.darkness = this.getDarkness();
  51761. serializationObject.blurBoxOffset = this.blurBoxOffset;
  51762. serializationObject.blurKernel = this.blurKernel;
  51763. serializationObject.blurScale = this.blurScale;
  51764. serializationObject.useKernelBlur = this.useKernelBlur;
  51765. serializationObject.transparencyShadow = this._transparencyShadow;
  51766. serializationObject.renderList = [];
  51767. if (shadowMap.renderList) {
  51768. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  51769. var mesh = shadowMap.renderList[meshIndex];
  51770. serializationObject.renderList.push(mesh.id);
  51771. }
  51772. }
  51773. return serializationObject;
  51774. };
  51775. /**
  51776. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  51777. */
  51778. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  51779. //casting to point light, as light is missing the position attr and typescript complains.
  51780. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  51781. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  51782. var shadowMap = shadowGenerator.getShadowMap();
  51783. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  51784. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  51785. meshes.forEach(function (mesh) {
  51786. if (!shadowMap) {
  51787. return;
  51788. }
  51789. if (!shadowMap.renderList) {
  51790. shadowMap.renderList = [];
  51791. }
  51792. shadowMap.renderList.push(mesh);
  51793. });
  51794. }
  51795. if (parsedShadowGenerator.usePoissonSampling) {
  51796. shadowGenerator.usePoissonSampling = true;
  51797. }
  51798. else if (parsedShadowGenerator.useExponentialShadowMap) {
  51799. shadowGenerator.useExponentialShadowMap = true;
  51800. }
  51801. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  51802. shadowGenerator.useBlurExponentialShadowMap = true;
  51803. }
  51804. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  51805. shadowGenerator.useCloseExponentialShadowMap = true;
  51806. }
  51807. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  51808. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  51809. }
  51810. else if (parsedShadowGenerator.useVarianceShadowMap) {
  51811. shadowGenerator.useExponentialShadowMap = true;
  51812. }
  51813. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  51814. shadowGenerator.useBlurExponentialShadowMap = true;
  51815. }
  51816. if (parsedShadowGenerator.depthScale) {
  51817. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  51818. }
  51819. if (parsedShadowGenerator.blurScale) {
  51820. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  51821. }
  51822. if (parsedShadowGenerator.blurBoxOffset) {
  51823. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  51824. }
  51825. if (parsedShadowGenerator.useKernelBlur) {
  51826. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  51827. }
  51828. if (parsedShadowGenerator.blurKernel) {
  51829. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  51830. }
  51831. if (parsedShadowGenerator.bias !== undefined) {
  51832. shadowGenerator.bias = parsedShadowGenerator.bias;
  51833. }
  51834. if (parsedShadowGenerator.darkness) {
  51835. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  51836. }
  51837. if (parsedShadowGenerator.transparencyShadow) {
  51838. shadowGenerator.setTransparencyShadow(true);
  51839. }
  51840. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  51841. return shadowGenerator;
  51842. };
  51843. ShadowGenerator._FILTER_NONE = 0;
  51844. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  51845. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  51846. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  51847. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  51848. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  51849. return ShadowGenerator;
  51850. }());
  51851. BABYLON.ShadowGenerator = ShadowGenerator;
  51852. })(BABYLON || (BABYLON = {}));
  51853. //# sourceMappingURL=babylon.shadowGenerator.js.map
  51854. var BABYLON;
  51855. (function (BABYLON) {
  51856. var DefaultLoadingScreen = /** @class */ (function () {
  51857. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  51858. if (_loadingText === void 0) { _loadingText = ""; }
  51859. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  51860. var _this = this;
  51861. this._renderingCanvas = _renderingCanvas;
  51862. this._loadingText = _loadingText;
  51863. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  51864. // Resize
  51865. this._resizeLoadingUI = function () {
  51866. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  51867. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  51868. if (!_this._loadingDiv) {
  51869. return;
  51870. }
  51871. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  51872. _this._loadingDiv.style.left = canvasRect.left + "px";
  51873. _this._loadingDiv.style.top = canvasRect.top + "px";
  51874. _this._loadingDiv.style.width = canvasRect.width + "px";
  51875. _this._loadingDiv.style.height = canvasRect.height + "px";
  51876. };
  51877. }
  51878. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  51879. if (this._loadingDiv) {
  51880. // Do not add a loading screen if there is already one
  51881. return;
  51882. }
  51883. this._loadingDiv = document.createElement("div");
  51884. this._loadingDiv.id = "babylonjsLoadingDiv";
  51885. this._loadingDiv.style.opacity = "0";
  51886. this._loadingDiv.style.transition = "opacity 1.5s ease";
  51887. this._loadingDiv.style.pointerEvents = "none";
  51888. // Loading text
  51889. this._loadingTextDiv = document.createElement("div");
  51890. this._loadingTextDiv.style.position = "absolute";
  51891. this._loadingTextDiv.style.left = "0";
  51892. this._loadingTextDiv.style.top = "50%";
  51893. this._loadingTextDiv.style.marginTop = "80px";
  51894. this._loadingTextDiv.style.width = "100%";
  51895. this._loadingTextDiv.style.height = "20px";
  51896. this._loadingTextDiv.style.fontFamily = "Arial";
  51897. this._loadingTextDiv.style.fontSize = "14px";
  51898. this._loadingTextDiv.style.color = "white";
  51899. this._loadingTextDiv.style.textAlign = "center";
  51900. this._loadingTextDiv.innerHTML = "Loading";
  51901. this._loadingDiv.appendChild(this._loadingTextDiv);
  51902. //set the predefined text
  51903. this._loadingTextDiv.innerHTML = this._loadingText;
  51904. // Generating keyframes
  51905. var style = document.createElement('style');
  51906. style.type = 'text/css';
  51907. 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 }";
  51908. style.innerHTML = keyFrames;
  51909. document.getElementsByTagName('head')[0].appendChild(style);
  51910. // Loading img
  51911. var imgBack = new Image();
  51912. 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";
  51913. imgBack.style.position = "absolute";
  51914. imgBack.style.left = "50%";
  51915. imgBack.style.top = "50%";
  51916. imgBack.style.marginLeft = "-60px";
  51917. imgBack.style.marginTop = "-60px";
  51918. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  51919. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  51920. imgBack.style.transformOrigin = "50% 50%";
  51921. imgBack.style.webkitTransformOrigin = "50% 50%";
  51922. this._loadingDiv.appendChild(imgBack);
  51923. this._resizeLoadingUI();
  51924. window.addEventListener("resize", this._resizeLoadingUI);
  51925. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51926. document.body.appendChild(this._loadingDiv);
  51927. this._loadingDiv.style.opacity = "1";
  51928. };
  51929. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  51930. var _this = this;
  51931. if (!this._loadingDiv) {
  51932. return;
  51933. }
  51934. var onTransitionEnd = function () {
  51935. if (!_this._loadingDiv) {
  51936. return;
  51937. }
  51938. document.body.removeChild(_this._loadingDiv);
  51939. window.removeEventListener("resize", _this._resizeLoadingUI);
  51940. _this._loadingDiv = null;
  51941. };
  51942. this._loadingDiv.style.opacity = "0";
  51943. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  51944. };
  51945. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  51946. set: function (text) {
  51947. this._loadingText = text;
  51948. if (this._loadingTextDiv) {
  51949. this._loadingTextDiv.innerHTML = this._loadingText;
  51950. }
  51951. },
  51952. enumerable: true,
  51953. configurable: true
  51954. });
  51955. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  51956. get: function () {
  51957. return this._loadingDivBackgroundColor;
  51958. },
  51959. set: function (color) {
  51960. this._loadingDivBackgroundColor = color;
  51961. if (!this._loadingDiv) {
  51962. return;
  51963. }
  51964. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51965. },
  51966. enumerable: true,
  51967. configurable: true
  51968. });
  51969. return DefaultLoadingScreen;
  51970. }());
  51971. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  51972. })(BABYLON || (BABYLON = {}));
  51973. //# sourceMappingURL=babylon.loadingScreen.js.map
  51974. var BABYLON;
  51975. (function (BABYLON) {
  51976. var SceneLoader = /** @class */ (function () {
  51977. function SceneLoader() {
  51978. }
  51979. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  51980. get: function () {
  51981. return 0;
  51982. },
  51983. enumerable: true,
  51984. configurable: true
  51985. });
  51986. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  51987. get: function () {
  51988. return 1;
  51989. },
  51990. enumerable: true,
  51991. configurable: true
  51992. });
  51993. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  51994. get: function () {
  51995. return 2;
  51996. },
  51997. enumerable: true,
  51998. configurable: true
  51999. });
  52000. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  52001. get: function () {
  52002. return 3;
  52003. },
  52004. enumerable: true,
  52005. configurable: true
  52006. });
  52007. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  52008. get: function () {
  52009. return SceneLoader._ForceFullSceneLoadingForIncremental;
  52010. },
  52011. set: function (value) {
  52012. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  52013. },
  52014. enumerable: true,
  52015. configurable: true
  52016. });
  52017. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  52018. get: function () {
  52019. return SceneLoader._ShowLoadingScreen;
  52020. },
  52021. set: function (value) {
  52022. SceneLoader._ShowLoadingScreen = value;
  52023. },
  52024. enumerable: true,
  52025. configurable: true
  52026. });
  52027. Object.defineProperty(SceneLoader, "loggingLevel", {
  52028. get: function () {
  52029. return SceneLoader._loggingLevel;
  52030. },
  52031. set: function (value) {
  52032. SceneLoader._loggingLevel = value;
  52033. },
  52034. enumerable: true,
  52035. configurable: true
  52036. });
  52037. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  52038. get: function () {
  52039. return SceneLoader._CleanBoneMatrixWeights;
  52040. },
  52041. set: function (value) {
  52042. SceneLoader._CleanBoneMatrixWeights = value;
  52043. },
  52044. enumerable: true,
  52045. configurable: true
  52046. });
  52047. SceneLoader._getDefaultPlugin = function () {
  52048. return SceneLoader._registeredPlugins[".babylon"];
  52049. };
  52050. SceneLoader._getPluginForExtension = function (extension) {
  52051. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  52052. if (registeredPlugin) {
  52053. return registeredPlugin;
  52054. }
  52055. return SceneLoader._getDefaultPlugin();
  52056. };
  52057. SceneLoader._getPluginForDirectLoad = function (data) {
  52058. for (var extension in SceneLoader._registeredPlugins) {
  52059. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  52060. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  52061. return SceneLoader._registeredPlugins[extension];
  52062. }
  52063. }
  52064. return SceneLoader._getDefaultPlugin();
  52065. };
  52066. SceneLoader._getPluginForFilename = function (sceneFilename) {
  52067. if (sceneFilename.name) {
  52068. sceneFilename = sceneFilename.name;
  52069. }
  52070. var dotPosition = sceneFilename.lastIndexOf(".");
  52071. var queryStringPosition = sceneFilename.indexOf("?");
  52072. if (queryStringPosition === -1) {
  52073. queryStringPosition = sceneFilename.length;
  52074. }
  52075. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  52076. return SceneLoader._getPluginForExtension(extension);
  52077. };
  52078. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  52079. SceneLoader._getDirectLoad = function (sceneFilename) {
  52080. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  52081. return sceneFilename.substr(5);
  52082. }
  52083. return null;
  52084. };
  52085. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52086. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  52087. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  52088. var plugin = registeredPlugin.plugin;
  52089. var useArrayBuffer = registeredPlugin.isBinary;
  52090. var database;
  52091. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  52092. var dataCallback = function (data) {
  52093. if (scene.isDisposed) {
  52094. onError("Scene has been disposed");
  52095. return;
  52096. }
  52097. scene.database = database;
  52098. try {
  52099. onSuccess(plugin, data);
  52100. }
  52101. catch (e) {
  52102. onError(null, e);
  52103. }
  52104. };
  52105. var manifestChecked = function (success) {
  52106. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  52107. if (request) {
  52108. onError(request.status + " " + request.statusText);
  52109. }
  52110. });
  52111. };
  52112. if (directLoad) {
  52113. dataCallback(directLoad);
  52114. return registeredPlugin.plugin;
  52115. }
  52116. if (rootUrl.indexOf("file:") === -1) {
  52117. if (scene.getEngine().enableOfflineSupport) {
  52118. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  52119. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  52120. }
  52121. else {
  52122. manifestChecked(true);
  52123. }
  52124. }
  52125. else {
  52126. var fileOrString = sceneFilename;
  52127. if (fileOrString.name) {
  52128. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  52129. }
  52130. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  52131. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  52132. }
  52133. else {
  52134. onError("Unable to find file named " + sceneFilename);
  52135. }
  52136. }
  52137. return registeredPlugin.plugin;
  52138. };
  52139. // Public functions
  52140. SceneLoader.GetPluginForExtension = function (extension) {
  52141. return SceneLoader._getPluginForExtension(extension).plugin;
  52142. };
  52143. SceneLoader.RegisterPlugin = function (plugin) {
  52144. if (typeof plugin.extensions === "string") {
  52145. var extension = plugin.extensions;
  52146. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52147. plugin: plugin,
  52148. isBinary: false
  52149. };
  52150. }
  52151. else {
  52152. var extensions = plugin.extensions;
  52153. Object.keys(extensions).forEach(function (extension) {
  52154. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52155. plugin: plugin,
  52156. isBinary: extensions[extension].isBinary
  52157. };
  52158. });
  52159. }
  52160. };
  52161. /**
  52162. * Import meshes into a scene
  52163. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  52164. * @param rootUrl a string that defines the root url for scene and resources
  52165. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52166. * @param scene the instance of BABYLON.Scene to append to
  52167. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  52168. * @param onProgress a callback with a progress event for each file being loaded
  52169. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52170. */
  52171. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52172. if (onSuccess === void 0) { onSuccess = null; }
  52173. if (onProgress === void 0) { onProgress = null; }
  52174. if (onError === void 0) { onError = null; }
  52175. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52176. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52177. return null;
  52178. }
  52179. var loadingToken = {};
  52180. scene._addPendingData(loadingToken);
  52181. var errorHandler = function (message, exception) {
  52182. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52183. if (onError) {
  52184. onError(scene, errorMessage, exception);
  52185. }
  52186. else {
  52187. BABYLON.Tools.Error(errorMessage);
  52188. // should the exception be thrown?
  52189. }
  52190. scene._removePendingData(loadingToken);
  52191. };
  52192. var progressHandler = function (event) {
  52193. if (onProgress) {
  52194. onProgress(event);
  52195. }
  52196. };
  52197. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52198. if (plugin.importMesh) {
  52199. var syncedPlugin = plugin;
  52200. var meshes = new Array();
  52201. var particleSystems = new Array();
  52202. var skeletons = new Array();
  52203. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  52204. return;
  52205. }
  52206. if (onSuccess) {
  52207. // wrap onSuccess with try-catch to know if something went wrong.
  52208. try {
  52209. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52210. onSuccess(meshes, particleSystems, skeletons);
  52211. scene._removePendingData(loadingToken);
  52212. }
  52213. catch (e) {
  52214. var message = 'Error in onSuccess callback.';
  52215. errorHandler(message, e);
  52216. }
  52217. }
  52218. }
  52219. else {
  52220. var asyncedPlugin = plugin;
  52221. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  52222. if (onSuccess) {
  52223. try {
  52224. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52225. onSuccess(meshes, particleSystems, skeletons);
  52226. scene._removePendingData(loadingToken);
  52227. }
  52228. catch (e) {
  52229. var message = 'Error in onSuccess callback.';
  52230. errorHandler(message, e);
  52231. }
  52232. }
  52233. }, progressHandler, errorHandler);
  52234. }
  52235. }, progressHandler, errorHandler, pluginExtension);
  52236. };
  52237. /**
  52238. * Load a scene
  52239. * @param rootUrl a string that defines the root url for scene and resources
  52240. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52241. * @param engine is the instance of BABYLON.Engine to use to create the scene
  52242. * @param onSuccess a callback with the scene when import succeeds
  52243. * @param onProgress a callback with a progress event for each file being loaded
  52244. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52245. */
  52246. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  52247. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  52248. };
  52249. /**
  52250. * Append a scene
  52251. * @param rootUrl a string that defines the root url for scene and resources
  52252. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52253. * @param scene is the instance of BABYLON.Scene to append to
  52254. * @param onSuccess a callback with the scene when import succeeds
  52255. * @param onProgress a callback with a progress event for each file being loaded
  52256. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52257. */
  52258. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52259. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52260. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52261. return null;
  52262. }
  52263. if (SceneLoader.ShowLoadingScreen) {
  52264. scene.getEngine().displayLoadingUI();
  52265. }
  52266. var loadingToken = {};
  52267. scene._addPendingData(loadingToken);
  52268. var errorHandler = function (message, exception) {
  52269. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52270. if (onError) {
  52271. onError(scene, errorMessage, exception);
  52272. }
  52273. else {
  52274. BABYLON.Tools.Error(errorMessage);
  52275. // should the exception be thrown?
  52276. }
  52277. scene._removePendingData(loadingToken);
  52278. scene.getEngine().hideLoadingUI();
  52279. };
  52280. var progressHandler = function (event) {
  52281. if (onProgress) {
  52282. onProgress(event);
  52283. }
  52284. };
  52285. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52286. if (plugin.load) {
  52287. var syncedPlugin = plugin;
  52288. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  52289. return;
  52290. }
  52291. if (onSuccess) {
  52292. try {
  52293. onSuccess(scene);
  52294. }
  52295. catch (e) {
  52296. errorHandler("Error in onSuccess callback", e);
  52297. }
  52298. }
  52299. scene.loadingPluginName = plugin.name;
  52300. scene._removePendingData(loadingToken);
  52301. }
  52302. else {
  52303. var asyncedPlugin = plugin;
  52304. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  52305. if (onSuccess) {
  52306. onSuccess(scene);
  52307. }
  52308. scene.loadingPluginName = plugin.name;
  52309. scene._removePendingData(loadingToken);
  52310. }, progressHandler, errorHandler);
  52311. }
  52312. if (SceneLoader.ShowLoadingScreen) {
  52313. scene.executeWhenReady(function () {
  52314. scene.getEngine().hideLoadingUI();
  52315. });
  52316. }
  52317. }, progressHandler, errorHandler, pluginExtension);
  52318. };
  52319. // Flags
  52320. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  52321. SceneLoader._ShowLoadingScreen = true;
  52322. SceneLoader._CleanBoneMatrixWeights = false;
  52323. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  52324. // Members
  52325. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  52326. SceneLoader._registeredPlugins = {};
  52327. return SceneLoader;
  52328. }());
  52329. BABYLON.SceneLoader = SceneLoader;
  52330. ;
  52331. })(BABYLON || (BABYLON = {}));
  52332. //# sourceMappingURL=babylon.sceneLoader.js.map
  52333. var BABYLON;
  52334. (function (BABYLON) {
  52335. var Internals;
  52336. (function (Internals) {
  52337. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52338. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52339. var parsedMaterial = parsedData.materials[index];
  52340. if (parsedMaterial.id === id) {
  52341. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52342. }
  52343. }
  52344. return null;
  52345. };
  52346. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52347. for (var i in names) {
  52348. if (mesh.name === names[i]) {
  52349. hierarchyIds.push(mesh.id);
  52350. return true;
  52351. }
  52352. }
  52353. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52354. hierarchyIds.push(mesh.id);
  52355. return true;
  52356. }
  52357. return false;
  52358. };
  52359. var logOperation = function (operation, producer) {
  52360. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52361. };
  52362. BABYLON.SceneLoader.RegisterPlugin({
  52363. name: "babylon.js",
  52364. extensions: ".babylon",
  52365. canDirectLoad: function (data) {
  52366. if (data.indexOf("babylon") !== -1) {
  52367. return true;
  52368. }
  52369. return false;
  52370. },
  52371. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52372. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52373. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52374. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52375. // and avoid problems with multiple concurrent .babylon loads.
  52376. var log = "importMesh has failed JSON parse";
  52377. try {
  52378. var parsedData = JSON.parse(data);
  52379. log = "";
  52380. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52381. if (!meshesNames) {
  52382. meshesNames = null;
  52383. }
  52384. else if (!Array.isArray(meshesNames)) {
  52385. meshesNames = [meshesNames];
  52386. }
  52387. var hierarchyIds = new Array();
  52388. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52389. var loadedSkeletonsIds = [];
  52390. var loadedMaterialsIds = [];
  52391. var index;
  52392. var cache;
  52393. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52394. var parsedMesh = parsedData.meshes[index];
  52395. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52396. if (meshesNames !== null) {
  52397. // Remove found mesh name from list.
  52398. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52399. }
  52400. //Geometry?
  52401. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  52402. //does the file contain geometries?
  52403. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  52404. //find the correct geometry and add it to the scene
  52405. var found = false;
  52406. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  52407. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  52408. return;
  52409. }
  52410. else {
  52411. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  52412. if (parsedGeometryData.id === parsedMesh.geometryId) {
  52413. switch (geometryType) {
  52414. case "boxes":
  52415. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  52416. break;
  52417. case "spheres":
  52418. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  52419. break;
  52420. case "cylinders":
  52421. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  52422. break;
  52423. case "toruses":
  52424. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  52425. break;
  52426. case "grounds":
  52427. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  52428. break;
  52429. case "planes":
  52430. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  52431. break;
  52432. case "torusKnots":
  52433. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  52434. break;
  52435. case "vertexData":
  52436. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  52437. break;
  52438. }
  52439. found = true;
  52440. }
  52441. });
  52442. }
  52443. });
  52444. if (found === false) {
  52445. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  52446. }
  52447. }
  52448. }
  52449. // Material ?
  52450. if (parsedMesh.materialId) {
  52451. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  52452. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52453. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  52454. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  52455. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  52456. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  52457. var subMatId = parsedMultiMaterial.materials[matIndex];
  52458. loadedMaterialsIds.push(subMatId);
  52459. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  52460. log += "\n\tMaterial " + mat.toString(fullDetails);
  52461. }
  52462. loadedMaterialsIds.push(parsedMultiMaterial.id);
  52463. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52464. materialFound = true;
  52465. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  52466. break;
  52467. }
  52468. }
  52469. }
  52470. if (materialFound === false) {
  52471. loadedMaterialsIds.push(parsedMesh.materialId);
  52472. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  52473. if (!mat) {
  52474. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  52475. }
  52476. else {
  52477. log += "\n\tMaterial " + mat.toString(fullDetails);
  52478. }
  52479. }
  52480. }
  52481. // Skeleton ?
  52482. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52483. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  52484. if (skeletonAlreadyLoaded === false) {
  52485. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  52486. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  52487. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  52488. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52489. skeletons.push(skeleton);
  52490. loadedSkeletonsIds.push(parsedSkeleton.id);
  52491. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  52492. }
  52493. }
  52494. }
  52495. }
  52496. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52497. meshes.push(mesh);
  52498. log += "\n\tMesh " + mesh.toString(fullDetails);
  52499. }
  52500. }
  52501. // Connecting parents
  52502. var currentMesh;
  52503. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52504. currentMesh = scene.meshes[index];
  52505. if (currentMesh._waitingParentId) {
  52506. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  52507. currentMesh._waitingParentId = null;
  52508. }
  52509. }
  52510. // freeze and compute world matrix application
  52511. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52512. currentMesh = scene.meshes[index];
  52513. if (currentMesh._waitingFreezeWorldMatrix) {
  52514. currentMesh.freezeWorldMatrix();
  52515. currentMesh._waitingFreezeWorldMatrix = null;
  52516. }
  52517. else {
  52518. currentMesh.computeWorldMatrix(true);
  52519. }
  52520. }
  52521. }
  52522. // Particles
  52523. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52524. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52525. var parsedParticleSystem = parsedData.particleSystems[index];
  52526. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  52527. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  52528. }
  52529. }
  52530. }
  52531. return true;
  52532. }
  52533. catch (err) {
  52534. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  52535. if (onError) {
  52536. onError(msg, err);
  52537. }
  52538. else {
  52539. BABYLON.Tools.Log(msg);
  52540. throw err;
  52541. }
  52542. }
  52543. finally {
  52544. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52545. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52546. }
  52547. }
  52548. return false;
  52549. },
  52550. load: function (scene, data, rootUrl, onError) {
  52551. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52552. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52553. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52554. // and avoid problems with multiple concurrent .babylon loads.
  52555. var log = "importScene has failed JSON parse";
  52556. try {
  52557. var parsedData = JSON.parse(data);
  52558. log = "";
  52559. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52560. // Scene
  52561. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  52562. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  52563. }
  52564. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  52565. scene.autoClear = parsedData.autoClear;
  52566. }
  52567. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  52568. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  52569. }
  52570. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  52571. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  52572. }
  52573. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  52574. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  52575. }
  52576. // Fog
  52577. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  52578. scene.fogMode = parsedData.fogMode;
  52579. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  52580. scene.fogStart = parsedData.fogStart;
  52581. scene.fogEnd = parsedData.fogEnd;
  52582. scene.fogDensity = parsedData.fogDensity;
  52583. log += "\tFog mode for scene: ";
  52584. switch (scene.fogMode) {
  52585. // getters not compiling, so using hardcoded
  52586. case 1:
  52587. log += "exp\n";
  52588. break;
  52589. case 2:
  52590. log += "exp2\n";
  52591. break;
  52592. case 3:
  52593. log += "linear\n";
  52594. break;
  52595. }
  52596. }
  52597. //Physics
  52598. if (parsedData.physicsEnabled) {
  52599. var physicsPlugin;
  52600. if (parsedData.physicsEngine === "cannon") {
  52601. physicsPlugin = new BABYLON.CannonJSPlugin();
  52602. }
  52603. else if (parsedData.physicsEngine === "oimo") {
  52604. physicsPlugin = new BABYLON.OimoJSPlugin();
  52605. }
  52606. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  52607. //else - default engine, which is currently oimo
  52608. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  52609. scene.enablePhysics(physicsGravity, physicsPlugin);
  52610. }
  52611. // Metadata
  52612. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  52613. scene.metadata = parsedData.metadata;
  52614. }
  52615. //collisions, if defined. otherwise, default is true
  52616. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  52617. scene.collisionsEnabled = parsedData.collisionsEnabled;
  52618. }
  52619. scene.workerCollisions = !!parsedData.workerCollisions;
  52620. var index;
  52621. var cache;
  52622. // Lights
  52623. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  52624. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  52625. var parsedLight = parsedData.lights[index];
  52626. var light = BABYLON.Light.Parse(parsedLight, scene);
  52627. if (light) {
  52628. log += (index === 0 ? "\n\tLights:" : "");
  52629. log += "\n\t\t" + light.toString(fullDetails);
  52630. }
  52631. }
  52632. }
  52633. // Animations
  52634. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  52635. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  52636. var parsedAnimation = parsedData.animations[index];
  52637. var animation = BABYLON.Animation.Parse(parsedAnimation);
  52638. scene.animations.push(animation);
  52639. log += (index === 0 ? "\n\tAnimations:" : "");
  52640. log += "\n\t\t" + animation.toString(fullDetails);
  52641. }
  52642. }
  52643. if (parsedData.autoAnimate) {
  52644. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  52645. }
  52646. // Materials
  52647. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  52648. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52649. var parsedMaterial = parsedData.materials[index];
  52650. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52651. log += (index === 0 ? "\n\tMaterials:" : "");
  52652. log += "\n\t\t" + mat.toString(fullDetails);
  52653. }
  52654. }
  52655. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52656. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  52657. var parsedMultiMaterial = parsedData.multiMaterials[index];
  52658. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52659. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  52660. log += "\n\t\t" + mmat.toString(fullDetails);
  52661. }
  52662. }
  52663. // Morph targets
  52664. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  52665. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  52666. var managerData = _a[_i];
  52667. BABYLON.MorphTargetManager.Parse(managerData, scene);
  52668. }
  52669. }
  52670. // Skeletons
  52671. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52672. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  52673. var parsedSkeleton = parsedData.skeletons[index];
  52674. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52675. log += (index === 0 ? "\n\tSkeletons:" : "");
  52676. log += "\n\t\t" + skeleton.toString(fullDetails);
  52677. }
  52678. }
  52679. // Geometries
  52680. var geometries = parsedData.geometries;
  52681. if (geometries !== undefined && geometries !== null) {
  52682. // Boxes
  52683. var boxes = geometries.boxes;
  52684. if (boxes !== undefined && boxes !== null) {
  52685. for (index = 0, cache = boxes.length; index < cache; index++) {
  52686. var parsedBox = boxes[index];
  52687. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  52688. }
  52689. }
  52690. // Spheres
  52691. var spheres = geometries.spheres;
  52692. if (spheres !== undefined && spheres !== null) {
  52693. for (index = 0, cache = spheres.length; index < cache; index++) {
  52694. var parsedSphere = spheres[index];
  52695. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  52696. }
  52697. }
  52698. // Cylinders
  52699. var cylinders = geometries.cylinders;
  52700. if (cylinders !== undefined && cylinders !== null) {
  52701. for (index = 0, cache = cylinders.length; index < cache; index++) {
  52702. var parsedCylinder = cylinders[index];
  52703. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  52704. }
  52705. }
  52706. // Toruses
  52707. var toruses = geometries.toruses;
  52708. if (toruses !== undefined && toruses !== null) {
  52709. for (index = 0, cache = toruses.length; index < cache; index++) {
  52710. var parsedTorus = toruses[index];
  52711. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  52712. }
  52713. }
  52714. // Grounds
  52715. var grounds = geometries.grounds;
  52716. if (grounds !== undefined && grounds !== null) {
  52717. for (index = 0, cache = grounds.length; index < cache; index++) {
  52718. var parsedGround = grounds[index];
  52719. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  52720. }
  52721. }
  52722. // Planes
  52723. var planes = geometries.planes;
  52724. if (planes !== undefined && planes !== null) {
  52725. for (index = 0, cache = planes.length; index < cache; index++) {
  52726. var parsedPlane = planes[index];
  52727. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  52728. }
  52729. }
  52730. // TorusKnots
  52731. var torusKnots = geometries.torusKnots;
  52732. if (torusKnots !== undefined && torusKnots !== null) {
  52733. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  52734. var parsedTorusKnot = torusKnots[index];
  52735. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  52736. }
  52737. }
  52738. // VertexData
  52739. var vertexData = geometries.vertexData;
  52740. if (vertexData !== undefined && vertexData !== null) {
  52741. for (index = 0, cache = vertexData.length; index < cache; index++) {
  52742. var parsedVertexData = vertexData[index];
  52743. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  52744. }
  52745. }
  52746. }
  52747. // Meshes
  52748. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52749. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52750. var parsedMesh = parsedData.meshes[index];
  52751. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52752. log += (index === 0 ? "\n\tMeshes:" : "");
  52753. log += "\n\t\t" + mesh.toString(fullDetails);
  52754. }
  52755. }
  52756. // Cameras
  52757. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  52758. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  52759. var parsedCamera = parsedData.cameras[index];
  52760. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  52761. log += (index === 0 ? "\n\tCameras:" : "");
  52762. log += "\n\t\t" + camera.toString(fullDetails);
  52763. }
  52764. }
  52765. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  52766. scene.setActiveCameraByID(parsedData.activeCameraID);
  52767. }
  52768. // Browsing all the graph to connect the dots
  52769. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  52770. var camera = scene.cameras[index];
  52771. if (camera._waitingParentId) {
  52772. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  52773. camera._waitingParentId = null;
  52774. }
  52775. }
  52776. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52777. var light_1 = scene.lights[index];
  52778. if (light_1 && light_1._waitingParentId) {
  52779. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  52780. light_1._waitingParentId = null;
  52781. }
  52782. }
  52783. // Sounds
  52784. var loadedSounds = [];
  52785. var loadedSound;
  52786. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  52787. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  52788. var parsedSound = parsedData.sounds[index];
  52789. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52790. if (!parsedSound.url)
  52791. parsedSound.url = parsedSound.name;
  52792. if (!loadedSounds[parsedSound.url]) {
  52793. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  52794. loadedSounds[parsedSound.url] = loadedSound;
  52795. }
  52796. else {
  52797. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  52798. }
  52799. }
  52800. else {
  52801. new BABYLON.Sound(parsedSound.name, null, scene);
  52802. }
  52803. }
  52804. }
  52805. loadedSounds = [];
  52806. // Connect parents & children and parse actions
  52807. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52808. var mesh = scene.meshes[index];
  52809. if (mesh._waitingParentId) {
  52810. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  52811. mesh._waitingParentId = null;
  52812. }
  52813. if (mesh._waitingActions) {
  52814. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  52815. mesh._waitingActions = null;
  52816. }
  52817. }
  52818. // freeze world matrix application
  52819. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52820. var currentMesh = scene.meshes[index];
  52821. if (currentMesh._waitingFreezeWorldMatrix) {
  52822. currentMesh.freezeWorldMatrix();
  52823. currentMesh._waitingFreezeWorldMatrix = null;
  52824. }
  52825. else {
  52826. currentMesh.computeWorldMatrix(true);
  52827. }
  52828. }
  52829. // Particles Systems
  52830. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52831. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52832. var parsedParticleSystem = parsedData.particleSystems[index];
  52833. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  52834. }
  52835. }
  52836. // Environment texture
  52837. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  52838. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  52839. if (parsedData.createDefaultSkybox === true) {
  52840. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  52841. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  52842. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  52843. }
  52844. }
  52845. // Lens flares
  52846. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  52847. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  52848. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  52849. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  52850. }
  52851. }
  52852. // Shadows
  52853. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  52854. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  52855. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  52856. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  52857. }
  52858. }
  52859. // Lights exclusions / inclusions
  52860. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52861. var light_2 = scene.lights[index];
  52862. // Excluded check
  52863. if (light_2._excludedMeshesIds.length > 0) {
  52864. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  52865. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  52866. if (excludedMesh) {
  52867. light_2.excludedMeshes.push(excludedMesh);
  52868. }
  52869. }
  52870. light_2._excludedMeshesIds = [];
  52871. }
  52872. // Included check
  52873. if (light_2._includedOnlyMeshesIds.length > 0) {
  52874. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  52875. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  52876. if (includedOnlyMesh) {
  52877. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  52878. }
  52879. }
  52880. light_2._includedOnlyMeshesIds = [];
  52881. }
  52882. }
  52883. // Actions (scene)
  52884. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  52885. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  52886. }
  52887. // Finish
  52888. return true;
  52889. }
  52890. catch (err) {
  52891. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  52892. if (onError) {
  52893. onError(msg, err);
  52894. }
  52895. else {
  52896. BABYLON.Tools.Log(msg);
  52897. throw err;
  52898. }
  52899. }
  52900. finally {
  52901. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52902. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52903. }
  52904. }
  52905. return false;
  52906. }
  52907. });
  52908. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52909. })(BABYLON || (BABYLON = {}));
  52910. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  52911. var BABYLON;
  52912. (function (BABYLON) {
  52913. var FilesInput = /** @class */ (function () {
  52914. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  52915. this.onProcessFileCallback = function () { return true; };
  52916. this._engine = engine;
  52917. this._currentScene = scene;
  52918. this._sceneLoadedCallback = sceneLoadedCallback;
  52919. this._progressCallback = progressCallback;
  52920. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  52921. this._textureLoadingCallback = textureLoadingCallback;
  52922. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  52923. this._onReloadCallback = onReloadCallback;
  52924. this._errorCallback = errorCallback;
  52925. }
  52926. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  52927. var _this = this;
  52928. if (elementToMonitor) {
  52929. this._elementToMonitor = elementToMonitor;
  52930. this._dragEnterHandler = function (e) { _this.drag(e); };
  52931. this._dragOverHandler = function (e) { _this.drag(e); };
  52932. this._dropHandler = function (e) { _this.drop(e); };
  52933. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  52934. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  52935. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  52936. }
  52937. };
  52938. FilesInput.prototype.dispose = function () {
  52939. if (!this._elementToMonitor) {
  52940. return;
  52941. }
  52942. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  52943. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  52944. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  52945. };
  52946. FilesInput.prototype.renderFunction = function () {
  52947. if (this._additionalRenderLoopLogicCallback) {
  52948. this._additionalRenderLoopLogicCallback();
  52949. }
  52950. if (this._currentScene) {
  52951. if (this._textureLoadingCallback) {
  52952. var remaining = this._currentScene.getWaitingItemsCount();
  52953. if (remaining > 0) {
  52954. this._textureLoadingCallback(remaining);
  52955. }
  52956. }
  52957. this._currentScene.render();
  52958. }
  52959. };
  52960. FilesInput.prototype.drag = function (e) {
  52961. e.stopPropagation();
  52962. e.preventDefault();
  52963. };
  52964. FilesInput.prototype.drop = function (eventDrop) {
  52965. eventDrop.stopPropagation();
  52966. eventDrop.preventDefault();
  52967. this.loadFiles(eventDrop);
  52968. };
  52969. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  52970. var _this = this;
  52971. var reader = folder.createReader();
  52972. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  52973. reader.readEntries(function (entries) {
  52974. remaining.count += entries.length;
  52975. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  52976. var entry = entries_1[_i];
  52977. if (entry.isFile) {
  52978. entry.file(function (file) {
  52979. file.correctName = relativePath + file.name;
  52980. files.push(file);
  52981. if (--remaining.count === 0) {
  52982. callback();
  52983. }
  52984. });
  52985. }
  52986. else if (entry.isDirectory) {
  52987. _this._traverseFolder(entry, files, remaining, callback);
  52988. }
  52989. }
  52990. if (--remaining.count) {
  52991. callback();
  52992. }
  52993. });
  52994. };
  52995. FilesInput.prototype._processFiles = function (files) {
  52996. var skippedFiles = 0;
  52997. for (var i = 0; i < files.length; i++) {
  52998. var name = files[i].correctName.toLowerCase();
  52999. var extension = name.split('.').pop();
  53000. if (!this.onProcessFileCallback(files[i], name, extension)) {
  53001. skippedFiles++;
  53002. continue;
  53003. }
  53004. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  53005. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  53006. this._sceneFileToLoad = files[i];
  53007. }
  53008. else {
  53009. FilesInput.FilesToLoad[name] = files[i];
  53010. }
  53011. }
  53012. if (this._onReloadCallback) {
  53013. this._onReloadCallback(this._sceneFileToLoad);
  53014. }
  53015. else if (skippedFiles < files.length) {
  53016. this.reload();
  53017. }
  53018. };
  53019. FilesInput.prototype.loadFiles = function (event) {
  53020. var _this = this;
  53021. if (this._startingProcessingFilesCallback)
  53022. this._startingProcessingFilesCallback();
  53023. // Handling data transfer via drag'n'drop
  53024. if (event && event.dataTransfer && event.dataTransfer.files) {
  53025. this._filesToLoad = event.dataTransfer.files;
  53026. }
  53027. // Handling files from input files
  53028. if (event && event.target && event.target.files) {
  53029. this._filesToLoad = event.target.files;
  53030. }
  53031. if (this._filesToLoad && this._filesToLoad.length > 0) {
  53032. var files_1 = new Array();
  53033. var folders = [];
  53034. var items = event.dataTransfer ? event.dataTransfer.items : null;
  53035. for (var i = 0; i < this._filesToLoad.length; i++) {
  53036. var fileToLoad = this._filesToLoad[i];
  53037. var name_1 = fileToLoad.name.toLowerCase();
  53038. var entry = void 0;
  53039. fileToLoad.correctName = name_1;
  53040. if (items) {
  53041. var item = items[i];
  53042. if (item.getAsEntry) {
  53043. entry = item.getAsEntry();
  53044. }
  53045. else if (item.webkitGetAsEntry) {
  53046. entry = item.webkitGetAsEntry();
  53047. }
  53048. }
  53049. if (!entry) {
  53050. files_1.push(fileToLoad);
  53051. }
  53052. else {
  53053. if (entry.isDirectory) {
  53054. folders.push(entry);
  53055. }
  53056. else {
  53057. files_1.push(fileToLoad);
  53058. }
  53059. }
  53060. }
  53061. if (folders.length === 0) {
  53062. this._processFiles(files_1);
  53063. }
  53064. else {
  53065. var remaining = { count: folders.length };
  53066. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  53067. var folder = folders_1[_i];
  53068. this._traverseFolder(folder, files_1, remaining, function () {
  53069. _this._processFiles(files_1);
  53070. });
  53071. }
  53072. }
  53073. }
  53074. };
  53075. FilesInput.prototype.reload = function () {
  53076. var _this = this;
  53077. // If a ".babylon" file has been provided
  53078. if (this._sceneFileToLoad) {
  53079. if (this._currentScene) {
  53080. if (BABYLON.Tools.errorsCount > 0) {
  53081. BABYLON.Tools.ClearLogCache();
  53082. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  53083. }
  53084. this._engine.stopRenderLoop();
  53085. this._currentScene.dispose();
  53086. }
  53087. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  53088. _this._currentScene = newScene;
  53089. if (_this._sceneLoadedCallback) {
  53090. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  53091. }
  53092. // Wait for textures and shaders to be ready
  53093. _this._currentScene.executeWhenReady(function () {
  53094. _this._engine.runRenderLoop(function () {
  53095. _this.renderFunction();
  53096. });
  53097. });
  53098. }, function (progress) {
  53099. if (_this._progressCallback) {
  53100. _this._progressCallback(progress);
  53101. }
  53102. }, function (scene, message) {
  53103. _this._currentScene = scene;
  53104. if (_this._errorCallback) {
  53105. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  53106. }
  53107. });
  53108. }
  53109. else {
  53110. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  53111. }
  53112. };
  53113. FilesInput.FilesToLoad = {};
  53114. return FilesInput;
  53115. }());
  53116. BABYLON.FilesInput = FilesInput;
  53117. })(BABYLON || (BABYLON = {}));
  53118. //# sourceMappingURL=babylon.filesInput.js.map
  53119. var BABYLON;
  53120. (function (BABYLON) {
  53121. /**
  53122. * This class implement a typical dictionary using a string as key and the generic type T as value.
  53123. * The underlying implementation relies on an associative array to ensure the best performances.
  53124. * The value can be anything including 'null' but except 'undefined'
  53125. */
  53126. var StringDictionary = /** @class */ (function () {
  53127. function StringDictionary() {
  53128. this._count = 0;
  53129. this._data = {};
  53130. }
  53131. /**
  53132. * This will clear this dictionary and copy the content from the 'source' one.
  53133. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  53134. * @param source the dictionary to take the content from and copy to this dictionary
  53135. */
  53136. StringDictionary.prototype.copyFrom = function (source) {
  53137. var _this = this;
  53138. this.clear();
  53139. source.forEach(function (t, v) { return _this.add(t, v); });
  53140. };
  53141. /**
  53142. * Get a value based from its key
  53143. * @param key the given key to get the matching value from
  53144. * @return the value if found, otherwise undefined is returned
  53145. */
  53146. StringDictionary.prototype.get = function (key) {
  53147. var val = this._data[key];
  53148. if (val !== undefined) {
  53149. return val;
  53150. }
  53151. return undefined;
  53152. };
  53153. /**
  53154. * Get a value from its key or add it if it doesn't exist.
  53155. * This method will ensure you that a given key/data will be present in the dictionary.
  53156. * @param key the given key to get the matching value from
  53157. * @param factory the factory that will create the value if the key is not present in the dictionary.
  53158. * The factory will only be invoked if there's no data for the given key.
  53159. * @return the value corresponding to the key.
  53160. */
  53161. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  53162. var val = this.get(key);
  53163. if (val !== undefined) {
  53164. return val;
  53165. }
  53166. val = factory(key);
  53167. if (val) {
  53168. this.add(key, val);
  53169. }
  53170. return val;
  53171. };
  53172. /**
  53173. * Get a value from its key if present in the dictionary otherwise add it
  53174. * @param key the key to get the value from
  53175. * @param val if there's no such key/value pair in the dictionary add it with this value
  53176. * @return the value corresponding to the key
  53177. */
  53178. StringDictionary.prototype.getOrAdd = function (key, val) {
  53179. var curVal = this.get(key);
  53180. if (curVal !== undefined) {
  53181. return curVal;
  53182. }
  53183. this.add(key, val);
  53184. return val;
  53185. };
  53186. /**
  53187. * Check if there's a given key in the dictionary
  53188. * @param key the key to check for
  53189. * @return true if the key is present, false otherwise
  53190. */
  53191. StringDictionary.prototype.contains = function (key) {
  53192. return this._data[key] !== undefined;
  53193. };
  53194. /**
  53195. * Add a new key and its corresponding value
  53196. * @param key the key to add
  53197. * @param value the value corresponding to the key
  53198. * @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
  53199. */
  53200. StringDictionary.prototype.add = function (key, value) {
  53201. if (this._data[key] !== undefined) {
  53202. return false;
  53203. }
  53204. this._data[key] = value;
  53205. ++this._count;
  53206. return true;
  53207. };
  53208. StringDictionary.prototype.set = function (key, value) {
  53209. if (this._data[key] === undefined) {
  53210. return false;
  53211. }
  53212. this._data[key] = value;
  53213. return true;
  53214. };
  53215. /**
  53216. * Get the element of the given key and remove it from the dictionary
  53217. * @param key
  53218. */
  53219. StringDictionary.prototype.getAndRemove = function (key) {
  53220. var val = this.get(key);
  53221. if (val !== undefined) {
  53222. delete this._data[key];
  53223. --this._count;
  53224. return val;
  53225. }
  53226. return null;
  53227. };
  53228. /**
  53229. * Remove a key/value from the dictionary.
  53230. * @param key the key to remove
  53231. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  53232. */
  53233. StringDictionary.prototype.remove = function (key) {
  53234. if (this.contains(key)) {
  53235. delete this._data[key];
  53236. --this._count;
  53237. return true;
  53238. }
  53239. return false;
  53240. };
  53241. /**
  53242. * Clear the whole content of the dictionary
  53243. */
  53244. StringDictionary.prototype.clear = function () {
  53245. this._data = {};
  53246. this._count = 0;
  53247. };
  53248. Object.defineProperty(StringDictionary.prototype, "count", {
  53249. get: function () {
  53250. return this._count;
  53251. },
  53252. enumerable: true,
  53253. configurable: true
  53254. });
  53255. /**
  53256. * Execute a callback on each key/val of the dictionary.
  53257. * Note that you can remove any element in this dictionary in the callback implementation
  53258. * @param callback the callback to execute on a given key/value pair
  53259. */
  53260. StringDictionary.prototype.forEach = function (callback) {
  53261. for (var cur in this._data) {
  53262. var val = this._data[cur];
  53263. callback(cur, val);
  53264. }
  53265. };
  53266. /**
  53267. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  53268. * If the callback returns null or undefined the method will iterate to the next key/value pair
  53269. * Note that you can remove any element in this dictionary in the callback implementation
  53270. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  53271. */
  53272. StringDictionary.prototype.first = function (callback) {
  53273. for (var cur in this._data) {
  53274. var val = this._data[cur];
  53275. var res = callback(cur, val);
  53276. if (res) {
  53277. return res;
  53278. }
  53279. }
  53280. return null;
  53281. };
  53282. return StringDictionary;
  53283. }());
  53284. BABYLON.StringDictionary = StringDictionary;
  53285. })(BABYLON || (BABYLON = {}));
  53286. //# sourceMappingURL=babylon.stringDictionary.js.map
  53287. var BABYLON;
  53288. (function (BABYLON) {
  53289. var Tags = /** @class */ (function () {
  53290. function Tags() {
  53291. }
  53292. Tags.EnableFor = function (obj) {
  53293. obj._tags = obj._tags || {};
  53294. obj.hasTags = function () {
  53295. return Tags.HasTags(obj);
  53296. };
  53297. obj.addTags = function (tagsString) {
  53298. return Tags.AddTagsTo(obj, tagsString);
  53299. };
  53300. obj.removeTags = function (tagsString) {
  53301. return Tags.RemoveTagsFrom(obj, tagsString);
  53302. };
  53303. obj.matchesTagsQuery = function (tagsQuery) {
  53304. return Tags.MatchesQuery(obj, tagsQuery);
  53305. };
  53306. };
  53307. Tags.DisableFor = function (obj) {
  53308. delete obj._tags;
  53309. delete obj.hasTags;
  53310. delete obj.addTags;
  53311. delete obj.removeTags;
  53312. delete obj.matchesTagsQuery;
  53313. };
  53314. Tags.HasTags = function (obj) {
  53315. if (!obj._tags) {
  53316. return false;
  53317. }
  53318. return !BABYLON.Tools.IsEmpty(obj._tags);
  53319. };
  53320. Tags.GetTags = function (obj, asString) {
  53321. if (asString === void 0) { asString = true; }
  53322. if (!obj._tags) {
  53323. return null;
  53324. }
  53325. if (asString) {
  53326. var tagsArray = [];
  53327. for (var tag in obj._tags) {
  53328. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53329. tagsArray.push(tag);
  53330. }
  53331. }
  53332. return tagsArray.join(" ");
  53333. }
  53334. else {
  53335. return obj._tags;
  53336. }
  53337. };
  53338. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53339. // a tag cannot start with '||', '&&', and '!'
  53340. // it cannot contain whitespaces
  53341. Tags.AddTagsTo = function (obj, tagsString) {
  53342. if (!tagsString) {
  53343. return;
  53344. }
  53345. if (typeof tagsString !== "string") {
  53346. return;
  53347. }
  53348. var tags = tagsString.split(" ");
  53349. tags.forEach(function (tag, index, array) {
  53350. Tags._AddTagTo(obj, tag);
  53351. });
  53352. };
  53353. Tags._AddTagTo = function (obj, tag) {
  53354. tag = tag.trim();
  53355. if (tag === "" || tag === "true" || tag === "false") {
  53356. return;
  53357. }
  53358. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53359. return;
  53360. }
  53361. Tags.EnableFor(obj);
  53362. obj._tags[tag] = true;
  53363. };
  53364. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53365. if (!Tags.HasTags(obj)) {
  53366. return;
  53367. }
  53368. var tags = tagsString.split(" ");
  53369. for (var t in tags) {
  53370. Tags._RemoveTagFrom(obj, tags[t]);
  53371. }
  53372. };
  53373. Tags._RemoveTagFrom = function (obj, tag) {
  53374. delete obj._tags[tag];
  53375. };
  53376. Tags.MatchesQuery = function (obj, tagsQuery) {
  53377. if (tagsQuery === undefined) {
  53378. return true;
  53379. }
  53380. if (tagsQuery === "") {
  53381. return Tags.HasTags(obj);
  53382. }
  53383. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53384. };
  53385. return Tags;
  53386. }());
  53387. BABYLON.Tags = Tags;
  53388. })(BABYLON || (BABYLON = {}));
  53389. //# sourceMappingURL=babylon.tags.js.map
  53390. var BABYLON;
  53391. (function (BABYLON) {
  53392. var Internals;
  53393. (function (Internals) {
  53394. var AndOrNotEvaluator = /** @class */ (function () {
  53395. function AndOrNotEvaluator() {
  53396. }
  53397. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  53398. if (!query.match(/\([^\(\)]*\)/g)) {
  53399. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  53400. }
  53401. else {
  53402. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  53403. // remove parenthesis
  53404. r = r.slice(1, r.length - 1);
  53405. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  53406. });
  53407. }
  53408. if (query === "true") {
  53409. return true;
  53410. }
  53411. if (query === "false") {
  53412. return false;
  53413. }
  53414. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  53415. };
  53416. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  53417. evaluateCallback = evaluateCallback || (function (r) {
  53418. return r === "true" ? true : false;
  53419. });
  53420. var result;
  53421. var or = parenthesisContent.split("||");
  53422. for (var i in or) {
  53423. if (or.hasOwnProperty(i)) {
  53424. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  53425. var and = ori.split("&&");
  53426. if (and.length > 1) {
  53427. for (var j = 0; j < and.length; ++j) {
  53428. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  53429. if (andj !== "true" && andj !== "false") {
  53430. if (andj[0] === "!") {
  53431. result = !evaluateCallback(andj.substring(1));
  53432. }
  53433. else {
  53434. result = evaluateCallback(andj);
  53435. }
  53436. }
  53437. else {
  53438. result = andj === "true" ? true : false;
  53439. }
  53440. if (!result) {
  53441. ori = "false";
  53442. break;
  53443. }
  53444. }
  53445. }
  53446. if (result || ori === "true") {
  53447. result = true;
  53448. break;
  53449. }
  53450. // result equals false (or undefined)
  53451. if (ori !== "true" && ori !== "false") {
  53452. if (ori[0] === "!") {
  53453. result = !evaluateCallback(ori.substring(1));
  53454. }
  53455. else {
  53456. result = evaluateCallback(ori);
  53457. }
  53458. }
  53459. else {
  53460. result = ori === "true" ? true : false;
  53461. }
  53462. }
  53463. }
  53464. // the whole parenthesis scope is replaced by 'true' or 'false'
  53465. return result ? "true" : "false";
  53466. };
  53467. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  53468. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  53469. // remove whitespaces
  53470. r = r.replace(/[\s]/g, function () { return ""; });
  53471. return r.length % 2 ? "!" : "";
  53472. });
  53473. booleanString = booleanString.trim();
  53474. if (booleanString === "!true") {
  53475. booleanString = "false";
  53476. }
  53477. else if (booleanString === "!false") {
  53478. booleanString = "true";
  53479. }
  53480. return booleanString;
  53481. };
  53482. return AndOrNotEvaluator;
  53483. }());
  53484. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  53485. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53486. })(BABYLON || (BABYLON = {}));
  53487. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  53488. var BABYLON;
  53489. (function (BABYLON) {
  53490. var Database = /** @class */ (function () {
  53491. function Database(urlToScene, callbackManifestChecked) {
  53492. // Handling various flavors of prefixed version of IndexedDB
  53493. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  53494. this.callbackManifestChecked = callbackManifestChecked;
  53495. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  53496. this.db = null;
  53497. this._enableSceneOffline = false;
  53498. this._enableTexturesOffline = false;
  53499. this.manifestVersionFound = 0;
  53500. this.mustUpdateRessources = false;
  53501. this.hasReachedQuota = false;
  53502. if (!Database.IDBStorageEnabled) {
  53503. this.callbackManifestChecked(true);
  53504. }
  53505. else {
  53506. this.checkManifestFile();
  53507. }
  53508. }
  53509. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  53510. get: function () {
  53511. return this._enableSceneOffline;
  53512. },
  53513. enumerable: true,
  53514. configurable: true
  53515. });
  53516. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  53517. get: function () {
  53518. return this._enableTexturesOffline;
  53519. },
  53520. enumerable: true,
  53521. configurable: true
  53522. });
  53523. Database.prototype.checkManifestFile = function () {
  53524. var _this = this;
  53525. var noManifestFile = function () {
  53526. _this._enableSceneOffline = false;
  53527. _this._enableTexturesOffline = false;
  53528. _this.callbackManifestChecked(false);
  53529. };
  53530. var timeStampUsed = false;
  53531. var manifestURL = this.currentSceneUrl + ".manifest";
  53532. var xhr = new XMLHttpRequest();
  53533. if (navigator.onLine) {
  53534. // Adding a timestamp to by-pass browsers' cache
  53535. timeStampUsed = true;
  53536. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  53537. }
  53538. xhr.open("GET", manifestURL, true);
  53539. xhr.addEventListener("load", function () {
  53540. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53541. try {
  53542. var manifestFile = JSON.parse(xhr.response);
  53543. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  53544. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  53545. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  53546. _this.manifestVersionFound = manifestFile.version;
  53547. }
  53548. if (_this.callbackManifestChecked) {
  53549. _this.callbackManifestChecked(true);
  53550. }
  53551. }
  53552. catch (ex) {
  53553. noManifestFile();
  53554. }
  53555. }
  53556. else {
  53557. noManifestFile();
  53558. }
  53559. }, false);
  53560. xhr.addEventListener("error", function (event) {
  53561. if (timeStampUsed) {
  53562. timeStampUsed = false;
  53563. // Let's retry without the timeStamp
  53564. // It could fail when coupled with HTML5 Offline API
  53565. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  53566. xhr.open("GET", retryManifestURL, true);
  53567. xhr.send();
  53568. }
  53569. else {
  53570. noManifestFile();
  53571. }
  53572. }, false);
  53573. try {
  53574. xhr.send();
  53575. }
  53576. catch (ex) {
  53577. BABYLON.Tools.Error("Error on XHR send request.");
  53578. this.callbackManifestChecked(false);
  53579. }
  53580. };
  53581. Database.prototype.openAsync = function (successCallback, errorCallback) {
  53582. var _this = this;
  53583. var handleError = function () {
  53584. _this.isSupported = false;
  53585. if (errorCallback)
  53586. errorCallback();
  53587. };
  53588. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  53589. // Your browser doesn't support IndexedDB
  53590. this.isSupported = false;
  53591. if (errorCallback)
  53592. errorCallback();
  53593. }
  53594. else {
  53595. // If the DB hasn't been opened or created yet
  53596. if (!this.db) {
  53597. this.hasReachedQuota = false;
  53598. this.isSupported = true;
  53599. var request = this.idbFactory.open("babylonjs", 1);
  53600. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  53601. request.onerror = function (event) {
  53602. handleError();
  53603. };
  53604. // executes when a version change transaction cannot complete due to other active transactions
  53605. request.onblocked = function (event) {
  53606. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  53607. handleError();
  53608. };
  53609. // DB has been opened successfully
  53610. request.onsuccess = function (event) {
  53611. _this.db = request.result;
  53612. successCallback();
  53613. };
  53614. // Initialization of the DB. Creating Scenes & Textures stores
  53615. request.onupgradeneeded = function (event) {
  53616. _this.db = (event.target).result;
  53617. if (_this.db) {
  53618. try {
  53619. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  53620. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  53621. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  53622. }
  53623. catch (ex) {
  53624. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  53625. handleError();
  53626. }
  53627. }
  53628. };
  53629. }
  53630. else {
  53631. if (successCallback)
  53632. successCallback();
  53633. }
  53634. }
  53635. };
  53636. Database.prototype.loadImageFromDB = function (url, image) {
  53637. var _this = this;
  53638. var completeURL = Database.ReturnFullUrlLocation(url);
  53639. var saveAndLoadImage = function () {
  53640. if (!_this.hasReachedQuota && _this.db !== null) {
  53641. // the texture is not yet in the DB, let's try to save it
  53642. _this._saveImageIntoDBAsync(completeURL, image);
  53643. }
  53644. else {
  53645. image.src = url;
  53646. }
  53647. };
  53648. if (!this.mustUpdateRessources) {
  53649. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  53650. }
  53651. else {
  53652. saveAndLoadImage();
  53653. }
  53654. };
  53655. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  53656. if (this.isSupported && this.db !== null) {
  53657. var texture;
  53658. var transaction = this.db.transaction(["textures"]);
  53659. transaction.onabort = function (event) {
  53660. image.src = url;
  53661. };
  53662. transaction.oncomplete = function (event) {
  53663. var blobTextureURL;
  53664. if (texture) {
  53665. var URL = window.URL || window.webkitURL;
  53666. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  53667. image.onerror = function () {
  53668. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  53669. image.src = url;
  53670. };
  53671. image.src = blobTextureURL;
  53672. }
  53673. else {
  53674. notInDBCallback();
  53675. }
  53676. };
  53677. var getRequest = transaction.objectStore("textures").get(url);
  53678. getRequest.onsuccess = function (event) {
  53679. texture = (event.target).result;
  53680. };
  53681. getRequest.onerror = function (event) {
  53682. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  53683. image.src = url;
  53684. };
  53685. }
  53686. else {
  53687. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53688. image.src = url;
  53689. }
  53690. };
  53691. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  53692. var _this = this;
  53693. if (this.isSupported) {
  53694. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  53695. var generateBlobUrl = function () {
  53696. var blobTextureURL;
  53697. if (blob) {
  53698. var URL = window.URL || window.webkitURL;
  53699. try {
  53700. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  53701. }
  53702. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  53703. catch (ex) {
  53704. blobTextureURL = URL.createObjectURL(blob);
  53705. }
  53706. }
  53707. if (blobTextureURL) {
  53708. image.src = blobTextureURL;
  53709. }
  53710. };
  53711. if (Database.IsUASupportingBlobStorage) {
  53712. var xhr = new XMLHttpRequest(), blob;
  53713. xhr.open("GET", url, true);
  53714. xhr.responseType = "blob";
  53715. xhr.addEventListener("load", function () {
  53716. if (xhr.status === 200 && _this.db) {
  53717. // Blob as response (XHR2)
  53718. blob = xhr.response;
  53719. var transaction = _this.db.transaction(["textures"], "readwrite");
  53720. // the transaction could abort because of a QuotaExceededError error
  53721. transaction.onabort = function (event) {
  53722. try {
  53723. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53724. var srcElement = (event.srcElement || event.target);
  53725. var error = srcElement.error;
  53726. if (error && error.name === "QuotaExceededError") {
  53727. _this.hasReachedQuota = true;
  53728. }
  53729. }
  53730. catch (ex) { }
  53731. generateBlobUrl();
  53732. };
  53733. transaction.oncomplete = function (event) {
  53734. generateBlobUrl();
  53735. };
  53736. var newTexture = { textureUrl: url, data: blob };
  53737. try {
  53738. // Put the blob into the dabase
  53739. var addRequest = transaction.objectStore("textures").put(newTexture);
  53740. addRequest.onsuccess = function (event) {
  53741. };
  53742. addRequest.onerror = function (event) {
  53743. generateBlobUrl();
  53744. };
  53745. }
  53746. catch (ex) {
  53747. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  53748. if (ex.code === 25) {
  53749. Database.IsUASupportingBlobStorage = false;
  53750. }
  53751. image.src = url;
  53752. }
  53753. }
  53754. else {
  53755. image.src = url;
  53756. }
  53757. }, false);
  53758. xhr.addEventListener("error", function (event) {
  53759. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  53760. image.src = url;
  53761. }, false);
  53762. xhr.send();
  53763. }
  53764. else {
  53765. image.src = url;
  53766. }
  53767. }
  53768. else {
  53769. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53770. image.src = url;
  53771. }
  53772. };
  53773. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  53774. var _this = this;
  53775. var updateVersion = function () {
  53776. // the version is not yet in the DB or we need to update it
  53777. _this._saveVersionIntoDBAsync(url, versionLoaded);
  53778. };
  53779. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  53780. };
  53781. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  53782. var _this = this;
  53783. if (this.isSupported && this.db) {
  53784. var version;
  53785. try {
  53786. var transaction = this.db.transaction(["versions"]);
  53787. transaction.oncomplete = function (event) {
  53788. if (version) {
  53789. // If the version in the JSON file is > than the version in DB
  53790. if (_this.manifestVersionFound > version.data) {
  53791. _this.mustUpdateRessources = true;
  53792. updateInDBCallback();
  53793. }
  53794. else {
  53795. callback(version.data);
  53796. }
  53797. }
  53798. else {
  53799. _this.mustUpdateRessources = true;
  53800. updateInDBCallback();
  53801. }
  53802. };
  53803. transaction.onabort = function (event) {
  53804. callback(-1);
  53805. };
  53806. var getRequest = transaction.objectStore("versions").get(url);
  53807. getRequest.onsuccess = function (event) {
  53808. version = (event.target).result;
  53809. };
  53810. getRequest.onerror = function (event) {
  53811. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  53812. callback(-1);
  53813. };
  53814. }
  53815. catch (ex) {
  53816. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  53817. callback(-1);
  53818. }
  53819. }
  53820. else {
  53821. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53822. callback(-1);
  53823. }
  53824. };
  53825. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  53826. var _this = this;
  53827. if (this.isSupported && !this.hasReachedQuota && this.db) {
  53828. try {
  53829. // Open a transaction to the database
  53830. var transaction = this.db.transaction(["versions"], "readwrite");
  53831. // the transaction could abort because of a QuotaExceededError error
  53832. transaction.onabort = function (event) {
  53833. try {
  53834. var error = event.srcElement['error'];
  53835. if (error && error.name === "QuotaExceededError") {
  53836. _this.hasReachedQuota = true;
  53837. }
  53838. }
  53839. catch (ex) { }
  53840. callback(-1);
  53841. };
  53842. transaction.oncomplete = function (event) {
  53843. callback(_this.manifestVersionFound);
  53844. };
  53845. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  53846. // Put the scene into the database
  53847. var addRequest = transaction.objectStore("versions").put(newVersion);
  53848. addRequest.onsuccess = function (event) {
  53849. };
  53850. addRequest.onerror = function (event) {
  53851. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  53852. };
  53853. }
  53854. catch (ex) {
  53855. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  53856. callback(-1);
  53857. }
  53858. }
  53859. else {
  53860. callback(-1);
  53861. }
  53862. };
  53863. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  53864. var _this = this;
  53865. var completeUrl = Database.ReturnFullUrlLocation(url);
  53866. var saveAndLoadFile = function () {
  53867. // the scene is not yet in the DB, let's try to save it
  53868. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  53869. };
  53870. this._checkVersionFromDB(completeUrl, function (version) {
  53871. if (version !== -1) {
  53872. if (!_this.mustUpdateRessources) {
  53873. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  53874. }
  53875. else {
  53876. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  53877. }
  53878. }
  53879. else {
  53880. if (errorCallback) {
  53881. errorCallback();
  53882. }
  53883. }
  53884. });
  53885. };
  53886. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  53887. if (this.isSupported && this.db) {
  53888. var targetStore;
  53889. if (url.indexOf(".babylon") !== -1) {
  53890. targetStore = "scenes";
  53891. }
  53892. else {
  53893. targetStore = "textures";
  53894. }
  53895. var file;
  53896. var transaction = this.db.transaction([targetStore]);
  53897. transaction.oncomplete = function (event) {
  53898. if (file) {
  53899. callback(file.data);
  53900. }
  53901. else {
  53902. notInDBCallback();
  53903. }
  53904. };
  53905. transaction.onabort = function (event) {
  53906. notInDBCallback();
  53907. };
  53908. var getRequest = transaction.objectStore(targetStore).get(url);
  53909. getRequest.onsuccess = function (event) {
  53910. file = (event.target).result;
  53911. };
  53912. getRequest.onerror = function (event) {
  53913. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  53914. notInDBCallback();
  53915. };
  53916. }
  53917. else {
  53918. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53919. callback();
  53920. }
  53921. };
  53922. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  53923. var _this = this;
  53924. if (this.isSupported) {
  53925. var targetStore;
  53926. if (url.indexOf(".babylon") !== -1) {
  53927. targetStore = "scenes";
  53928. }
  53929. else {
  53930. targetStore = "textures";
  53931. }
  53932. // Create XHR
  53933. var xhr = new XMLHttpRequest();
  53934. var fileData;
  53935. xhr.open("GET", url, true);
  53936. if (useArrayBuffer) {
  53937. xhr.responseType = "arraybuffer";
  53938. }
  53939. if (progressCallback) {
  53940. xhr.onprogress = progressCallback;
  53941. }
  53942. xhr.addEventListener("load", function () {
  53943. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  53944. // Blob as response (XHR2)
  53945. //fileData = xhr.responseText;
  53946. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  53947. if (!_this.hasReachedQuota && _this.db) {
  53948. // Open a transaction to the database
  53949. var transaction = _this.db.transaction([targetStore], "readwrite");
  53950. // the transaction could abort because of a QuotaExceededError error
  53951. transaction.onabort = function (event) {
  53952. try {
  53953. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53954. var error = event.srcElement['error'];
  53955. if (error && error.name === "QuotaExceededError") {
  53956. _this.hasReachedQuota = true;
  53957. }
  53958. }
  53959. catch (ex) { }
  53960. callback(fileData);
  53961. };
  53962. transaction.oncomplete = function (event) {
  53963. callback(fileData);
  53964. };
  53965. var newFile;
  53966. if (targetStore === "scenes") {
  53967. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  53968. }
  53969. else {
  53970. newFile = { textureUrl: url, data: fileData };
  53971. }
  53972. try {
  53973. // Put the scene into the database
  53974. var addRequest = transaction.objectStore(targetStore).put(newFile);
  53975. addRequest.onsuccess = function (event) {
  53976. };
  53977. addRequest.onerror = function (event) {
  53978. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  53979. };
  53980. }
  53981. catch (ex) {
  53982. callback(fileData);
  53983. }
  53984. }
  53985. else {
  53986. callback(fileData);
  53987. }
  53988. }
  53989. else {
  53990. callback();
  53991. }
  53992. }, false);
  53993. xhr.addEventListener("error", function (event) {
  53994. BABYLON.Tools.Error("error on XHR request.");
  53995. callback();
  53996. }, false);
  53997. xhr.send();
  53998. }
  53999. else {
  54000. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54001. callback();
  54002. }
  54003. };
  54004. Database.IsUASupportingBlobStorage = true;
  54005. Database.IDBStorageEnabled = true;
  54006. Database.parseURL = function (url) {
  54007. var a = document.createElement('a');
  54008. a.href = url;
  54009. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  54010. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  54011. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  54012. return absLocation;
  54013. };
  54014. Database.ReturnFullUrlLocation = function (url) {
  54015. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  54016. return (Database.parseURL(window.location.href) + url);
  54017. }
  54018. else {
  54019. return url;
  54020. }
  54021. };
  54022. return Database;
  54023. }());
  54024. BABYLON.Database = Database;
  54025. })(BABYLON || (BABYLON = {}));
  54026. //# sourceMappingURL=babylon.database.js.map
  54027. var BABYLON;
  54028. (function (BABYLON) {
  54029. var FresnelParameters = /** @class */ (function () {
  54030. function FresnelParameters() {
  54031. this._isEnabled = true;
  54032. this.leftColor = BABYLON.Color3.White();
  54033. this.rightColor = BABYLON.Color3.Black();
  54034. this.bias = 0;
  54035. this.power = 1;
  54036. }
  54037. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  54038. get: function () {
  54039. return this._isEnabled;
  54040. },
  54041. set: function (value) {
  54042. if (this._isEnabled === value) {
  54043. return;
  54044. }
  54045. this._isEnabled = value;
  54046. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  54047. },
  54048. enumerable: true,
  54049. configurable: true
  54050. });
  54051. FresnelParameters.prototype.clone = function () {
  54052. var newFresnelParameters = new FresnelParameters();
  54053. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  54054. return newFresnelParameters;
  54055. };
  54056. FresnelParameters.prototype.serialize = function () {
  54057. var serializationObject = {};
  54058. serializationObject.isEnabled = this.isEnabled;
  54059. serializationObject.leftColor = this.leftColor;
  54060. serializationObject.rightColor = this.rightColor;
  54061. serializationObject.bias = this.bias;
  54062. serializationObject.power = this.power;
  54063. return serializationObject;
  54064. };
  54065. FresnelParameters.Parse = function (parsedFresnelParameters) {
  54066. var fresnelParameters = new FresnelParameters();
  54067. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  54068. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  54069. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  54070. fresnelParameters.bias = parsedFresnelParameters.bias;
  54071. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  54072. return fresnelParameters;
  54073. };
  54074. return FresnelParameters;
  54075. }());
  54076. BABYLON.FresnelParameters = FresnelParameters;
  54077. })(BABYLON || (BABYLON = {}));
  54078. //# sourceMappingURL=babylon.fresnelParameters.js.map
  54079. var BABYLON;
  54080. (function (BABYLON) {
  54081. var MultiMaterial = /** @class */ (function (_super) {
  54082. __extends(MultiMaterial, _super);
  54083. function MultiMaterial(name, scene) {
  54084. var _this = _super.call(this, name, scene, true) || this;
  54085. scene.multiMaterials.push(_this);
  54086. _this.subMaterials = new Array();
  54087. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  54088. return _this;
  54089. }
  54090. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  54091. get: function () {
  54092. return this._subMaterials;
  54093. },
  54094. set: function (value) {
  54095. this._subMaterials = value;
  54096. this._hookArray(value);
  54097. },
  54098. enumerable: true,
  54099. configurable: true
  54100. });
  54101. MultiMaterial.prototype._hookArray = function (array) {
  54102. var _this = this;
  54103. var oldPush = array.push;
  54104. array.push = function () {
  54105. var items = [];
  54106. for (var _i = 0; _i < arguments.length; _i++) {
  54107. items[_i] = arguments[_i];
  54108. }
  54109. var result = oldPush.apply(array, items);
  54110. _this._markAllSubMeshesAsTexturesDirty();
  54111. return result;
  54112. };
  54113. var oldSplice = array.splice;
  54114. array.splice = function (index, deleteCount) {
  54115. var deleted = oldSplice.apply(array, [index, deleteCount]);
  54116. _this._markAllSubMeshesAsTexturesDirty();
  54117. return deleted;
  54118. };
  54119. };
  54120. // Properties
  54121. MultiMaterial.prototype.getSubMaterial = function (index) {
  54122. if (index < 0 || index >= this.subMaterials.length) {
  54123. return this.getScene().defaultMaterial;
  54124. }
  54125. return this.subMaterials[index];
  54126. };
  54127. MultiMaterial.prototype.getActiveTextures = function () {
  54128. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  54129. if (subMaterial) {
  54130. return subMaterial.getActiveTextures();
  54131. }
  54132. else {
  54133. return [];
  54134. }
  54135. }));
  54136. var _a;
  54137. };
  54138. // Methods
  54139. MultiMaterial.prototype.getClassName = function () {
  54140. return "MultiMaterial";
  54141. };
  54142. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  54143. for (var index = 0; index < this.subMaterials.length; index++) {
  54144. var subMaterial = this.subMaterials[index];
  54145. if (subMaterial) {
  54146. if (subMaterial.storeEffectOnSubMeshes) {
  54147. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  54148. return false;
  54149. }
  54150. continue;
  54151. }
  54152. if (!subMaterial.isReady(mesh)) {
  54153. return false;
  54154. }
  54155. }
  54156. }
  54157. return true;
  54158. };
  54159. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  54160. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  54161. for (var index = 0; index < this.subMaterials.length; index++) {
  54162. var subMaterial = null;
  54163. var current = this.subMaterials[index];
  54164. if (cloneChildren && current) {
  54165. subMaterial = current.clone(name + "-" + current.name);
  54166. }
  54167. else {
  54168. subMaterial = this.subMaterials[index];
  54169. }
  54170. newMultiMaterial.subMaterials.push(subMaterial);
  54171. }
  54172. return newMultiMaterial;
  54173. };
  54174. MultiMaterial.prototype.serialize = function () {
  54175. var serializationObject = {};
  54176. serializationObject.name = this.name;
  54177. serializationObject.id = this.id;
  54178. serializationObject.tags = BABYLON.Tags.GetTags(this);
  54179. serializationObject.materials = [];
  54180. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  54181. var subMat = this.subMaterials[matIndex];
  54182. if (subMat) {
  54183. serializationObject.materials.push(subMat.id);
  54184. }
  54185. else {
  54186. serializationObject.materials.push(null);
  54187. }
  54188. }
  54189. return serializationObject;
  54190. };
  54191. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54192. var scene = this.getScene();
  54193. if (!scene) {
  54194. return;
  54195. }
  54196. var index = scene.multiMaterials.indexOf(this);
  54197. if (index >= 0) {
  54198. scene.multiMaterials.splice(index, 1);
  54199. }
  54200. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54201. };
  54202. return MultiMaterial;
  54203. }(BABYLON.Material));
  54204. BABYLON.MultiMaterial = MultiMaterial;
  54205. })(BABYLON || (BABYLON = {}));
  54206. //# sourceMappingURL=babylon.multiMaterial.js.map
  54207. var BABYLON;
  54208. (function (BABYLON) {
  54209. var FreeCameraTouchInput = /** @class */ (function () {
  54210. function FreeCameraTouchInput() {
  54211. this._offsetX = null;
  54212. this._offsetY = null;
  54213. this._pointerCount = 0;
  54214. this._pointerPressed = new Array();
  54215. this.touchAngularSensibility = 200000.0;
  54216. this.touchMoveSensibility = 250.0;
  54217. }
  54218. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  54219. var _this = this;
  54220. var previousPosition = null;
  54221. if (this._pointerInput === undefined) {
  54222. this._onLostFocus = function (evt) {
  54223. _this._offsetX = null;
  54224. _this._offsetY = null;
  54225. };
  54226. this._pointerInput = function (p, s) {
  54227. var evt = p.event;
  54228. if (evt.pointerType === "mouse") {
  54229. return;
  54230. }
  54231. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  54232. if (!noPreventDefault) {
  54233. evt.preventDefault();
  54234. }
  54235. _this._pointerPressed.push(evt.pointerId);
  54236. if (_this._pointerPressed.length !== 1) {
  54237. return;
  54238. }
  54239. previousPosition = {
  54240. x: evt.clientX,
  54241. y: evt.clientY
  54242. };
  54243. }
  54244. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  54245. if (!noPreventDefault) {
  54246. evt.preventDefault();
  54247. }
  54248. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54249. if (index === -1) {
  54250. return;
  54251. }
  54252. _this._pointerPressed.splice(index, 1);
  54253. if (index != 0) {
  54254. return;
  54255. }
  54256. previousPosition = null;
  54257. _this._offsetX = null;
  54258. _this._offsetY = null;
  54259. }
  54260. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  54261. if (!noPreventDefault) {
  54262. evt.preventDefault();
  54263. }
  54264. if (!previousPosition) {
  54265. return;
  54266. }
  54267. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54268. if (index != 0) {
  54269. return;
  54270. }
  54271. _this._offsetX = evt.clientX - previousPosition.x;
  54272. _this._offsetY = -(evt.clientY - previousPosition.y);
  54273. }
  54274. };
  54275. }
  54276. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  54277. if (this._onLostFocus) {
  54278. element.addEventListener("blur", this._onLostFocus);
  54279. }
  54280. };
  54281. FreeCameraTouchInput.prototype.detachControl = function (element) {
  54282. if (this._pointerInput && element) {
  54283. if (this._observer) {
  54284. this.camera.getScene().onPointerObservable.remove(this._observer);
  54285. this._observer = null;
  54286. }
  54287. if (this._onLostFocus) {
  54288. element.removeEventListener("blur", this._onLostFocus);
  54289. this._onLostFocus = null;
  54290. }
  54291. this._pointerPressed = [];
  54292. this._offsetX = null;
  54293. this._offsetY = null;
  54294. this._pointerCount = 0;
  54295. }
  54296. };
  54297. FreeCameraTouchInput.prototype.checkInputs = function () {
  54298. if (this._offsetX && this._offsetY) {
  54299. var camera = this.camera;
  54300. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  54301. if (this._pointerPressed.length > 1) {
  54302. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  54303. }
  54304. else {
  54305. var speed = camera._computeLocalCameraSpeed();
  54306. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  54307. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  54308. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  54309. }
  54310. }
  54311. };
  54312. FreeCameraTouchInput.prototype.getClassName = function () {
  54313. return "FreeCameraTouchInput";
  54314. };
  54315. FreeCameraTouchInput.prototype.getSimpleName = function () {
  54316. return "touch";
  54317. };
  54318. __decorate([
  54319. BABYLON.serialize()
  54320. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  54321. __decorate([
  54322. BABYLON.serialize()
  54323. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  54324. return FreeCameraTouchInput;
  54325. }());
  54326. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  54327. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54328. })(BABYLON || (BABYLON = {}));
  54329. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54330. var BABYLON;
  54331. (function (BABYLON) {
  54332. // We're mainly based on the logic defined into the FreeCamera code
  54333. var TouchCamera = /** @class */ (function (_super) {
  54334. __extends(TouchCamera, _super);
  54335. //-- end properties for backward compatibility for inputs
  54336. function TouchCamera(name, position, scene) {
  54337. var _this = _super.call(this, name, position, scene) || this;
  54338. _this.inputs.addTouch();
  54339. _this._setupInputs();
  54340. return _this;
  54341. }
  54342. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54343. //-- Begin properties for backward compatibility for inputs
  54344. get: function () {
  54345. var touch = this.inputs.attached["touch"];
  54346. if (touch)
  54347. return touch.touchAngularSensibility;
  54348. return 0;
  54349. },
  54350. set: function (value) {
  54351. var touch = this.inputs.attached["touch"];
  54352. if (touch)
  54353. touch.touchAngularSensibility = value;
  54354. },
  54355. enumerable: true,
  54356. configurable: true
  54357. });
  54358. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54359. get: function () {
  54360. var touch = this.inputs.attached["touch"];
  54361. if (touch)
  54362. return touch.touchMoveSensibility;
  54363. return 0;
  54364. },
  54365. set: function (value) {
  54366. var touch = this.inputs.attached["touch"];
  54367. if (touch)
  54368. touch.touchMoveSensibility = value;
  54369. },
  54370. enumerable: true,
  54371. configurable: true
  54372. });
  54373. TouchCamera.prototype.getClassName = function () {
  54374. return "TouchCamera";
  54375. };
  54376. TouchCamera.prototype._setupInputs = function () {
  54377. var mouse = this.inputs.attached["mouse"];
  54378. if (mouse) {
  54379. mouse.touchEnabled = false;
  54380. }
  54381. };
  54382. return TouchCamera;
  54383. }(BABYLON.FreeCamera));
  54384. BABYLON.TouchCamera = TouchCamera;
  54385. })(BABYLON || (BABYLON = {}));
  54386. //# sourceMappingURL=babylon.touchCamera.js.map
  54387. var BABYLON;
  54388. (function (BABYLON) {
  54389. var ProceduralTexture = /** @class */ (function (_super) {
  54390. __extends(ProceduralTexture, _super);
  54391. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  54392. if (fallbackTexture === void 0) { fallbackTexture = null; }
  54393. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54394. if (isCube === void 0) { isCube = false; }
  54395. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54396. _this.isCube = isCube;
  54397. _this.isEnabled = true;
  54398. _this._currentRefreshId = -1;
  54399. _this._refreshRate = 1;
  54400. _this._vertexBuffers = {};
  54401. _this._uniforms = new Array();
  54402. _this._samplers = new Array();
  54403. _this._textures = {};
  54404. _this._floats = {};
  54405. _this._floatsArrays = {};
  54406. _this._colors3 = {};
  54407. _this._colors4 = {};
  54408. _this._vectors2 = {};
  54409. _this._vectors3 = {};
  54410. _this._matrices = {};
  54411. _this._fallbackTextureUsed = false;
  54412. scene._proceduralTextures.push(_this);
  54413. _this._engine = scene.getEngine();
  54414. _this.name = name;
  54415. _this.isRenderTarget = true;
  54416. _this._size = size;
  54417. _this._generateMipMaps = generateMipMaps;
  54418. _this.setFragment(fragment);
  54419. _this._fallbackTexture = fallbackTexture;
  54420. if (isCube) {
  54421. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  54422. _this.setFloat("face", 0);
  54423. }
  54424. else {
  54425. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  54426. }
  54427. // VBO
  54428. var vertices = [];
  54429. vertices.push(1, 1);
  54430. vertices.push(-1, 1);
  54431. vertices.push(-1, -1);
  54432. vertices.push(1, -1);
  54433. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54434. _this._createIndexBuffer();
  54435. return _this;
  54436. }
  54437. ProceduralTexture.prototype._createIndexBuffer = function () {
  54438. var engine = this._engine;
  54439. // Indices
  54440. var indices = [];
  54441. indices.push(0);
  54442. indices.push(1);
  54443. indices.push(2);
  54444. indices.push(0);
  54445. indices.push(2);
  54446. indices.push(3);
  54447. this._indexBuffer = engine.createIndexBuffer(indices);
  54448. };
  54449. ProceduralTexture.prototype._rebuild = function () {
  54450. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54451. if (vb) {
  54452. vb._rebuild();
  54453. }
  54454. this._createIndexBuffer();
  54455. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54456. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54457. }
  54458. };
  54459. ProceduralTexture.prototype.reset = function () {
  54460. if (this._effect === undefined) {
  54461. return;
  54462. }
  54463. var engine = this._engine;
  54464. engine._releaseEffect(this._effect);
  54465. };
  54466. ProceduralTexture.prototype.isReady = function () {
  54467. var _this = this;
  54468. var engine = this._engine;
  54469. var shaders;
  54470. if (!this._fragment) {
  54471. return false;
  54472. }
  54473. if (this._fallbackTextureUsed) {
  54474. return true;
  54475. }
  54476. if (this._fragment.fragmentElement !== undefined) {
  54477. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  54478. }
  54479. else {
  54480. shaders = { vertex: "procedural", fragment: this._fragment };
  54481. }
  54482. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  54483. _this.releaseInternalTexture();
  54484. if (_this._fallbackTexture) {
  54485. _this._texture = _this._fallbackTexture._texture;
  54486. if (_this._texture) {
  54487. _this._texture.incrementReferences();
  54488. }
  54489. }
  54490. _this._fallbackTextureUsed = true;
  54491. });
  54492. return this._effect.isReady();
  54493. };
  54494. ProceduralTexture.prototype.resetRefreshCounter = function () {
  54495. this._currentRefreshId = -1;
  54496. };
  54497. ProceduralTexture.prototype.setFragment = function (fragment) {
  54498. this._fragment = fragment;
  54499. };
  54500. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  54501. get: function () {
  54502. return this._refreshRate;
  54503. },
  54504. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54505. set: function (value) {
  54506. this._refreshRate = value;
  54507. this.resetRefreshCounter();
  54508. },
  54509. enumerable: true,
  54510. configurable: true
  54511. });
  54512. ProceduralTexture.prototype._shouldRender = function () {
  54513. if (!this.isEnabled || !this.isReady() || !this._texture) {
  54514. return false;
  54515. }
  54516. if (this._fallbackTextureUsed) {
  54517. return false;
  54518. }
  54519. if (this._currentRefreshId === -1) {
  54520. this._currentRefreshId = 1;
  54521. return true;
  54522. }
  54523. if (this.refreshRate === this._currentRefreshId) {
  54524. this._currentRefreshId = 1;
  54525. return true;
  54526. }
  54527. this._currentRefreshId++;
  54528. return false;
  54529. };
  54530. ProceduralTexture.prototype.getRenderSize = function () {
  54531. return this._size;
  54532. };
  54533. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  54534. if (this._fallbackTextureUsed) {
  54535. return;
  54536. }
  54537. this.releaseInternalTexture();
  54538. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  54539. };
  54540. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  54541. if (this._uniforms.indexOf(uniformName) === -1) {
  54542. this._uniforms.push(uniformName);
  54543. }
  54544. };
  54545. ProceduralTexture.prototype.setTexture = function (name, texture) {
  54546. if (this._samplers.indexOf(name) === -1) {
  54547. this._samplers.push(name);
  54548. }
  54549. this._textures[name] = texture;
  54550. return this;
  54551. };
  54552. ProceduralTexture.prototype.setFloat = function (name, value) {
  54553. this._checkUniform(name);
  54554. this._floats[name] = value;
  54555. return this;
  54556. };
  54557. ProceduralTexture.prototype.setFloats = function (name, value) {
  54558. this._checkUniform(name);
  54559. this._floatsArrays[name] = value;
  54560. return this;
  54561. };
  54562. ProceduralTexture.prototype.setColor3 = function (name, value) {
  54563. this._checkUniform(name);
  54564. this._colors3[name] = value;
  54565. return this;
  54566. };
  54567. ProceduralTexture.prototype.setColor4 = function (name, value) {
  54568. this._checkUniform(name);
  54569. this._colors4[name] = value;
  54570. return this;
  54571. };
  54572. ProceduralTexture.prototype.setVector2 = function (name, value) {
  54573. this._checkUniform(name);
  54574. this._vectors2[name] = value;
  54575. return this;
  54576. };
  54577. ProceduralTexture.prototype.setVector3 = function (name, value) {
  54578. this._checkUniform(name);
  54579. this._vectors3[name] = value;
  54580. return this;
  54581. };
  54582. ProceduralTexture.prototype.setMatrix = function (name, value) {
  54583. this._checkUniform(name);
  54584. this._matrices[name] = value;
  54585. return this;
  54586. };
  54587. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54588. var scene = this.getScene();
  54589. if (!scene) {
  54590. return;
  54591. }
  54592. var engine = this._engine;
  54593. // Render
  54594. engine.enableEffect(this._effect);
  54595. engine.setState(false);
  54596. // Texture
  54597. for (var name in this._textures) {
  54598. this._effect.setTexture(name, this._textures[name]);
  54599. }
  54600. // Float
  54601. for (name in this._floats) {
  54602. this._effect.setFloat(name, this._floats[name]);
  54603. }
  54604. // Floats
  54605. for (name in this._floatsArrays) {
  54606. this._effect.setArray(name, this._floatsArrays[name]);
  54607. }
  54608. // Color3
  54609. for (name in this._colors3) {
  54610. this._effect.setColor3(name, this._colors3[name]);
  54611. }
  54612. // Color4
  54613. for (name in this._colors4) {
  54614. var color = this._colors4[name];
  54615. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54616. }
  54617. // Vector2
  54618. for (name in this._vectors2) {
  54619. this._effect.setVector2(name, this._vectors2[name]);
  54620. }
  54621. // Vector3
  54622. for (name in this._vectors3) {
  54623. this._effect.setVector3(name, this._vectors3[name]);
  54624. }
  54625. // Matrix
  54626. for (name in this._matrices) {
  54627. this._effect.setMatrix(name, this._matrices[name]);
  54628. }
  54629. if (!this._texture) {
  54630. return;
  54631. }
  54632. if (this.isCube) {
  54633. for (var face = 0; face < 6; face++) {
  54634. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  54635. // VBOs
  54636. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54637. this._effect.setFloat("face", face);
  54638. // Clear
  54639. engine.clear(scene.clearColor, true, true, true);
  54640. // Draw order
  54641. engine.draw(true, 0, 6);
  54642. // Mipmaps
  54643. if (face === 5) {
  54644. engine.generateMipMapsForCubemap(this._texture);
  54645. }
  54646. }
  54647. }
  54648. else {
  54649. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  54650. // VBOs
  54651. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54652. // Clear
  54653. engine.clear(scene.clearColor, true, true, true);
  54654. // Draw order
  54655. engine.draw(true, 0, 6);
  54656. }
  54657. // Unbind
  54658. engine.unBindFramebuffer(this._texture, this.isCube);
  54659. if (this.onGenerated) {
  54660. this.onGenerated();
  54661. }
  54662. };
  54663. ProceduralTexture.prototype.clone = function () {
  54664. var textureSize = this.getSize();
  54665. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  54666. // Base texture
  54667. newTexture.hasAlpha = this.hasAlpha;
  54668. newTexture.level = this.level;
  54669. // RenderTarget Texture
  54670. newTexture.coordinatesMode = this.coordinatesMode;
  54671. return newTexture;
  54672. };
  54673. ProceduralTexture.prototype.dispose = function () {
  54674. var scene = this.getScene();
  54675. if (!scene) {
  54676. return;
  54677. }
  54678. var index = scene._proceduralTextures.indexOf(this);
  54679. if (index >= 0) {
  54680. scene._proceduralTextures.splice(index, 1);
  54681. }
  54682. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54683. if (vertexBuffer) {
  54684. vertexBuffer.dispose();
  54685. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54686. }
  54687. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  54688. this._indexBuffer = null;
  54689. }
  54690. _super.prototype.dispose.call(this);
  54691. };
  54692. return ProceduralTexture;
  54693. }(BABYLON.Texture));
  54694. BABYLON.ProceduralTexture = ProceduralTexture;
  54695. })(BABYLON || (BABYLON = {}));
  54696. //# sourceMappingURL=babylon.proceduralTexture.js.map
  54697. var BABYLON;
  54698. (function (BABYLON) {
  54699. var CustomProceduralTexture = /** @class */ (function (_super) {
  54700. __extends(CustomProceduralTexture, _super);
  54701. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  54702. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  54703. _this._animate = true;
  54704. _this._time = 0;
  54705. _this._texturePath = texturePath;
  54706. //Try to load json
  54707. _this.loadJson(texturePath);
  54708. _this.refreshRate = 1;
  54709. return _this;
  54710. }
  54711. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  54712. var _this = this;
  54713. var noConfigFile = function () {
  54714. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  54715. try {
  54716. _this.setFragment(_this._texturePath);
  54717. }
  54718. catch (ex) {
  54719. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  54720. }
  54721. };
  54722. var configFileUrl = jsonUrl + "/config.json";
  54723. var xhr = new XMLHttpRequest();
  54724. xhr.open("GET", configFileUrl, true);
  54725. xhr.addEventListener("load", function () {
  54726. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54727. try {
  54728. _this._config = JSON.parse(xhr.response);
  54729. _this.updateShaderUniforms();
  54730. _this.updateTextures();
  54731. _this.setFragment(_this._texturePath + "/custom");
  54732. _this._animate = _this._config.animate;
  54733. _this.refreshRate = _this._config.refreshrate;
  54734. }
  54735. catch (ex) {
  54736. noConfigFile();
  54737. }
  54738. }
  54739. else {
  54740. noConfigFile();
  54741. }
  54742. }, false);
  54743. xhr.addEventListener("error", function () {
  54744. noConfigFile();
  54745. }, false);
  54746. try {
  54747. xhr.send();
  54748. }
  54749. catch (ex) {
  54750. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  54751. }
  54752. };
  54753. CustomProceduralTexture.prototype.isReady = function () {
  54754. if (!_super.prototype.isReady.call(this)) {
  54755. return false;
  54756. }
  54757. for (var name in this._textures) {
  54758. var texture = this._textures[name];
  54759. if (!texture.isReady()) {
  54760. return false;
  54761. }
  54762. }
  54763. return true;
  54764. };
  54765. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54766. var scene = this.getScene();
  54767. if (this._animate && scene) {
  54768. this._time += scene.getAnimationRatio() * 0.03;
  54769. this.updateShaderUniforms();
  54770. }
  54771. _super.prototype.render.call(this, useCameraPostProcess);
  54772. };
  54773. CustomProceduralTexture.prototype.updateTextures = function () {
  54774. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  54775. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  54776. }
  54777. };
  54778. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  54779. if (this._config) {
  54780. for (var j = 0; j < this._config.uniforms.length; j++) {
  54781. var uniform = this._config.uniforms[j];
  54782. switch (uniform.type) {
  54783. case "float":
  54784. this.setFloat(uniform.name, uniform.value);
  54785. break;
  54786. case "color3":
  54787. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  54788. break;
  54789. case "color4":
  54790. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  54791. break;
  54792. case "vector2":
  54793. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  54794. break;
  54795. case "vector3":
  54796. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  54797. break;
  54798. }
  54799. }
  54800. }
  54801. this.setFloat("time", this._time);
  54802. };
  54803. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  54804. get: function () {
  54805. return this._animate;
  54806. },
  54807. set: function (value) {
  54808. this._animate = value;
  54809. },
  54810. enumerable: true,
  54811. configurable: true
  54812. });
  54813. return CustomProceduralTexture;
  54814. }(BABYLON.ProceduralTexture));
  54815. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  54816. })(BABYLON || (BABYLON = {}));
  54817. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  54818. var BABYLON;
  54819. (function (BABYLON) {
  54820. var FreeCameraGamepadInput = /** @class */ (function () {
  54821. function FreeCameraGamepadInput() {
  54822. this.gamepadAngularSensibility = 200;
  54823. this.gamepadMoveSensibility = 40;
  54824. // private members
  54825. this._cameraTransform = BABYLON.Matrix.Identity();
  54826. this._deltaTransform = BABYLON.Vector3.Zero();
  54827. this._vector3 = BABYLON.Vector3.Zero();
  54828. this._vector2 = BABYLON.Vector2.Zero();
  54829. }
  54830. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54831. var _this = this;
  54832. var manager = this.camera.getScene().gamepadManager;
  54833. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54834. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54835. // prioritize XBOX gamepads.
  54836. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54837. _this.gamepad = gamepad;
  54838. }
  54839. }
  54840. });
  54841. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54842. if (_this.gamepad === gamepad) {
  54843. _this.gamepad = null;
  54844. }
  54845. });
  54846. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54847. };
  54848. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  54849. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54850. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54851. this.gamepad = null;
  54852. };
  54853. FreeCameraGamepadInput.prototype.checkInputs = function () {
  54854. if (this.gamepad && this.gamepad.leftStick) {
  54855. var camera = this.camera;
  54856. var LSValues = this.gamepad.leftStick;
  54857. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  54858. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54859. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  54860. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  54861. var RSValues = this.gamepad.rightStick;
  54862. if (RSValues) {
  54863. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  54864. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  54865. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  54866. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  54867. }
  54868. else {
  54869. RSValues = { x: 0, y: 0 };
  54870. }
  54871. if (!camera.rotationQuaternion) {
  54872. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  54873. }
  54874. else {
  54875. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  54876. }
  54877. var speed = camera._computeLocalCameraSpeed() * 50.0;
  54878. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  54879. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  54880. camera.cameraDirection.addInPlace(this._deltaTransform);
  54881. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  54882. camera.cameraRotation.addInPlace(this._vector2);
  54883. }
  54884. };
  54885. FreeCameraGamepadInput.prototype.getClassName = function () {
  54886. return "FreeCameraGamepadInput";
  54887. };
  54888. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  54889. return "gamepad";
  54890. };
  54891. __decorate([
  54892. BABYLON.serialize()
  54893. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  54894. __decorate([
  54895. BABYLON.serialize()
  54896. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54897. return FreeCameraGamepadInput;
  54898. }());
  54899. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  54900. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  54901. })(BABYLON || (BABYLON = {}));
  54902. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  54903. var BABYLON;
  54904. (function (BABYLON) {
  54905. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  54906. function ArcRotateCameraGamepadInput() {
  54907. this.gamepadRotationSensibility = 80;
  54908. this.gamepadMoveSensibility = 40;
  54909. }
  54910. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54911. var _this = this;
  54912. var manager = this.camera.getScene().gamepadManager;
  54913. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54914. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54915. // prioritize XBOX gamepads.
  54916. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54917. _this.gamepad = gamepad;
  54918. }
  54919. }
  54920. });
  54921. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54922. if (_this.gamepad === gamepad) {
  54923. _this.gamepad = null;
  54924. }
  54925. });
  54926. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54927. };
  54928. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  54929. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54930. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54931. this.gamepad = null;
  54932. };
  54933. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  54934. if (this.gamepad) {
  54935. var camera = this.camera;
  54936. var RSValues = this.gamepad.rightStick;
  54937. if (RSValues) {
  54938. if (RSValues.x != 0) {
  54939. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  54940. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  54941. camera.inertialAlphaOffset += normalizedRX;
  54942. }
  54943. }
  54944. if (RSValues.y != 0) {
  54945. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  54946. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  54947. camera.inertialBetaOffset += normalizedRY;
  54948. }
  54949. }
  54950. }
  54951. var LSValues = this.gamepad.leftStick;
  54952. if (LSValues && LSValues.y != 0) {
  54953. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54954. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  54955. this.camera.inertialRadiusOffset -= normalizedLY;
  54956. }
  54957. }
  54958. }
  54959. };
  54960. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  54961. return "ArcRotateCameraGamepadInput";
  54962. };
  54963. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  54964. return "gamepad";
  54965. };
  54966. __decorate([
  54967. BABYLON.serialize()
  54968. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  54969. __decorate([
  54970. BABYLON.serialize()
  54971. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54972. return ArcRotateCameraGamepadInput;
  54973. }());
  54974. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  54975. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  54976. })(BABYLON || (BABYLON = {}));
  54977. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  54978. var BABYLON;
  54979. (function (BABYLON) {
  54980. var GamepadManager = /** @class */ (function () {
  54981. function GamepadManager() {
  54982. var _this = this;
  54983. this._babylonGamepads = [];
  54984. this._oneGamepadConnected = false;
  54985. this._isMonitoring = false;
  54986. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  54987. if (!BABYLON.Tools.IsWindowObjectExist()) {
  54988. this._gamepadEventSupported = false;
  54989. }
  54990. else {
  54991. this._gamepadEventSupported = 'GamepadEvent' in window;
  54992. this._gamepadSupport = (navigator.getGamepads ||
  54993. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  54994. }
  54995. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  54996. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  54997. for (var i in _this._babylonGamepads) {
  54998. var gamepad = _this._babylonGamepads[i];
  54999. if (gamepad && gamepad._isConnected) {
  55000. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  55001. }
  55002. }
  55003. });
  55004. this._onGamepadConnectedEvent = function (evt) {
  55005. var gamepad = evt.gamepad;
  55006. if (gamepad.index in _this._babylonGamepads) {
  55007. if (_this._babylonGamepads[gamepad.index].isConnected) {
  55008. return;
  55009. }
  55010. }
  55011. var newGamepad;
  55012. if (_this._babylonGamepads[gamepad.index]) {
  55013. newGamepad = _this._babylonGamepads[gamepad.index];
  55014. newGamepad.browserGamepad = gamepad;
  55015. newGamepad._isConnected = true;
  55016. }
  55017. else {
  55018. newGamepad = _this._addNewGamepad(gamepad);
  55019. }
  55020. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55021. _this._startMonitoringGamepads();
  55022. };
  55023. this._onGamepadDisconnectedEvent = function (evt) {
  55024. var gamepad = evt.gamepad;
  55025. // Remove the gamepad from the list of gamepads to monitor.
  55026. for (var i in _this._babylonGamepads) {
  55027. if (_this._babylonGamepads[i].index === gamepad.index) {
  55028. var disconnectedGamepad = _this._babylonGamepads[i];
  55029. disconnectedGamepad._isConnected = false;
  55030. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  55031. break;
  55032. }
  55033. }
  55034. };
  55035. if (this._gamepadSupport) {
  55036. //first add already-connected gamepads
  55037. this._updateGamepadObjects();
  55038. if (this._babylonGamepads.length) {
  55039. this._startMonitoringGamepads();
  55040. }
  55041. // Checking if the gamepad connected event is supported (like in Firefox)
  55042. if (this._gamepadEventSupported) {
  55043. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55044. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  55045. }
  55046. else {
  55047. this._startMonitoringGamepads();
  55048. }
  55049. }
  55050. }
  55051. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  55052. get: function () {
  55053. return this._babylonGamepads;
  55054. },
  55055. enumerable: true,
  55056. configurable: true
  55057. });
  55058. GamepadManager.prototype.getGamepadByType = function (type) {
  55059. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  55060. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  55061. var gamepad = _a[_i];
  55062. if (gamepad && gamepad.type === type) {
  55063. return gamepad;
  55064. }
  55065. }
  55066. return null;
  55067. };
  55068. GamepadManager.prototype.dispose = function () {
  55069. if (this._gamepadEventSupported) {
  55070. if (this._onGamepadConnectedEvent) {
  55071. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  55072. }
  55073. if (this._onGamepadDisconnectedEvent) {
  55074. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  55075. }
  55076. this._onGamepadConnectedEvent = null;
  55077. this._onGamepadDisconnectedEvent = null;
  55078. }
  55079. this._babylonGamepads.forEach(function (gamepad) {
  55080. gamepad.dispose();
  55081. });
  55082. this.onGamepadConnectedObservable.clear();
  55083. this.onGamepadDisconnectedObservable.clear();
  55084. this._oneGamepadConnected = false;
  55085. this._stopMonitoringGamepads();
  55086. this._babylonGamepads = [];
  55087. };
  55088. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  55089. if (!this._oneGamepadConnected) {
  55090. this._oneGamepadConnected = true;
  55091. }
  55092. var newGamepad;
  55093. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  55094. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  55095. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  55096. }
  55097. else if (gamepad.pose) {
  55098. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  55099. }
  55100. else {
  55101. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  55102. }
  55103. this._babylonGamepads[newGamepad.index] = newGamepad;
  55104. return newGamepad;
  55105. };
  55106. GamepadManager.prototype._startMonitoringGamepads = function () {
  55107. if (!this._isMonitoring) {
  55108. this._isMonitoring = true;
  55109. this._checkGamepadsStatus();
  55110. }
  55111. };
  55112. GamepadManager.prototype._stopMonitoringGamepads = function () {
  55113. this._isMonitoring = false;
  55114. };
  55115. GamepadManager.prototype._checkGamepadsStatus = function () {
  55116. var _this = this;
  55117. // Hack to be compatible Chrome
  55118. this._updateGamepadObjects();
  55119. for (var i in this._babylonGamepads) {
  55120. var gamepad = this._babylonGamepads[i];
  55121. if (!gamepad || !gamepad.isConnected) {
  55122. continue;
  55123. }
  55124. gamepad.update();
  55125. }
  55126. if (this._isMonitoring) {
  55127. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  55128. }
  55129. };
  55130. // This function is called only on Chrome, which does not properly support
  55131. // connection/disconnection events and forces you to recopy again the gamepad object
  55132. GamepadManager.prototype._updateGamepadObjects = function () {
  55133. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  55134. for (var i = 0; i < gamepads.length; i++) {
  55135. if (gamepads[i]) {
  55136. if (!this._babylonGamepads[gamepads[i].index]) {
  55137. var newGamepad = this._addNewGamepad(gamepads[i]);
  55138. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55139. }
  55140. else {
  55141. // Forced to copy again this object for Chrome for unknown reason
  55142. this._babylonGamepads[i].browserGamepad = gamepads[i];
  55143. if (!this._babylonGamepads[i].isConnected) {
  55144. this._babylonGamepads[i]._isConnected = true;
  55145. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  55146. }
  55147. }
  55148. }
  55149. }
  55150. };
  55151. return GamepadManager;
  55152. }());
  55153. BABYLON.GamepadManager = GamepadManager;
  55154. })(BABYLON || (BABYLON = {}));
  55155. //# sourceMappingURL=babylon.gamepadManager.js.map
  55156. var BABYLON;
  55157. (function (BABYLON) {
  55158. var StickValues = /** @class */ (function () {
  55159. function StickValues(x, y) {
  55160. this.x = x;
  55161. this.y = y;
  55162. }
  55163. return StickValues;
  55164. }());
  55165. BABYLON.StickValues = StickValues;
  55166. var Gamepad = /** @class */ (function () {
  55167. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  55168. if (leftStickX === void 0) { leftStickX = 0; }
  55169. if (leftStickY === void 0) { leftStickY = 1; }
  55170. if (rightStickX === void 0) { rightStickX = 2; }
  55171. if (rightStickY === void 0) { rightStickY = 3; }
  55172. this.id = id;
  55173. this.index = index;
  55174. this.browserGamepad = browserGamepad;
  55175. this._isConnected = true;
  55176. this.type = Gamepad.GAMEPAD;
  55177. this._leftStickAxisX = leftStickX;
  55178. this._leftStickAxisY = leftStickY;
  55179. this._rightStickAxisX = rightStickX;
  55180. this._rightStickAxisY = rightStickY;
  55181. if (this.browserGamepad.axes.length >= 2) {
  55182. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55183. }
  55184. if (this.browserGamepad.axes.length >= 4) {
  55185. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55186. }
  55187. }
  55188. Object.defineProperty(Gamepad.prototype, "isConnected", {
  55189. get: function () {
  55190. return this._isConnected;
  55191. },
  55192. enumerable: true,
  55193. configurable: true
  55194. });
  55195. Gamepad.prototype.onleftstickchanged = function (callback) {
  55196. this._onleftstickchanged = callback;
  55197. };
  55198. Gamepad.prototype.onrightstickchanged = function (callback) {
  55199. this._onrightstickchanged = callback;
  55200. };
  55201. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55202. get: function () {
  55203. return this._leftStick;
  55204. },
  55205. set: function (newValues) {
  55206. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55207. this._onleftstickchanged(newValues);
  55208. }
  55209. this._leftStick = newValues;
  55210. },
  55211. enumerable: true,
  55212. configurable: true
  55213. });
  55214. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55215. get: function () {
  55216. return this._rightStick;
  55217. },
  55218. set: function (newValues) {
  55219. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55220. this._onrightstickchanged(newValues);
  55221. }
  55222. this._rightStick = newValues;
  55223. },
  55224. enumerable: true,
  55225. configurable: true
  55226. });
  55227. Gamepad.prototype.update = function () {
  55228. if (this._leftStick) {
  55229. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55230. }
  55231. if (this._rightStick) {
  55232. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55233. }
  55234. };
  55235. Gamepad.prototype.dispose = function () {
  55236. };
  55237. Gamepad.GAMEPAD = 0;
  55238. Gamepad.GENERIC = 1;
  55239. Gamepad.XBOX = 2;
  55240. Gamepad.POSE_ENABLED = 3;
  55241. return Gamepad;
  55242. }());
  55243. BABYLON.Gamepad = Gamepad;
  55244. var GenericPad = /** @class */ (function (_super) {
  55245. __extends(GenericPad, _super);
  55246. function GenericPad(id, index, browserGamepad) {
  55247. var _this = _super.call(this, id, index, browserGamepad) || this;
  55248. _this.onButtonDownObservable = new BABYLON.Observable();
  55249. _this.onButtonUpObservable = new BABYLON.Observable();
  55250. _this.type = Gamepad.GENERIC;
  55251. _this._buttons = new Array(browserGamepad.buttons.length);
  55252. return _this;
  55253. }
  55254. GenericPad.prototype.onbuttondown = function (callback) {
  55255. this._onbuttondown = callback;
  55256. };
  55257. GenericPad.prototype.onbuttonup = function (callback) {
  55258. this._onbuttonup = callback;
  55259. };
  55260. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55261. if (newValue !== currentValue) {
  55262. if (newValue === 1) {
  55263. if (this._onbuttondown) {
  55264. this._onbuttondown(buttonIndex);
  55265. }
  55266. this.onButtonDownObservable.notifyObservers(buttonIndex);
  55267. }
  55268. if (newValue === 0) {
  55269. if (this._onbuttonup) {
  55270. this._onbuttonup(buttonIndex);
  55271. }
  55272. this.onButtonUpObservable.notifyObservers(buttonIndex);
  55273. }
  55274. }
  55275. return newValue;
  55276. };
  55277. GenericPad.prototype.update = function () {
  55278. _super.prototype.update.call(this);
  55279. for (var index = 0; index < this._buttons.length; index++) {
  55280. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  55281. }
  55282. };
  55283. return GenericPad;
  55284. }(Gamepad));
  55285. BABYLON.GenericPad = GenericPad;
  55286. })(BABYLON || (BABYLON = {}));
  55287. //# sourceMappingURL=babylon.gamepad.js.map
  55288. var BABYLON;
  55289. (function (BABYLON) {
  55290. var Xbox360Button;
  55291. (function (Xbox360Button) {
  55292. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55293. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55294. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55295. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55296. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55297. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55298. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55299. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55300. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55301. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55302. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55303. var Xbox360Dpad;
  55304. (function (Xbox360Dpad) {
  55305. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55306. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55307. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55308. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55309. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55310. var Xbox360Pad = /** @class */ (function (_super) {
  55311. __extends(Xbox360Pad, _super);
  55312. function Xbox360Pad(id, index, gamepad, xboxOne) {
  55313. if (xboxOne === void 0) { xboxOne = false; }
  55314. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  55315. _this._leftTrigger = 0;
  55316. _this._rightTrigger = 0;
  55317. _this.onButtonDownObservable = new BABYLON.Observable();
  55318. _this.onButtonUpObservable = new BABYLON.Observable();
  55319. _this.onPadDownObservable = new BABYLON.Observable();
  55320. _this.onPadUpObservable = new BABYLON.Observable();
  55321. _this._buttonA = 0;
  55322. _this._buttonB = 0;
  55323. _this._buttonX = 0;
  55324. _this._buttonY = 0;
  55325. _this._buttonBack = 0;
  55326. _this._buttonStart = 0;
  55327. _this._buttonLB = 0;
  55328. _this._buttonRB = 0;
  55329. _this._buttonLeftStick = 0;
  55330. _this._buttonRightStick = 0;
  55331. _this._dPadUp = 0;
  55332. _this._dPadDown = 0;
  55333. _this._dPadLeft = 0;
  55334. _this._dPadRight = 0;
  55335. _this._isXboxOnePad = false;
  55336. _this.type = BABYLON.Gamepad.XBOX;
  55337. _this._isXboxOnePad = xboxOne;
  55338. return _this;
  55339. }
  55340. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55341. this._onlefttriggerchanged = callback;
  55342. };
  55343. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55344. this._onrighttriggerchanged = callback;
  55345. };
  55346. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55347. get: function () {
  55348. return this._leftTrigger;
  55349. },
  55350. set: function (newValue) {
  55351. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55352. this._onlefttriggerchanged(newValue);
  55353. }
  55354. this._leftTrigger = newValue;
  55355. },
  55356. enumerable: true,
  55357. configurable: true
  55358. });
  55359. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55360. get: function () {
  55361. return this._rightTrigger;
  55362. },
  55363. set: function (newValue) {
  55364. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55365. this._onrighttriggerchanged(newValue);
  55366. }
  55367. this._rightTrigger = newValue;
  55368. },
  55369. enumerable: true,
  55370. configurable: true
  55371. });
  55372. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55373. this._onbuttondown = callback;
  55374. };
  55375. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55376. this._onbuttonup = callback;
  55377. };
  55378. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55379. this._ondpaddown = callback;
  55380. };
  55381. Xbox360Pad.prototype.ondpadup = function (callback) {
  55382. this._ondpadup = callback;
  55383. };
  55384. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55385. if (newValue !== currentValue) {
  55386. if (newValue === 1) {
  55387. if (this._onbuttondown) {
  55388. this._onbuttondown(buttonType);
  55389. }
  55390. this.onButtonDownObservable.notifyObservers(buttonType);
  55391. }
  55392. if (newValue === 0) {
  55393. if (this._onbuttonup) {
  55394. this._onbuttonup(buttonType);
  55395. }
  55396. this.onButtonUpObservable.notifyObservers(buttonType);
  55397. }
  55398. }
  55399. return newValue;
  55400. };
  55401. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55402. if (newValue !== currentValue) {
  55403. if (newValue === 1) {
  55404. if (this._ondpaddown) {
  55405. this._ondpaddown(buttonType);
  55406. }
  55407. this.onPadDownObservable.notifyObservers(buttonType);
  55408. }
  55409. if (newValue === 0) {
  55410. if (this._ondpadup) {
  55411. this._ondpadup(buttonType);
  55412. }
  55413. this.onPadUpObservable.notifyObservers(buttonType);
  55414. }
  55415. }
  55416. return newValue;
  55417. };
  55418. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55419. get: function () {
  55420. return this._buttonA;
  55421. },
  55422. set: function (value) {
  55423. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55424. },
  55425. enumerable: true,
  55426. configurable: true
  55427. });
  55428. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55429. get: function () {
  55430. return this._buttonB;
  55431. },
  55432. set: function (value) {
  55433. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55434. },
  55435. enumerable: true,
  55436. configurable: true
  55437. });
  55438. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55439. get: function () {
  55440. return this._buttonX;
  55441. },
  55442. set: function (value) {
  55443. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55444. },
  55445. enumerable: true,
  55446. configurable: true
  55447. });
  55448. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55449. get: function () {
  55450. return this._buttonY;
  55451. },
  55452. set: function (value) {
  55453. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55454. },
  55455. enumerable: true,
  55456. configurable: true
  55457. });
  55458. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55459. get: function () {
  55460. return this._buttonStart;
  55461. },
  55462. set: function (value) {
  55463. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55464. },
  55465. enumerable: true,
  55466. configurable: true
  55467. });
  55468. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55469. get: function () {
  55470. return this._buttonBack;
  55471. },
  55472. set: function (value) {
  55473. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55474. },
  55475. enumerable: true,
  55476. configurable: true
  55477. });
  55478. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55479. get: function () {
  55480. return this._buttonLB;
  55481. },
  55482. set: function (value) {
  55483. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55484. },
  55485. enumerable: true,
  55486. configurable: true
  55487. });
  55488. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55489. get: function () {
  55490. return this._buttonRB;
  55491. },
  55492. set: function (value) {
  55493. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55494. },
  55495. enumerable: true,
  55496. configurable: true
  55497. });
  55498. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55499. get: function () {
  55500. return this._buttonLeftStick;
  55501. },
  55502. set: function (value) {
  55503. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55504. },
  55505. enumerable: true,
  55506. configurable: true
  55507. });
  55508. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55509. get: function () {
  55510. return this._buttonRightStick;
  55511. },
  55512. set: function (value) {
  55513. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55514. },
  55515. enumerable: true,
  55516. configurable: true
  55517. });
  55518. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55519. get: function () {
  55520. return this._dPadUp;
  55521. },
  55522. set: function (value) {
  55523. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55524. },
  55525. enumerable: true,
  55526. configurable: true
  55527. });
  55528. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55529. get: function () {
  55530. return this._dPadDown;
  55531. },
  55532. set: function (value) {
  55533. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55534. },
  55535. enumerable: true,
  55536. configurable: true
  55537. });
  55538. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55539. get: function () {
  55540. return this._dPadLeft;
  55541. },
  55542. set: function (value) {
  55543. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55544. },
  55545. enumerable: true,
  55546. configurable: true
  55547. });
  55548. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55549. get: function () {
  55550. return this._dPadRight;
  55551. },
  55552. set: function (value) {
  55553. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55554. },
  55555. enumerable: true,
  55556. configurable: true
  55557. });
  55558. Xbox360Pad.prototype.update = function () {
  55559. _super.prototype.update.call(this);
  55560. if (this._isXboxOnePad) {
  55561. this.buttonA = this.browserGamepad.buttons[0].value;
  55562. this.buttonB = this.browserGamepad.buttons[1].value;
  55563. this.buttonX = this.browserGamepad.buttons[2].value;
  55564. this.buttonY = this.browserGamepad.buttons[3].value;
  55565. this.buttonLB = this.browserGamepad.buttons[4].value;
  55566. this.buttonRB = this.browserGamepad.buttons[5].value;
  55567. this.leftTrigger = this.browserGamepad.axes[2];
  55568. this.rightTrigger = this.browserGamepad.axes[5];
  55569. this.buttonBack = this.browserGamepad.buttons[9].value;
  55570. this.buttonStart = this.browserGamepad.buttons[8].value;
  55571. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  55572. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  55573. this.dPadUp = this.browserGamepad.buttons[11].value;
  55574. this.dPadDown = this.browserGamepad.buttons[12].value;
  55575. this.dPadLeft = this.browserGamepad.buttons[13].value;
  55576. this.dPadRight = this.browserGamepad.buttons[14].value;
  55577. }
  55578. else {
  55579. this.buttonA = this.browserGamepad.buttons[0].value;
  55580. this.buttonB = this.browserGamepad.buttons[1].value;
  55581. this.buttonX = this.browserGamepad.buttons[2].value;
  55582. this.buttonY = this.browserGamepad.buttons[3].value;
  55583. this.buttonLB = this.browserGamepad.buttons[4].value;
  55584. this.buttonRB = this.browserGamepad.buttons[5].value;
  55585. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55586. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55587. this.buttonBack = this.browserGamepad.buttons[8].value;
  55588. this.buttonStart = this.browserGamepad.buttons[9].value;
  55589. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55590. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55591. this.dPadUp = this.browserGamepad.buttons[12].value;
  55592. this.dPadDown = this.browserGamepad.buttons[13].value;
  55593. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55594. this.dPadRight = this.browserGamepad.buttons[15].value;
  55595. }
  55596. };
  55597. return Xbox360Pad;
  55598. }(BABYLON.Gamepad));
  55599. BABYLON.Xbox360Pad = Xbox360Pad;
  55600. })(BABYLON || (BABYLON = {}));
  55601. //# sourceMappingURL=babylon.xboxGamepad.js.map
  55602. var BABYLON;
  55603. (function (BABYLON) {
  55604. var PoseEnabledControllerType;
  55605. (function (PoseEnabledControllerType) {
  55606. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  55607. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  55608. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  55609. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  55610. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  55611. var PoseEnabledControllerHelper = /** @class */ (function () {
  55612. function PoseEnabledControllerHelper() {
  55613. }
  55614. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  55615. // Oculus Touch
  55616. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  55617. return new BABYLON.OculusTouchController(vrGamepad);
  55618. }
  55619. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  55620. return new BABYLON.WindowsMotionController(vrGamepad);
  55621. }
  55622. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  55623. return new BABYLON.ViveController(vrGamepad);
  55624. }
  55625. else {
  55626. return new BABYLON.GenericController(vrGamepad);
  55627. }
  55628. };
  55629. return PoseEnabledControllerHelper;
  55630. }());
  55631. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  55632. var PoseEnabledController = /** @class */ (function (_super) {
  55633. __extends(PoseEnabledController, _super);
  55634. function PoseEnabledController(browserGamepad) {
  55635. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  55636. _this.deviceScaleFactor = 1;
  55637. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  55638. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  55639. _this.controllerType = PoseEnabledControllerType.GENERIC;
  55640. _this.position = BABYLON.Vector3.Zero();
  55641. _this.rotationQuaternion = new BABYLON.Quaternion();
  55642. _this.devicePosition = BABYLON.Vector3.Zero();
  55643. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  55644. _this._calculatedPosition = BABYLON.Vector3.Zero();
  55645. _this._calculatedRotation = new BABYLON.Quaternion();
  55646. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  55647. return _this;
  55648. }
  55649. PoseEnabledController.prototype.update = function () {
  55650. _super.prototype.update.call(this);
  55651. var pose = this.browserGamepad.pose;
  55652. this.updateFromDevice(pose);
  55653. if (this._mesh) {
  55654. this._mesh.position.copyFrom(this._calculatedPosition);
  55655. if (this._mesh.rotationQuaternion) {
  55656. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  55657. }
  55658. }
  55659. };
  55660. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  55661. if (poseData) {
  55662. this.rawPose = poseData;
  55663. if (poseData.position) {
  55664. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  55665. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  55666. this.devicePosition.z *= -1;
  55667. }
  55668. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  55669. this._calculatedPosition.addInPlace(this.position);
  55670. }
  55671. var pose = this.rawPose;
  55672. if (poseData.orientation && pose.orientation) {
  55673. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  55674. if (this._mesh) {
  55675. if (this._mesh.getScene().useRightHandedSystem) {
  55676. this.deviceRotationQuaternion.z *= -1;
  55677. this.deviceRotationQuaternion.w *= -1;
  55678. }
  55679. else {
  55680. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  55681. }
  55682. }
  55683. // if the camera is set, rotate to the camera's rotation
  55684. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  55685. }
  55686. }
  55687. };
  55688. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  55689. if (this._mesh) {
  55690. this._mesh.parent = null;
  55691. }
  55692. this._mesh = mesh;
  55693. if (this._poseControlledCamera) {
  55694. this._mesh.parent = this._poseControlledCamera;
  55695. }
  55696. if (!this._mesh.rotationQuaternion) {
  55697. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  55698. }
  55699. };
  55700. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  55701. this._poseControlledCamera = camera;
  55702. if (this._mesh) {
  55703. this._mesh.parent = this._poseControlledCamera;
  55704. }
  55705. };
  55706. PoseEnabledController.prototype.dispose = function () {
  55707. if (this._mesh) {
  55708. this._mesh.dispose();
  55709. }
  55710. this._mesh = null;
  55711. _super.prototype.dispose.call(this);
  55712. };
  55713. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  55714. get: function () {
  55715. return this._mesh;
  55716. },
  55717. enumerable: true,
  55718. configurable: true
  55719. });
  55720. PoseEnabledController.prototype.getForwardRay = function (length) {
  55721. if (length === void 0) { length = 100; }
  55722. if (!this.mesh) {
  55723. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  55724. }
  55725. var m = this.mesh.getWorldMatrix();
  55726. var origin = m.getTranslation();
  55727. var forward = new BABYLON.Vector3(0, 0, -1);
  55728. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55729. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55730. return new BABYLON.Ray(origin, direction, length);
  55731. };
  55732. return PoseEnabledController;
  55733. }(BABYLON.Gamepad));
  55734. BABYLON.PoseEnabledController = PoseEnabledController;
  55735. })(BABYLON || (BABYLON = {}));
  55736. //# sourceMappingURL=babylon.poseEnabledController.js.map
  55737. var BABYLON;
  55738. (function (BABYLON) {
  55739. var WebVRController = /** @class */ (function (_super) {
  55740. __extends(WebVRController, _super);
  55741. function WebVRController(vrGamepad) {
  55742. var _this = _super.call(this, vrGamepad) || this;
  55743. // Observables
  55744. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  55745. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  55746. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  55747. _this.onPadStateChangedObservable = new BABYLON.Observable();
  55748. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  55749. _this.pad = { x: 0, y: 0 };
  55750. // avoid GC, store state in a tmp object
  55751. _this._changes = {
  55752. pressChanged: false,
  55753. touchChanged: false,
  55754. valueChanged: false,
  55755. changed: false
  55756. };
  55757. _this._buttons = new Array(vrGamepad.buttons.length);
  55758. _this.hand = vrGamepad.hand;
  55759. return _this;
  55760. }
  55761. WebVRController.prototype.onButtonStateChange = function (callback) {
  55762. this._onButtonStateChange = callback;
  55763. };
  55764. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  55765. get: function () {
  55766. return this._defaultModel;
  55767. },
  55768. enumerable: true,
  55769. configurable: true
  55770. });
  55771. WebVRController.prototype.update = function () {
  55772. _super.prototype.update.call(this);
  55773. for (var index = 0; index < this._buttons.length; index++) {
  55774. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  55775. }
  55776. ;
  55777. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  55778. this.pad.x = this.leftStick.x;
  55779. this.pad.y = this.leftStick.y;
  55780. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  55781. }
  55782. };
  55783. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  55784. if (!newState) {
  55785. newState = {
  55786. pressed: false,
  55787. touched: false,
  55788. value: 0
  55789. };
  55790. }
  55791. if (!currentState) {
  55792. this._buttons[buttonIndex] = {
  55793. pressed: newState.pressed,
  55794. touched: newState.touched,
  55795. value: newState.value
  55796. };
  55797. return;
  55798. }
  55799. this._checkChanges(newState, currentState);
  55800. if (this._changes.changed) {
  55801. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  55802. this.handleButtonChange(buttonIndex, newState, this._changes);
  55803. }
  55804. this._buttons[buttonIndex].pressed = newState.pressed;
  55805. this._buttons[buttonIndex].touched = newState.touched;
  55806. // oculus triggers are never 0, thou not touched.
  55807. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  55808. };
  55809. WebVRController.prototype._checkChanges = function (newState, currentState) {
  55810. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  55811. this._changes.touchChanged = newState.touched !== currentState.touched;
  55812. this._changes.valueChanged = newState.value !== currentState.value;
  55813. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  55814. return this._changes;
  55815. };
  55816. WebVRController.prototype.dispose = function () {
  55817. _super.prototype.dispose.call(this);
  55818. this.onTriggerStateChangedObservable.clear();
  55819. this.onMainButtonStateChangedObservable.clear();
  55820. this.onSecondaryButtonStateChangedObservable.clear();
  55821. this.onPadStateChangedObservable.clear();
  55822. this.onPadValuesChangedObservable.clear();
  55823. };
  55824. return WebVRController;
  55825. }(BABYLON.PoseEnabledController));
  55826. BABYLON.WebVRController = WebVRController;
  55827. })(BABYLON || (BABYLON = {}));
  55828. //# sourceMappingURL=babylon.webVRController.js.map
  55829. var BABYLON;
  55830. (function (BABYLON) {
  55831. var OculusTouchController = /** @class */ (function (_super) {
  55832. __extends(OculusTouchController, _super);
  55833. function OculusTouchController(vrGamepad) {
  55834. var _this = _super.call(this, vrGamepad) || this;
  55835. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  55836. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  55837. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  55838. return _this;
  55839. }
  55840. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55841. var _this = this;
  55842. var meshName;
  55843. // Hand
  55844. if (this.hand === 'left') {
  55845. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  55846. }
  55847. else {
  55848. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  55849. }
  55850. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  55851. /*
  55852. Parent Mesh name: oculus_touch_left
  55853. - body
  55854. - trigger
  55855. - thumbstick
  55856. - grip
  55857. - button_y
  55858. - button_x
  55859. - button_enter
  55860. */
  55861. _this._defaultModel = newMeshes[1];
  55862. _this.attachToMesh(_this._defaultModel);
  55863. if (meshLoaded) {
  55864. meshLoaded(_this._defaultModel);
  55865. }
  55866. });
  55867. };
  55868. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  55869. // helper getters for left and right hand.
  55870. get: function () {
  55871. if (this.hand === 'right') {
  55872. return this.onMainButtonStateChangedObservable;
  55873. }
  55874. else {
  55875. throw new Error('No A button on left hand');
  55876. }
  55877. },
  55878. enumerable: true,
  55879. configurable: true
  55880. });
  55881. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  55882. get: function () {
  55883. if (this.hand === 'right') {
  55884. return this.onSecondaryButtonStateChangedObservable;
  55885. }
  55886. else {
  55887. throw new Error('No B button on left hand');
  55888. }
  55889. },
  55890. enumerable: true,
  55891. configurable: true
  55892. });
  55893. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  55894. get: function () {
  55895. if (this.hand === 'left') {
  55896. return this.onMainButtonStateChangedObservable;
  55897. }
  55898. else {
  55899. throw new Error('No X button on right hand');
  55900. }
  55901. },
  55902. enumerable: true,
  55903. configurable: true
  55904. });
  55905. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  55906. get: function () {
  55907. if (this.hand === 'left') {
  55908. return this.onSecondaryButtonStateChangedObservable;
  55909. }
  55910. else {
  55911. throw new Error('No Y button on right hand');
  55912. }
  55913. },
  55914. enumerable: true,
  55915. configurable: true
  55916. });
  55917. /*
  55918. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  55919. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  55920. 2) secondary trigger (same)
  55921. 3) A (right) X (left), touch, pressed = value
  55922. 4) B / Y
  55923. 5) thumb rest
  55924. */
  55925. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55926. var notifyObject = state; //{ state: state, changes: changes };
  55927. var triggerDirection = this.hand === 'right' ? -1 : 1;
  55928. switch (buttonIdx) {
  55929. case 0:
  55930. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55931. return;
  55932. case 1:// index trigger
  55933. if (this._defaultModel) {
  55934. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  55935. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  55936. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  55937. }
  55938. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55939. return;
  55940. case 2:// secondary trigger
  55941. if (this._defaultModel) {
  55942. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  55943. }
  55944. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  55945. return;
  55946. case 3:
  55947. if (this._defaultModel) {
  55948. if (notifyObject.pressed) {
  55949. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  55950. }
  55951. else {
  55952. (this._defaultModel.getChildren()[1]).position.y = 0;
  55953. }
  55954. }
  55955. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55956. return;
  55957. case 4:
  55958. if (this._defaultModel) {
  55959. if (notifyObject.pressed) {
  55960. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55961. }
  55962. else {
  55963. (this._defaultModel.getChildren()[2]).position.y = 0;
  55964. }
  55965. }
  55966. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55967. return;
  55968. case 5:
  55969. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  55970. return;
  55971. }
  55972. };
  55973. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  55974. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  55975. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  55976. return OculusTouchController;
  55977. }(BABYLON.WebVRController));
  55978. BABYLON.OculusTouchController = OculusTouchController;
  55979. })(BABYLON || (BABYLON = {}));
  55980. //# sourceMappingURL=babylon.oculusTouchController.js.map
  55981. var BABYLON;
  55982. (function (BABYLON) {
  55983. var ViveController = /** @class */ (function (_super) {
  55984. __extends(ViveController, _super);
  55985. function ViveController(vrGamepad) {
  55986. var _this = _super.call(this, vrGamepad) || this;
  55987. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  55988. return _this;
  55989. }
  55990. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55991. var _this = this;
  55992. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  55993. /*
  55994. Parent Mesh name: ViveWand
  55995. - body
  55996. - r_gripper
  55997. - l_gripper
  55998. - menu_button
  55999. - system_button
  56000. - trackpad
  56001. - trigger
  56002. - LED
  56003. */
  56004. _this._defaultModel = newMeshes[1];
  56005. _this.attachToMesh(_this._defaultModel);
  56006. if (meshLoaded) {
  56007. meshLoaded(_this._defaultModel);
  56008. }
  56009. });
  56010. };
  56011. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  56012. get: function () {
  56013. return this.onMainButtonStateChangedObservable;
  56014. },
  56015. enumerable: true,
  56016. configurable: true
  56017. });
  56018. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  56019. get: function () {
  56020. return this.onMainButtonStateChangedObservable;
  56021. },
  56022. enumerable: true,
  56023. configurable: true
  56024. });
  56025. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  56026. get: function () {
  56027. return this.onSecondaryButtonStateChangedObservable;
  56028. },
  56029. enumerable: true,
  56030. configurable: true
  56031. });
  56032. /**
  56033. * Vive mapping:
  56034. * 0: touchpad
  56035. * 1: trigger
  56036. * 2: left AND right buttons
  56037. * 3: menu button
  56038. */
  56039. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56040. var notifyObject = state; //{ state: state, changes: changes };
  56041. switch (buttonIdx) {
  56042. case 0:
  56043. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56044. return;
  56045. case 1:// index trigger
  56046. if (this._defaultModel) {
  56047. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  56048. }
  56049. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56050. return;
  56051. case 2:// left AND right button
  56052. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56053. return;
  56054. case 3:
  56055. if (this._defaultModel) {
  56056. if (notifyObject.pressed) {
  56057. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56058. }
  56059. else {
  56060. (this._defaultModel.getChildren()[2]).position.y = 0;
  56061. }
  56062. }
  56063. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56064. return;
  56065. }
  56066. };
  56067. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  56068. ViveController.MODEL_FILENAME = 'wand.babylon';
  56069. return ViveController;
  56070. }(BABYLON.WebVRController));
  56071. BABYLON.ViveController = ViveController;
  56072. })(BABYLON || (BABYLON = {}));
  56073. //# sourceMappingURL=babylon.viveController.js.map
  56074. var BABYLON;
  56075. (function (BABYLON) {
  56076. var GenericController = /** @class */ (function (_super) {
  56077. __extends(GenericController, _super);
  56078. function GenericController(vrGamepad) {
  56079. return _super.call(this, vrGamepad) || this;
  56080. }
  56081. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56082. var _this = this;
  56083. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  56084. _this._defaultModel = newMeshes[1];
  56085. _this.attachToMesh(_this._defaultModel);
  56086. if (meshLoaded) {
  56087. meshLoaded(_this._defaultModel);
  56088. }
  56089. });
  56090. };
  56091. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56092. console.log("Button id: " + buttonIdx + "state: ");
  56093. console.dir(state);
  56094. };
  56095. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  56096. GenericController.MODEL_FILENAME = 'generic.babylon';
  56097. return GenericController;
  56098. }(BABYLON.WebVRController));
  56099. BABYLON.GenericController = GenericController;
  56100. })(BABYLON || (BABYLON = {}));
  56101. //# sourceMappingURL=babylon.genericController.js.map
  56102. var BABYLON;
  56103. (function (BABYLON) {
  56104. var LoadedMeshInfo = /** @class */ (function () {
  56105. function LoadedMeshInfo() {
  56106. this.buttonMeshes = {};
  56107. this.axisMeshes = {};
  56108. }
  56109. return LoadedMeshInfo;
  56110. }());
  56111. var WindowsMotionController = /** @class */ (function (_super) {
  56112. __extends(WindowsMotionController, _super);
  56113. function WindowsMotionController(vrGamepad) {
  56114. var _this = _super.call(this, vrGamepad) || this;
  56115. _this._mapping = {
  56116. // Semantic button names
  56117. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  56118. // A mapping of the button name to glTF model node name
  56119. // that should be transformed by button value.
  56120. buttonMeshNames: {
  56121. 'trigger': 'SELECT',
  56122. 'menu': 'MENU',
  56123. 'grip': 'GRASP',
  56124. 'thumbstick': 'THUMBSTICK_PRESS',
  56125. 'trackpad': 'TOUCHPAD_PRESS'
  56126. },
  56127. // This mapping is used to translate from the Motion Controller to Babylon semantics
  56128. buttonObservableNames: {
  56129. 'trigger': 'onTriggerStateChangedObservable',
  56130. 'menu': 'onSecondaryButtonStateChangedObservable',
  56131. 'grip': 'onMainButtonStateChangedObservable',
  56132. 'thumbstick': 'onPadStateChangedObservable',
  56133. 'trackpad': 'onTrackpadChangedObservable'
  56134. },
  56135. // A mapping of the axis name to glTF model node name
  56136. // that should be transformed by axis value.
  56137. // This array mirrors the browserGamepad.axes array, such that
  56138. // the mesh corresponding to axis 0 is in this array index 0.
  56139. axisMeshNames: [
  56140. 'THUMBSTICK_X',
  56141. 'THUMBSTICK_Y',
  56142. 'TOUCHPAD_TOUCH_X',
  56143. 'TOUCHPAD_TOUCH_Y'
  56144. ],
  56145. pointingPoseMeshName: 'POINTING_POSE'
  56146. };
  56147. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  56148. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  56149. _this._loadedMeshInfo = null;
  56150. return _this;
  56151. }
  56152. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  56153. get: function () {
  56154. return this.onTriggerStateChangedObservable;
  56155. },
  56156. enumerable: true,
  56157. configurable: true
  56158. });
  56159. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  56160. get: function () {
  56161. return this.onSecondaryButtonStateChangedObservable;
  56162. },
  56163. enumerable: true,
  56164. configurable: true
  56165. });
  56166. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  56167. get: function () {
  56168. return this.onMainButtonStateChangedObservable;
  56169. },
  56170. enumerable: true,
  56171. configurable: true
  56172. });
  56173. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  56174. get: function () {
  56175. return this.onPadStateChangedObservable;
  56176. },
  56177. enumerable: true,
  56178. configurable: true
  56179. });
  56180. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  56181. get: function () {
  56182. return this.onTrackpadChangedObservable;
  56183. },
  56184. enumerable: true,
  56185. configurable: true
  56186. });
  56187. /**
  56188. * Called once per frame by the engine.
  56189. */
  56190. WindowsMotionController.prototype.update = function () {
  56191. _super.prototype.update.call(this);
  56192. // Only need to animate axes if there is a loaded mesh
  56193. if (this._loadedMeshInfo) {
  56194. if (this.browserGamepad.axes) {
  56195. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  56196. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  56197. }
  56198. }
  56199. }
  56200. };
  56201. /**
  56202. * Called once for each button that changed state since the last frame
  56203. * @param buttonIdx Which button index changed
  56204. * @param state New state of the button
  56205. * @param changes Which properties on the state changed since last frame
  56206. */
  56207. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56208. var buttonName = this._mapping.buttons[buttonIdx];
  56209. if (!buttonName) {
  56210. return;
  56211. }
  56212. // Only emit events for buttons that we know how to map from index to name
  56213. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  56214. if (observable) {
  56215. observable.notifyObservers(state);
  56216. }
  56217. this.lerpButtonTransform(buttonName, state.value);
  56218. };
  56219. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  56220. // If there is no loaded mesh, there is nothing to transform.
  56221. if (!this._loadedMeshInfo) {
  56222. return;
  56223. }
  56224. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  56225. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56226. return;
  56227. }
  56228. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  56229. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  56230. };
  56231. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  56232. if (!this._loadedMeshInfo) {
  56233. return;
  56234. }
  56235. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  56236. if (!meshInfo) {
  56237. return;
  56238. }
  56239. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56240. return;
  56241. }
  56242. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  56243. var lerpValue = axisValue * 0.5 + 0.5;
  56244. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  56245. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  56246. };
  56247. /**
  56248. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  56249. * @param scene scene in which to add meshes
  56250. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  56251. */
  56252. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  56253. var _this = this;
  56254. if (forceDefault === void 0) { forceDefault = false; }
  56255. var path;
  56256. var filename;
  56257. // Checking if GLB loader is present
  56258. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  56259. // Determine the device specific folder based on the ID suffix
  56260. var device = 'default';
  56261. if (this.id && !forceDefault) {
  56262. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  56263. device = ((match && match[0]) || device);
  56264. }
  56265. // Hand
  56266. if (this.hand === 'left') {
  56267. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  56268. }
  56269. else {
  56270. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  56271. }
  56272. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  56273. }
  56274. else {
  56275. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  56276. path = BABYLON.GenericController.MODEL_BASE_URL;
  56277. filename = BABYLON.GenericController.MODEL_FILENAME;
  56278. }
  56279. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  56280. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  56281. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  56282. if (!_this._loadedMeshInfo) {
  56283. return;
  56284. }
  56285. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  56286. _this.attachToMesh(_this._defaultModel);
  56287. if (meshLoaded) {
  56288. meshLoaded(_this._defaultModel);
  56289. }
  56290. }, null, function (scene, message) {
  56291. BABYLON.Tools.Log(message);
  56292. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  56293. if (!forceDefault) {
  56294. _this.initControllerMesh(scene, meshLoaded, true);
  56295. }
  56296. });
  56297. };
  56298. /**
  56299. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  56300. * can be transformed by button presses and axes values, based on this._mapping.
  56301. *
  56302. * @param scene scene in which the meshes exist
  56303. * @param meshes list of meshes that make up the controller model to process
  56304. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  56305. */
  56306. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  56307. var loadedMeshInfo = null;
  56308. // Create a new mesh to contain the glTF hierarchy
  56309. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  56310. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  56311. var childMesh = null;
  56312. for (var i = 0; i < meshes.length; i++) {
  56313. var mesh = meshes[i];
  56314. if (!mesh.parent) {
  56315. // Exclude controller meshes from picking results
  56316. mesh.isPickable = false;
  56317. // Handle root node, attach to the new parentMesh
  56318. childMesh = mesh;
  56319. break;
  56320. }
  56321. }
  56322. if (childMesh) {
  56323. childMesh.setParent(parentMesh);
  56324. // Create our mesh info. Note that this method will always return non-null.
  56325. loadedMeshInfo = this.createMeshInfo(parentMesh);
  56326. }
  56327. else {
  56328. BABYLON.Tools.Warn('Could not find root node in model file.');
  56329. }
  56330. return loadedMeshInfo;
  56331. };
  56332. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  56333. var loadedMeshInfo = new LoadedMeshInfo();
  56334. var i;
  56335. loadedMeshInfo.rootNode = rootNode;
  56336. // Reset the caches
  56337. loadedMeshInfo.buttonMeshes = {};
  56338. loadedMeshInfo.axisMeshes = {};
  56339. // Button Meshes
  56340. for (i = 0; i < this._mapping.buttons.length; i++) {
  56341. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56342. if (!buttonMeshName) {
  56343. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56344. continue;
  56345. }
  56346. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56347. if (!buttonMesh) {
  56348. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56349. continue;
  56350. }
  56351. var buttonMeshInfo = {
  56352. index: i,
  56353. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56354. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56355. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56356. };
  56357. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56358. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56359. }
  56360. else {
  56361. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56362. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56363. '(VALUE: ' + !!buttonMeshInfo.value +
  56364. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56365. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56366. ')');
  56367. }
  56368. }
  56369. // Axis Meshes
  56370. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56371. var axisMeshName = this._mapping.axisMeshNames[i];
  56372. if (!axisMeshName) {
  56373. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56374. continue;
  56375. }
  56376. var axisMesh = getChildByName(rootNode, axisMeshName);
  56377. if (!axisMesh) {
  56378. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56379. continue;
  56380. }
  56381. var axisMeshInfo = {
  56382. index: i,
  56383. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56384. min: getImmediateChildByName(axisMesh, 'MIN'),
  56385. max: getImmediateChildByName(axisMesh, 'MAX')
  56386. };
  56387. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  56388. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  56389. }
  56390. else {
  56391. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  56392. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  56393. '(VALUE: ' + !!axisMeshInfo.value +
  56394. ', MIN: ' + !!axisMeshInfo.min +
  56395. ', MAX:' + !!axisMeshInfo.max +
  56396. ')');
  56397. }
  56398. }
  56399. // Pointing Ray
  56400. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  56401. if (!loadedMeshInfo.pointingPoseNode) {
  56402. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  56403. }
  56404. return loadedMeshInfo;
  56405. // Look through all children recursively. This will return null if no mesh exists with the given name.
  56406. function getChildByName(node, name) {
  56407. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  56408. }
  56409. // Look through only immediate children. This will return null if no mesh exists with the given name.
  56410. function getImmediateChildByName(node, name) {
  56411. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  56412. }
  56413. };
  56414. WindowsMotionController.prototype.getForwardRay = function (length) {
  56415. if (length === void 0) { length = 100; }
  56416. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  56417. return _super.prototype.getForwardRay.call(this, length);
  56418. }
  56419. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  56420. var origin = m.getTranslation();
  56421. var forward = new BABYLON.Vector3(0, 0, -1);
  56422. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56423. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56424. return new BABYLON.Ray(origin, direction, length);
  56425. };
  56426. WindowsMotionController.prototype.dispose = function () {
  56427. _super.prototype.dispose.call(this);
  56428. this.onTrackpadChangedObservable.clear();
  56429. };
  56430. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  56431. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  56432. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  56433. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  56434. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  56435. return WindowsMotionController;
  56436. }(BABYLON.WebVRController));
  56437. BABYLON.WindowsMotionController = WindowsMotionController;
  56438. })(BABYLON || (BABYLON = {}));
  56439. //# sourceMappingURL=babylon.windowsMotionController.js.map
  56440. var BABYLON;
  56441. (function (BABYLON) {
  56442. var FollowCamera = /** @class */ (function (_super) {
  56443. __extends(FollowCamera, _super);
  56444. function FollowCamera(name, position, scene, lockedTarget) {
  56445. if (lockedTarget === void 0) { lockedTarget = null; }
  56446. var _this = _super.call(this, name, position, scene) || this;
  56447. _this.radius = 12;
  56448. _this.rotationOffset = 0;
  56449. _this.heightOffset = 4;
  56450. _this.cameraAcceleration = 0.05;
  56451. _this.maxCameraSpeed = 20;
  56452. _this.lockedTarget = lockedTarget;
  56453. return _this;
  56454. }
  56455. FollowCamera.prototype.getRadians = function (degrees) {
  56456. return degrees * Math.PI / 180;
  56457. };
  56458. FollowCamera.prototype.follow = function (cameraTarget) {
  56459. if (!cameraTarget)
  56460. return;
  56461. var yRotation;
  56462. if (cameraTarget.rotationQuaternion) {
  56463. var rotMatrix = new BABYLON.Matrix();
  56464. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  56465. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  56466. }
  56467. else {
  56468. yRotation = cameraTarget.rotation.y;
  56469. }
  56470. var radians = this.getRadians(this.rotationOffset) + yRotation;
  56471. var targetPosition = cameraTarget.getAbsolutePosition();
  56472. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  56473. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  56474. var dx = targetX - this.position.x;
  56475. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  56476. var dz = (targetZ) - this.position.z;
  56477. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  56478. var vy = dy * this.cameraAcceleration;
  56479. var vz = dz * this.cameraAcceleration * 2;
  56480. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  56481. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56482. }
  56483. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  56484. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56485. }
  56486. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  56487. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56488. }
  56489. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  56490. this.setTarget(targetPosition);
  56491. };
  56492. FollowCamera.prototype._checkInputs = function () {
  56493. _super.prototype._checkInputs.call(this);
  56494. if (this.lockedTarget) {
  56495. this.follow(this.lockedTarget);
  56496. }
  56497. };
  56498. FollowCamera.prototype.getClassName = function () {
  56499. return "FollowCamera";
  56500. };
  56501. __decorate([
  56502. BABYLON.serialize()
  56503. ], FollowCamera.prototype, "radius", void 0);
  56504. __decorate([
  56505. BABYLON.serialize()
  56506. ], FollowCamera.prototype, "rotationOffset", void 0);
  56507. __decorate([
  56508. BABYLON.serialize()
  56509. ], FollowCamera.prototype, "heightOffset", void 0);
  56510. __decorate([
  56511. BABYLON.serialize()
  56512. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  56513. __decorate([
  56514. BABYLON.serialize()
  56515. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  56516. __decorate([
  56517. BABYLON.serializeAsMeshReference("lockedTargetId")
  56518. ], FollowCamera.prototype, "lockedTarget", void 0);
  56519. return FollowCamera;
  56520. }(BABYLON.TargetCamera));
  56521. BABYLON.FollowCamera = FollowCamera;
  56522. var ArcFollowCamera = /** @class */ (function (_super) {
  56523. __extends(ArcFollowCamera, _super);
  56524. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  56525. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  56526. _this.alpha = alpha;
  56527. _this.beta = beta;
  56528. _this.radius = radius;
  56529. _this.target = target;
  56530. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  56531. _this.follow();
  56532. return _this;
  56533. }
  56534. ArcFollowCamera.prototype.follow = function () {
  56535. if (!this.target) {
  56536. return;
  56537. }
  56538. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  56539. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  56540. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  56541. var targetPosition = this.target.getAbsolutePosition();
  56542. this.position = targetPosition.add(this._cartesianCoordinates);
  56543. this.setTarget(targetPosition);
  56544. };
  56545. ArcFollowCamera.prototype._checkInputs = function () {
  56546. _super.prototype._checkInputs.call(this);
  56547. this.follow();
  56548. };
  56549. ArcFollowCamera.prototype.getClassName = function () {
  56550. return "ArcFollowCamera";
  56551. };
  56552. return ArcFollowCamera;
  56553. }(BABYLON.TargetCamera));
  56554. BABYLON.ArcFollowCamera = ArcFollowCamera;
  56555. })(BABYLON || (BABYLON = {}));
  56556. //# sourceMappingURL=babylon.followCamera.js.map
  56557. var BABYLON;
  56558. (function (BABYLON) {
  56559. // We're mainly based on the logic defined into the FreeCamera code
  56560. var UniversalCamera = /** @class */ (function (_super) {
  56561. __extends(UniversalCamera, _super);
  56562. //-- end properties for backward compatibility for inputs
  56563. function UniversalCamera(name, position, scene) {
  56564. var _this = _super.call(this, name, position, scene) || this;
  56565. _this.inputs.addGamepad();
  56566. return _this;
  56567. }
  56568. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  56569. //-- Begin properties for backward compatibility for inputs
  56570. get: function () {
  56571. var gamepad = this.inputs.attached["gamepad"];
  56572. if (gamepad)
  56573. return gamepad.gamepadAngularSensibility;
  56574. return 0;
  56575. },
  56576. set: function (value) {
  56577. var gamepad = this.inputs.attached["gamepad"];
  56578. if (gamepad)
  56579. gamepad.gamepadAngularSensibility = value;
  56580. },
  56581. enumerable: true,
  56582. configurable: true
  56583. });
  56584. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  56585. get: function () {
  56586. var gamepad = this.inputs.attached["gamepad"];
  56587. if (gamepad)
  56588. return gamepad.gamepadMoveSensibility;
  56589. return 0;
  56590. },
  56591. set: function (value) {
  56592. var gamepad = this.inputs.attached["gamepad"];
  56593. if (gamepad)
  56594. gamepad.gamepadMoveSensibility = value;
  56595. },
  56596. enumerable: true,
  56597. configurable: true
  56598. });
  56599. UniversalCamera.prototype.getClassName = function () {
  56600. return "UniversalCamera";
  56601. };
  56602. return UniversalCamera;
  56603. }(BABYLON.TouchCamera));
  56604. BABYLON.UniversalCamera = UniversalCamera;
  56605. })(BABYLON || (BABYLON = {}));
  56606. //# sourceMappingURL=babylon.universalCamera.js.map
  56607. var BABYLON;
  56608. (function (BABYLON) {
  56609. // We're mainly based on the logic defined into the FreeCamera code
  56610. var GamepadCamera = /** @class */ (function (_super) {
  56611. __extends(GamepadCamera, _super);
  56612. //-- end properties for backward compatibility for inputs
  56613. function GamepadCamera(name, position, scene) {
  56614. return _super.call(this, name, position, scene) || this;
  56615. }
  56616. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  56617. //-- Begin properties for backward compatibility for inputs
  56618. get: function () {
  56619. var gamepad = this.inputs.attached["gamepad"];
  56620. if (gamepad)
  56621. return gamepad.gamepadAngularSensibility;
  56622. return 0;
  56623. },
  56624. set: function (value) {
  56625. var gamepad = this.inputs.attached["gamepad"];
  56626. if (gamepad)
  56627. gamepad.gamepadAngularSensibility = value;
  56628. },
  56629. enumerable: true,
  56630. configurable: true
  56631. });
  56632. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  56633. get: function () {
  56634. var gamepad = this.inputs.attached["gamepad"];
  56635. if (gamepad)
  56636. return gamepad.gamepadMoveSensibility;
  56637. return 0;
  56638. },
  56639. set: function (value) {
  56640. var gamepad = this.inputs.attached["gamepad"];
  56641. if (gamepad)
  56642. gamepad.gamepadMoveSensibility = value;
  56643. },
  56644. enumerable: true,
  56645. configurable: true
  56646. });
  56647. GamepadCamera.prototype.getClassName = function () {
  56648. return "GamepadCamera";
  56649. };
  56650. return GamepadCamera;
  56651. }(BABYLON.UniversalCamera));
  56652. BABYLON.GamepadCamera = GamepadCamera;
  56653. })(BABYLON || (BABYLON = {}));
  56654. //# sourceMappingURL=babylon.gamepadCamera.js.map
  56655. var BABYLON;
  56656. (function (BABYLON) {
  56657. var PostProcessRenderPipelineManager = /** @class */ (function () {
  56658. function PostProcessRenderPipelineManager() {
  56659. this._renderPipelines = {};
  56660. }
  56661. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  56662. this._renderPipelines[renderPipeline._name] = renderPipeline;
  56663. };
  56664. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  56665. if (unique === void 0) { unique = false; }
  56666. var renderPipeline = this._renderPipelines[renderPipelineName];
  56667. if (!renderPipeline) {
  56668. return;
  56669. }
  56670. renderPipeline._attachCameras(cameras, unique);
  56671. };
  56672. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  56673. var renderPipeline = this._renderPipelines[renderPipelineName];
  56674. if (!renderPipeline) {
  56675. return;
  56676. }
  56677. renderPipeline._detachCameras(cameras);
  56678. };
  56679. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56680. var renderPipeline = this._renderPipelines[renderPipelineName];
  56681. if (!renderPipeline) {
  56682. return;
  56683. }
  56684. renderPipeline._enableEffect(renderEffectName, cameras);
  56685. };
  56686. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56687. var renderPipeline = this._renderPipelines[renderPipelineName];
  56688. if (!renderPipeline) {
  56689. return;
  56690. }
  56691. renderPipeline._disableEffect(renderEffectName, cameras);
  56692. };
  56693. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  56694. var renderPipeline = this._renderPipelines[renderPipelineName];
  56695. if (!renderPipeline) {
  56696. return;
  56697. }
  56698. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  56699. };
  56700. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  56701. var renderPipeline = this._renderPipelines[renderPipelineName];
  56702. if (!renderPipeline) {
  56703. return;
  56704. }
  56705. renderPipeline._disableDisplayOnlyPass(cameras);
  56706. };
  56707. PostProcessRenderPipelineManager.prototype.update = function () {
  56708. for (var renderPipelineName in this._renderPipelines) {
  56709. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56710. var pipeline = this._renderPipelines[renderPipelineName];
  56711. if (!pipeline.isSupported) {
  56712. pipeline.dispose();
  56713. delete this._renderPipelines[renderPipelineName];
  56714. }
  56715. else {
  56716. pipeline._update();
  56717. }
  56718. }
  56719. }
  56720. };
  56721. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  56722. for (var renderPipelineName in this._renderPipelines) {
  56723. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56724. var pipeline = this._renderPipelines[renderPipelineName];
  56725. pipeline._rebuild();
  56726. }
  56727. }
  56728. };
  56729. PostProcessRenderPipelineManager.prototype.dispose = function () {
  56730. for (var renderPipelineName in this._renderPipelines) {
  56731. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56732. var pipeline = this._renderPipelines[renderPipelineName];
  56733. pipeline.dispose();
  56734. }
  56735. }
  56736. };
  56737. return PostProcessRenderPipelineManager;
  56738. }());
  56739. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  56740. })(BABYLON || (BABYLON = {}));
  56741. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  56742. var BABYLON;
  56743. (function (BABYLON) {
  56744. var PostProcessRenderPass = /** @class */ (function () {
  56745. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  56746. this._refCount = 0;
  56747. this._name = name;
  56748. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  56749. this.setRenderList(renderList);
  56750. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  56751. this._renderTexture.onAfterRenderObservable.add(afterRender);
  56752. this._scene = scene;
  56753. this._renderList = renderList;
  56754. }
  56755. // private
  56756. PostProcessRenderPass.prototype._incRefCount = function () {
  56757. if (this._refCount === 0) {
  56758. this._scene.customRenderTargets.push(this._renderTexture);
  56759. }
  56760. return ++this._refCount;
  56761. };
  56762. PostProcessRenderPass.prototype._decRefCount = function () {
  56763. this._refCount--;
  56764. if (this._refCount <= 0) {
  56765. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  56766. }
  56767. return this._refCount;
  56768. };
  56769. PostProcessRenderPass.prototype._update = function () {
  56770. this.setRenderList(this._renderList);
  56771. };
  56772. // public
  56773. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  56774. this._renderTexture.renderList = renderList;
  56775. };
  56776. PostProcessRenderPass.prototype.getRenderTexture = function () {
  56777. return this._renderTexture;
  56778. };
  56779. return PostProcessRenderPass;
  56780. }());
  56781. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  56782. })(BABYLON || (BABYLON = {}));
  56783. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  56784. var BABYLON;
  56785. (function (BABYLON) {
  56786. var PostProcessRenderEffect = /** @class */ (function () {
  56787. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  56788. this._engine = engine;
  56789. this._name = name;
  56790. this._singleInstance = singleInstance || true;
  56791. this._getPostProcess = getPostProcess;
  56792. this._cameras = {};
  56793. this._indicesForCamera = {};
  56794. this._postProcesses = {};
  56795. this._renderPasses = {};
  56796. this._renderEffectAsPasses = {};
  56797. }
  56798. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  56799. get: function () {
  56800. for (var index in this._postProcesses) {
  56801. if (!this._postProcesses[index].isSupported) {
  56802. return false;
  56803. }
  56804. }
  56805. return true;
  56806. },
  56807. enumerable: true,
  56808. configurable: true
  56809. });
  56810. PostProcessRenderEffect.prototype._update = function () {
  56811. for (var renderPassName in this._renderPasses) {
  56812. this._renderPasses[renderPassName]._update();
  56813. }
  56814. };
  56815. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  56816. this._renderPasses[renderPass._name] = renderPass;
  56817. this._linkParameters();
  56818. };
  56819. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  56820. delete this._renderPasses[renderPass._name];
  56821. this._linkParameters();
  56822. };
  56823. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  56824. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  56825. this._linkParameters();
  56826. };
  56827. PostProcessRenderEffect.prototype.getPass = function (passName) {
  56828. for (var renderPassName in this._renderPasses) {
  56829. if (renderPassName === passName) {
  56830. return this._renderPasses[passName];
  56831. }
  56832. }
  56833. return null;
  56834. };
  56835. PostProcessRenderEffect.prototype.emptyPasses = function () {
  56836. this._renderPasses = {};
  56837. this._linkParameters();
  56838. };
  56839. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  56840. var cameraKey;
  56841. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56842. if (!cams) {
  56843. return;
  56844. }
  56845. for (var i = 0; i < cams.length; i++) {
  56846. var camera = cams[i];
  56847. var cameraName = camera.name;
  56848. if (this._singleInstance) {
  56849. cameraKey = 0;
  56850. }
  56851. else {
  56852. cameraKey = cameraName;
  56853. }
  56854. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  56855. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  56856. if (!this._indicesForCamera[cameraName]) {
  56857. this._indicesForCamera[cameraName] = [];
  56858. }
  56859. this._indicesForCamera[cameraName].push(index);
  56860. if (!this._cameras[cameraName]) {
  56861. this._cameras[cameraName] = camera;
  56862. }
  56863. for (var passName in this._renderPasses) {
  56864. this._renderPasses[passName]._incRefCount();
  56865. }
  56866. }
  56867. this._linkParameters();
  56868. };
  56869. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  56870. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56871. if (!cams) {
  56872. return;
  56873. }
  56874. for (var i = 0; i < cams.length; i++) {
  56875. var camera = cams[i];
  56876. var cameraName = camera.name;
  56877. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56878. if (this._cameras[cameraName]) {
  56879. //this._indicesForCamera.splice(index, 1);
  56880. this._cameras[cameraName] = null;
  56881. }
  56882. for (var passName in this._renderPasses) {
  56883. this._renderPasses[passName]._decRefCount();
  56884. }
  56885. }
  56886. };
  56887. PostProcessRenderEffect.prototype._enable = function (cameras) {
  56888. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56889. if (!cams) {
  56890. return;
  56891. }
  56892. for (var i = 0; i < cams.length; i++) {
  56893. var camera = cams[i];
  56894. var cameraName = camera.name;
  56895. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  56896. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  56897. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  56898. }
  56899. }
  56900. for (var passName in this._renderPasses) {
  56901. this._renderPasses[passName]._incRefCount();
  56902. }
  56903. }
  56904. };
  56905. PostProcessRenderEffect.prototype._disable = function (cameras) {
  56906. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56907. if (!cams) {
  56908. return;
  56909. }
  56910. for (var i = 0; i < cams.length; i++) {
  56911. var camera = cams[i];
  56912. var cameraName = camera.Name;
  56913. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56914. for (var passName in this._renderPasses) {
  56915. this._renderPasses[passName]._decRefCount();
  56916. }
  56917. }
  56918. };
  56919. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  56920. if (this._singleInstance) {
  56921. return this._postProcesses[0];
  56922. }
  56923. else {
  56924. if (!camera) {
  56925. return null;
  56926. }
  56927. return this._postProcesses[camera.name];
  56928. }
  56929. };
  56930. PostProcessRenderEffect.prototype._linkParameters = function () {
  56931. var _this = this;
  56932. for (var index in this._postProcesses) {
  56933. if (this.applyParameters) {
  56934. this.applyParameters(this._postProcesses[index]);
  56935. }
  56936. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  56937. _this._linkTextures(effect);
  56938. });
  56939. }
  56940. };
  56941. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  56942. for (var renderPassName in this._renderPasses) {
  56943. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  56944. }
  56945. for (var renderEffectName in this._renderEffectAsPasses) {
  56946. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  56947. }
  56948. };
  56949. return PostProcessRenderEffect;
  56950. }());
  56951. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  56952. })(BABYLON || (BABYLON = {}));
  56953. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  56954. var BABYLON;
  56955. (function (BABYLON) {
  56956. var PostProcessRenderPipeline = /** @class */ (function () {
  56957. function PostProcessRenderPipeline(engine, name) {
  56958. this._engine = engine;
  56959. this._name = name;
  56960. this._renderEffects = {};
  56961. this._renderEffectsForIsolatedPass = new Array();
  56962. this._cameras = [];
  56963. }
  56964. PostProcessRenderPipeline.prototype.getClassName = function () {
  56965. return "PostProcessRenderPipeline";
  56966. };
  56967. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  56968. get: function () {
  56969. for (var renderEffectName in this._renderEffects) {
  56970. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56971. if (!this._renderEffects[renderEffectName].isSupported) {
  56972. return false;
  56973. }
  56974. }
  56975. }
  56976. return true;
  56977. },
  56978. enumerable: true,
  56979. configurable: true
  56980. });
  56981. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  56982. this._renderEffects[renderEffect._name] = renderEffect;
  56983. };
  56984. // private
  56985. PostProcessRenderPipeline.prototype._rebuild = function () {
  56986. };
  56987. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  56988. var renderEffects = this._renderEffects[renderEffectName];
  56989. if (!renderEffects) {
  56990. return;
  56991. }
  56992. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56993. };
  56994. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  56995. var renderEffects = this._renderEffects[renderEffectName];
  56996. if (!renderEffects) {
  56997. return;
  56998. }
  56999. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57000. };
  57001. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  57002. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57003. if (!cams) {
  57004. return;
  57005. }
  57006. var indicesToDelete = [];
  57007. var i;
  57008. for (i = 0; i < cams.length; i++) {
  57009. var camera = cams[i];
  57010. var cameraName = camera.name;
  57011. if (this._cameras.indexOf(camera) === -1) {
  57012. this._cameras[cameraName] = camera;
  57013. }
  57014. else if (unique) {
  57015. indicesToDelete.push(i);
  57016. }
  57017. }
  57018. for (i = 0; i < indicesToDelete.length; i++) {
  57019. cameras.splice(indicesToDelete[i], 1);
  57020. }
  57021. for (var renderEffectName in this._renderEffects) {
  57022. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57023. this._renderEffects[renderEffectName]._attachCameras(cams);
  57024. }
  57025. }
  57026. };
  57027. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  57028. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57029. if (!cams) {
  57030. return;
  57031. }
  57032. for (var renderEffectName in this._renderEffects) {
  57033. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57034. this._renderEffects[renderEffectName]._detachCameras(cams);
  57035. }
  57036. }
  57037. for (var i = 0; i < cams.length; i++) {
  57038. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  57039. }
  57040. };
  57041. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  57042. var _this = this;
  57043. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57044. if (!cams) {
  57045. return;
  57046. }
  57047. var pass = null;
  57048. var renderEffectName;
  57049. for (renderEffectName in this._renderEffects) {
  57050. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57051. pass = this._renderEffects[renderEffectName].getPass(passName);
  57052. if (pass != null) {
  57053. break;
  57054. }
  57055. }
  57056. }
  57057. if (pass === null) {
  57058. return;
  57059. }
  57060. for (renderEffectName in this._renderEffects) {
  57061. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57062. this._renderEffects[renderEffectName]._disable(cams);
  57063. }
  57064. }
  57065. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  57066. for (var i = 0; i < cams.length; i++) {
  57067. var camera = cams[i];
  57068. var cameraName = camera.name;
  57069. 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); });
  57070. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  57071. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  57072. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  57073. }
  57074. };
  57075. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  57076. var _this = this;
  57077. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57078. if (!cams) {
  57079. return;
  57080. }
  57081. for (var i = 0; i < cams.length; i++) {
  57082. var camera = cams[i];
  57083. var cameraName = camera.name;
  57084. 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); });
  57085. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  57086. }
  57087. for (var renderEffectName in this._renderEffects) {
  57088. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57089. this._renderEffects[renderEffectName]._enable(cams);
  57090. }
  57091. }
  57092. };
  57093. PostProcessRenderPipeline.prototype._update = function () {
  57094. for (var renderEffectName in this._renderEffects) {
  57095. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57096. this._renderEffects[renderEffectName]._update();
  57097. }
  57098. }
  57099. for (var i = 0; i < this._cameras.length; i++) {
  57100. var cameraName = this._cameras[i].name;
  57101. if (this._renderEffectsForIsolatedPass[cameraName]) {
  57102. this._renderEffectsForIsolatedPass[cameraName]._update();
  57103. }
  57104. }
  57105. };
  57106. PostProcessRenderPipeline.prototype._reset = function () {
  57107. this._renderEffects = {};
  57108. this._renderEffectsForIsolatedPass = new Array();
  57109. };
  57110. PostProcessRenderPipeline.prototype.dispose = function () {
  57111. // Must be implemented by children
  57112. };
  57113. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  57114. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  57115. __decorate([
  57116. BABYLON.serialize()
  57117. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  57118. return PostProcessRenderPipeline;
  57119. }());
  57120. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  57121. })(BABYLON || (BABYLON = {}));
  57122. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  57123. var BABYLON;
  57124. (function (BABYLON) {
  57125. var DepthRenderer = /** @class */ (function () {
  57126. function DepthRenderer(scene, type) {
  57127. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  57128. var _this = this;
  57129. this._scene = scene;
  57130. var engine = scene.getEngine();
  57131. // Render target
  57132. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  57133. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57134. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57135. this._depthMap.refreshRate = 1;
  57136. this._depthMap.renderParticles = false;
  57137. this._depthMap.renderList = null;
  57138. // set default depth value to 1.0 (far away)
  57139. this._depthMap.onClearObservable.add(function (engine) {
  57140. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  57141. });
  57142. // Custom render function
  57143. var renderSubMesh = function (subMesh) {
  57144. var mesh = subMesh.getRenderingMesh();
  57145. var scene = _this._scene;
  57146. var engine = scene.getEngine();
  57147. var material = subMesh.getMaterial();
  57148. if (!material) {
  57149. return;
  57150. }
  57151. // Culling
  57152. engine.setState(material.backFaceCulling);
  57153. // Managing instances
  57154. var batch = mesh._getInstancesRenderList(subMesh._id);
  57155. if (batch.mustReturn) {
  57156. return;
  57157. }
  57158. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57159. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  57160. engine.enableEffect(_this._effect);
  57161. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  57162. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  57163. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  57164. // Alpha test
  57165. if (material && material.needAlphaTesting()) {
  57166. var alphaTexture = material.getAlphaTestTexture();
  57167. if (alphaTexture) {
  57168. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57169. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57170. }
  57171. }
  57172. // Bones
  57173. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57174. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57175. }
  57176. // Draw
  57177. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57178. }
  57179. };
  57180. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57181. var index;
  57182. if (depthOnlySubMeshes.length) {
  57183. engine.setColorWrite(false);
  57184. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57185. renderSubMesh(depthOnlySubMeshes.data[index]);
  57186. }
  57187. engine.setColorWrite(true);
  57188. }
  57189. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57190. renderSubMesh(opaqueSubMeshes.data[index]);
  57191. }
  57192. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57193. renderSubMesh(alphaTestSubMeshes.data[index]);
  57194. }
  57195. };
  57196. }
  57197. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  57198. var material = subMesh.getMaterial();
  57199. if (material.disableDepthWrite) {
  57200. return false;
  57201. }
  57202. var defines = [];
  57203. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57204. var mesh = subMesh.getMesh();
  57205. // Alpha test
  57206. if (material && material.needAlphaTesting()) {
  57207. defines.push("#define ALPHATEST");
  57208. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57209. attribs.push(BABYLON.VertexBuffer.UVKind);
  57210. defines.push("#define UV1");
  57211. }
  57212. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57213. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57214. defines.push("#define UV2");
  57215. }
  57216. }
  57217. // Bones
  57218. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57219. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57220. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57221. if (mesh.numBoneInfluencers > 4) {
  57222. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57223. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57224. }
  57225. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57226. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  57227. }
  57228. else {
  57229. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57230. }
  57231. // Instances
  57232. if (useInstances) {
  57233. defines.push("#define INSTANCES");
  57234. attribs.push("world0");
  57235. attribs.push("world1");
  57236. attribs.push("world2");
  57237. attribs.push("world3");
  57238. }
  57239. // Get correct effect
  57240. var join = defines.join("\n");
  57241. if (this._cachedDefines !== join) {
  57242. this._cachedDefines = join;
  57243. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  57244. }
  57245. return this._effect.isReady();
  57246. };
  57247. DepthRenderer.prototype.getDepthMap = function () {
  57248. return this._depthMap;
  57249. };
  57250. // Methods
  57251. DepthRenderer.prototype.dispose = function () {
  57252. this._depthMap.dispose();
  57253. };
  57254. return DepthRenderer;
  57255. }());
  57256. BABYLON.DepthRenderer = DepthRenderer;
  57257. })(BABYLON || (BABYLON = {}));
  57258. //# sourceMappingURL=babylon.depthRenderer.js.map
  57259. var BABYLON;
  57260. (function (BABYLON) {
  57261. var SSAORenderingPipeline = /** @class */ (function (_super) {
  57262. __extends(SSAORenderingPipeline, _super);
  57263. /**
  57264. * @constructor
  57265. * @param {string} name - The rendering pipeline name
  57266. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57267. * @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 }
  57268. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57269. */
  57270. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  57271. var _this = _super.call(this, scene.getEngine(), name) || this;
  57272. // Members
  57273. /**
  57274. * The PassPostProcess id in the pipeline that contains the original scene color
  57275. * @type {string}
  57276. */
  57277. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57278. /**
  57279. * The SSAO PostProcess id in the pipeline
  57280. * @type {string}
  57281. */
  57282. _this.SSAORenderEffect = "SSAORenderEffect";
  57283. /**
  57284. * The horizontal blur PostProcess id in the pipeline
  57285. * @type {string}
  57286. */
  57287. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57288. /**
  57289. * The vertical blur PostProcess id in the pipeline
  57290. * @type {string}
  57291. */
  57292. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57293. /**
  57294. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57295. * @type {string}
  57296. */
  57297. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57298. /**
  57299. * The output strength of the SSAO post-process. Default value is 1.0.
  57300. * @type {number}
  57301. */
  57302. _this.totalStrength = 1.0;
  57303. /**
  57304. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  57305. * @type {number}
  57306. */
  57307. _this.radius = 0.0001;
  57308. /**
  57309. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  57310. * Must not be equal to fallOff and superior to fallOff.
  57311. * Default value is 0.975
  57312. * @type {number}
  57313. */
  57314. _this.area = 0.0075;
  57315. /**
  57316. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  57317. * Must not be equal to area and inferior to area.
  57318. * Default value is 0.0
  57319. * @type {number}
  57320. */
  57321. _this.fallOff = 0.000001;
  57322. /**
  57323. * The base color of the SSAO post-process
  57324. * The final result is "base + ssao" between [0, 1]
  57325. * @type {number}
  57326. */
  57327. _this.base = 0.5;
  57328. _this._firstUpdate = true;
  57329. _this._scene = scene;
  57330. // Set up assets
  57331. _this._createRandomTexture();
  57332. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57333. var ssaoRatio = ratio.ssaoRatio || ratio;
  57334. var combineRatio = ratio.combineRatio || ratio;
  57335. _this._ratio = {
  57336. ssaoRatio: ssaoRatio,
  57337. combineRatio: combineRatio
  57338. };
  57339. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57340. _this._createSSAOPostProcess(ssaoRatio);
  57341. _this._createBlurPostProcess(ssaoRatio);
  57342. _this._createSSAOCombinePostProcess(combineRatio);
  57343. // Set up pipeline
  57344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57345. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57346. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57347. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57348. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57349. // Finish
  57350. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57351. if (cameras)
  57352. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57353. return _this;
  57354. }
  57355. // Public Methods
  57356. /**
  57357. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57358. */
  57359. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57360. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57361. for (var i = 0; i < this._scene.cameras.length; i++) {
  57362. var camera = this._scene.cameras[i];
  57363. this._originalColorPostProcess.dispose(camera);
  57364. this._ssaoPostProcess.dispose(camera);
  57365. this._blurHPostProcess.dispose(camera);
  57366. this._blurVPostProcess.dispose(camera);
  57367. this._ssaoCombinePostProcess.dispose(camera);
  57368. }
  57369. this._randomTexture.dispose();
  57370. if (disableDepthRender)
  57371. this._scene.disableDepthRenderer();
  57372. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57373. _super.prototype.dispose.call(this);
  57374. };
  57375. // Private Methods
  57376. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57377. var _this = this;
  57378. /*
  57379. var samplerOffsets = [
  57380. -8.0, -6.0, -4.0, -2.0,
  57381. 0.0,
  57382. 2.0, 4.0, 6.0, 8.0
  57383. ];
  57384. */
  57385. var samplerOffsets = new Array();
  57386. for (var i = -8; i < 8; i++) {
  57387. samplerOffsets.push(i * 2);
  57388. }
  57389. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  57390. this._blurHPostProcess.onApply = function (effect) {
  57391. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57392. effect.setTexture("depthSampler", _this._depthTexture);
  57393. if (_this._firstUpdate) {
  57394. effect.setArray("samplerOffsets", samplerOffsets);
  57395. }
  57396. };
  57397. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  57398. this._blurVPostProcess.onApply = function (effect) {
  57399. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57400. effect.setTexture("depthSampler", _this._depthTexture);
  57401. if (_this._firstUpdate) {
  57402. effect.setArray("samplerOffsets", samplerOffsets);
  57403. _this._firstUpdate = false;
  57404. }
  57405. };
  57406. };
  57407. SSAORenderingPipeline.prototype._rebuild = function () {
  57408. this._firstUpdate = true;
  57409. _super.prototype._rebuild.call(this);
  57410. };
  57411. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57412. var _this = this;
  57413. var numSamples = 16;
  57414. var sampleSphere = [
  57415. 0.5381, 0.1856, -0.4319,
  57416. 0.1379, 0.2486, 0.4430,
  57417. 0.3371, 0.5679, -0.0057,
  57418. -0.6999, -0.0451, -0.0019,
  57419. 0.0689, -0.1598, -0.8547,
  57420. 0.0560, 0.0069, -0.1843,
  57421. -0.0146, 0.1402, 0.0762,
  57422. 0.0100, -0.1924, -0.0344,
  57423. -0.3577, -0.5301, -0.4358,
  57424. -0.3169, 0.1063, 0.0158,
  57425. 0.0103, -0.5869, 0.0046,
  57426. -0.0897, -0.4940, 0.3287,
  57427. 0.7119, -0.0154, -0.0918,
  57428. -0.0533, 0.0596, -0.5411,
  57429. 0.0352, -0.0631, 0.5460,
  57430. -0.4776, 0.2847, -0.0271
  57431. ];
  57432. var samplesFactor = 1.0 / numSamples;
  57433. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  57434. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57435. "area", "fallOff", "base", "range", "viewport"
  57436. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57437. this._ssaoPostProcess.onApply = function (effect) {
  57438. if (_this._firstUpdate) {
  57439. effect.setArray3("sampleSphere", sampleSphere);
  57440. effect.setFloat("samplesFactor", samplesFactor);
  57441. effect.setFloat("randTextureTiles", 4.0);
  57442. }
  57443. effect.setFloat("totalStrength", _this.totalStrength);
  57444. effect.setFloat("radius", _this.radius);
  57445. effect.setFloat("area", _this.area);
  57446. effect.setFloat("fallOff", _this.fallOff);
  57447. effect.setFloat("base", _this.base);
  57448. effect.setTexture("textureSampler", _this._depthTexture);
  57449. effect.setTexture("randomSampler", _this._randomTexture);
  57450. };
  57451. };
  57452. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57453. var _this = this;
  57454. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57455. this._ssaoCombinePostProcess.onApply = function (effect) {
  57456. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57457. };
  57458. };
  57459. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  57460. var size = 512;
  57461. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57462. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57463. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57464. var context = this._randomTexture.getContext();
  57465. var rand = function (min, max) {
  57466. return Math.random() * (max - min) + min;
  57467. };
  57468. var randVector = BABYLON.Vector3.Zero();
  57469. for (var x = 0; x < size; x++) {
  57470. for (var y = 0; y < size; y++) {
  57471. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  57472. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  57473. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  57474. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57475. context.fillRect(x, y, 1, 1);
  57476. }
  57477. }
  57478. this._randomTexture.update(false);
  57479. };
  57480. __decorate([
  57481. BABYLON.serialize()
  57482. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  57483. __decorate([
  57484. BABYLON.serialize()
  57485. ], SSAORenderingPipeline.prototype, "radius", void 0);
  57486. __decorate([
  57487. BABYLON.serialize()
  57488. ], SSAORenderingPipeline.prototype, "area", void 0);
  57489. __decorate([
  57490. BABYLON.serialize()
  57491. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  57492. __decorate([
  57493. BABYLON.serialize()
  57494. ], SSAORenderingPipeline.prototype, "base", void 0);
  57495. __decorate([
  57496. BABYLON.serialize()
  57497. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  57498. return SSAORenderingPipeline;
  57499. }(BABYLON.PostProcessRenderPipeline));
  57500. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  57501. })(BABYLON || (BABYLON = {}));
  57502. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  57503. var BABYLON;
  57504. (function (BABYLON) {
  57505. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  57506. __extends(SSAO2RenderingPipeline, _super);
  57507. /**
  57508. * @constructor
  57509. * @param {string} name - The rendering pipeline name
  57510. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57511. * @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 }
  57512. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57513. */
  57514. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  57515. var _this = _super.call(this, scene.getEngine(), name) || this;
  57516. // Members
  57517. /**
  57518. * The PassPostProcess id in the pipeline that contains the original scene color
  57519. * @type {string}
  57520. */
  57521. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57522. /**
  57523. * The SSAO PostProcess id in the pipeline
  57524. * @type {string}
  57525. */
  57526. _this.SSAORenderEffect = "SSAORenderEffect";
  57527. /**
  57528. * The horizontal blur PostProcess id in the pipeline
  57529. * @type {string}
  57530. */
  57531. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57532. /**
  57533. * The vertical blur PostProcess id in the pipeline
  57534. * @type {string}
  57535. */
  57536. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57537. /**
  57538. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57539. * @type {string}
  57540. */
  57541. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57542. /**
  57543. * The output strength of the SSAO post-process. Default value is 1.0.
  57544. * @type {number}
  57545. */
  57546. _this.totalStrength = 1.0;
  57547. /**
  57548. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  57549. * @type {number}
  57550. */
  57551. _this.maxZ = 100.0;
  57552. /**
  57553. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  57554. * @type {number}
  57555. */
  57556. _this.minZAspect = 0.2;
  57557. /**
  57558. * Number of samples used for the SSAO calculations. Default value is 8
  57559. * @type {number}
  57560. */
  57561. _this._samples = 8;
  57562. /**
  57563. * Are we using bilateral blur ?
  57564. * @type {boolean}
  57565. */
  57566. _this._expensiveBlur = true;
  57567. /**
  57568. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  57569. * @type {number}
  57570. */
  57571. _this.radius = 2.0;
  57572. /**
  57573. * The base color of the SSAO post-process
  57574. * The final result is "base + ssao" between [0, 1]
  57575. * @type {number}
  57576. */
  57577. _this.base = 0.1;
  57578. _this._firstUpdate = true;
  57579. _this._scene = scene;
  57580. if (!_this.isSupported) {
  57581. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  57582. return _this;
  57583. }
  57584. var ssaoRatio = ratio.ssaoRatio || ratio;
  57585. var blurRatio = ratio.blurRatio || ratio;
  57586. _this._ratio = {
  57587. ssaoRatio: ssaoRatio,
  57588. blurRatio: blurRatio
  57589. };
  57590. // Set up assets
  57591. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  57592. _this._createRandomTexture();
  57593. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  57594. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  57595. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57596. _this._createSSAOPostProcess(1.0);
  57597. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  57598. _this._createSSAOCombinePostProcess(blurRatio);
  57599. // Set up pipeline
  57600. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57601. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57602. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57603. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57604. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57605. // Finish
  57606. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57607. if (cameras)
  57608. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57609. return _this;
  57610. }
  57611. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  57612. get: function () {
  57613. return this._samples;
  57614. },
  57615. set: function (n) {
  57616. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  57617. this._samples = n;
  57618. this._sampleSphere = this._generateHemisphere();
  57619. this._firstUpdate = true;
  57620. },
  57621. enumerable: true,
  57622. configurable: true
  57623. });
  57624. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  57625. get: function () {
  57626. return this._expensiveBlur;
  57627. },
  57628. set: function (b) {
  57629. 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"]);
  57630. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  57631. this._expensiveBlur = b;
  57632. this._firstUpdate = true;
  57633. },
  57634. enumerable: true,
  57635. configurable: true
  57636. });
  57637. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  57638. /**
  57639. * Support test.
  57640. * @type {boolean}
  57641. */
  57642. get: function () {
  57643. var engine = BABYLON.Engine.LastCreatedEngine;
  57644. if (!engine) {
  57645. return false;
  57646. }
  57647. return engine.getCaps().drawBuffersExtension;
  57648. },
  57649. enumerable: true,
  57650. configurable: true
  57651. });
  57652. // Public Methods
  57653. /**
  57654. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57655. */
  57656. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  57657. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  57658. for (var i = 0; i < this._scene.cameras.length; i++) {
  57659. var camera = this._scene.cameras[i];
  57660. this._originalColorPostProcess.dispose(camera);
  57661. this._ssaoPostProcess.dispose(camera);
  57662. this._blurHPostProcess.dispose(camera);
  57663. this._blurVPostProcess.dispose(camera);
  57664. this._ssaoCombinePostProcess.dispose(camera);
  57665. }
  57666. this._randomTexture.dispose();
  57667. if (disableGeometryBufferRenderer)
  57668. this._scene.disableGeometryBufferRenderer();
  57669. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57670. _super.prototype.dispose.call(this);
  57671. };
  57672. // Private Methods
  57673. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  57674. var _this = this;
  57675. this._samplerOffsets = [];
  57676. var expensive = this.expensiveBlur;
  57677. for (var i = -8; i < 8; i++) {
  57678. this._samplerOffsets.push(i * 2 + 0.5);
  57679. }
  57680. 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");
  57681. this._blurHPostProcess.onApply = function (effect) {
  57682. if (!_this._scene.activeCamera) {
  57683. return;
  57684. }
  57685. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57686. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57687. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57688. effect.setFloat("radius", _this.radius);
  57689. effect.setTexture("depthSampler", _this._depthTexture);
  57690. if (_this._firstUpdate) {
  57691. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57692. }
  57693. };
  57694. 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");
  57695. this._blurVPostProcess.onApply = function (effect) {
  57696. if (!_this._scene.activeCamera) {
  57697. return;
  57698. }
  57699. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57700. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57701. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57702. effect.setFloat("radius", _this.radius);
  57703. effect.setTexture("depthSampler", _this._depthTexture);
  57704. if (_this._firstUpdate) {
  57705. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57706. _this._firstUpdate = false;
  57707. }
  57708. };
  57709. };
  57710. SSAO2RenderingPipeline.prototype._rebuild = function () {
  57711. this._firstUpdate = true;
  57712. _super.prototype._rebuild.call(this);
  57713. };
  57714. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  57715. var numSamples = this.samples;
  57716. var result = [];
  57717. var vector, scale;
  57718. var rand = function (min, max) {
  57719. return Math.random() * (max - min) + min;
  57720. };
  57721. var i = 0;
  57722. while (i < numSamples) {
  57723. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  57724. vector.normalize();
  57725. scale = i / numSamples;
  57726. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  57727. vector.scaleInPlace(scale);
  57728. result.push(vector.x, vector.y, vector.z);
  57729. i++;
  57730. }
  57731. return result;
  57732. };
  57733. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57734. var _this = this;
  57735. var numSamples = this.samples;
  57736. this._sampleSphere = this._generateHemisphere();
  57737. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  57738. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57739. "base", "range", "projection", "near", "far", "texelSize",
  57740. "xViewport", "yViewport", "maxZ", "minZAspect"
  57741. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57742. this._ssaoPostProcess.onApply = function (effect) {
  57743. if (_this._firstUpdate) {
  57744. effect.setArray3("sampleSphere", _this._sampleSphere);
  57745. effect.setFloat("randTextureTiles", 4.0);
  57746. }
  57747. if (!_this._scene.activeCamera) {
  57748. return;
  57749. }
  57750. effect.setFloat("samplesFactor", 1 / _this.samples);
  57751. effect.setFloat("totalStrength", _this.totalStrength);
  57752. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  57753. effect.setFloat("radius", _this.radius);
  57754. effect.setFloat("maxZ", _this.maxZ);
  57755. effect.setFloat("minZAspect", _this.minZAspect);
  57756. effect.setFloat("base", _this.base);
  57757. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57758. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57759. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  57760. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  57761. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  57762. effect.setTexture("textureSampler", _this._depthTexture);
  57763. effect.setTexture("normalSampler", _this._normalTexture);
  57764. effect.setTexture("randomSampler", _this._randomTexture);
  57765. };
  57766. };
  57767. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57768. var _this = this;
  57769. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57770. this._ssaoCombinePostProcess.onApply = function (effect) {
  57771. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57772. };
  57773. };
  57774. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  57775. var size = 512;
  57776. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57777. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57778. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57779. var context = this._randomTexture.getContext();
  57780. var rand = function (min, max) {
  57781. return Math.random() * (max - min) + min;
  57782. };
  57783. var randVector = BABYLON.Vector3.Zero();
  57784. for (var x = 0; x < size; x++) {
  57785. for (var y = 0; y < size; y++) {
  57786. randVector.x = rand(0.0, 1.0);
  57787. randVector.y = rand(0.0, 1.0);
  57788. randVector.z = 0.0;
  57789. randVector.normalize();
  57790. randVector.scaleInPlace(255);
  57791. randVector.x = Math.floor(randVector.x);
  57792. randVector.y = Math.floor(randVector.y);
  57793. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57794. context.fillRect(x, y, 1, 1);
  57795. }
  57796. }
  57797. this._randomTexture.update(false);
  57798. };
  57799. __decorate([
  57800. BABYLON.serialize()
  57801. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  57802. __decorate([
  57803. BABYLON.serialize()
  57804. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  57805. __decorate([
  57806. BABYLON.serialize()
  57807. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  57808. __decorate([
  57809. BABYLON.serialize("samples")
  57810. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  57811. __decorate([
  57812. BABYLON.serialize("expensiveBlur")
  57813. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  57814. __decorate([
  57815. BABYLON.serialize()
  57816. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  57817. __decorate([
  57818. BABYLON.serialize()
  57819. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  57820. __decorate([
  57821. BABYLON.serialize()
  57822. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  57823. return SSAO2RenderingPipeline;
  57824. }(BABYLON.PostProcessRenderPipeline));
  57825. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  57826. })(BABYLON || (BABYLON = {}));
  57827. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  57828. // BABYLON.JS Chromatic Aberration GLSL Shader
  57829. // Author: Olivier Guyot
  57830. // Separates very slightly R, G and B colors on the edges of the screen
  57831. // Inspired by Francois Tarlier & Martins Upitis
  57832. var BABYLON;
  57833. (function (BABYLON) {
  57834. var LensRenderingPipeline = /** @class */ (function (_super) {
  57835. __extends(LensRenderingPipeline, _super);
  57836. /**
  57837. * @constructor
  57838. *
  57839. * Effect parameters are as follow:
  57840. * {
  57841. * chromatic_aberration: number; // from 0 to x (1 for realism)
  57842. * edge_blur: number; // from 0 to x (1 for realism)
  57843. * distortion: number; // from 0 to x (1 for realism)
  57844. * grain_amount: number; // from 0 to 1
  57845. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  57846. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  57847. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  57848. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  57849. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  57850. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  57851. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  57852. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  57853. * }
  57854. * Note: if an effect parameter is unset, effect is disabled
  57855. *
  57856. * @param {string} name - The rendering pipeline name
  57857. * @param {object} parameters - An object containing all parameters (see above)
  57858. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57859. * @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)
  57860. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57861. */
  57862. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  57863. if (ratio === void 0) { ratio = 1.0; }
  57864. var _this = _super.call(this, scene.getEngine(), name) || this;
  57865. // Lens effects can be of the following:
  57866. // - chromatic aberration (slight shift of RGB colors)
  57867. // - blur on the edge of the lens
  57868. // - lens distortion
  57869. // - depth-of-field blur & highlights enhancing
  57870. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  57871. // - grain effect (noise or custom texture)
  57872. // Two additional texture samplers are needed:
  57873. // - depth map (for depth-of-field)
  57874. // - grain texture
  57875. /**
  57876. * The chromatic aberration PostProcess id in the pipeline
  57877. * @type {string}
  57878. */
  57879. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  57880. /**
  57881. * The highlights enhancing PostProcess id in the pipeline
  57882. * @type {string}
  57883. */
  57884. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  57885. /**
  57886. * The depth-of-field PostProcess id in the pipeline
  57887. * @type {string}
  57888. */
  57889. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  57890. _this._scene = scene;
  57891. // Fetch texture samplers
  57892. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57893. if (parameters.grain_texture) {
  57894. _this._grainTexture = parameters.grain_texture;
  57895. }
  57896. else {
  57897. _this._createGrainTexture();
  57898. }
  57899. // save parameters
  57900. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  57901. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  57902. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  57903. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  57904. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  57905. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  57906. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  57907. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  57908. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  57909. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  57910. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  57911. // Create effects
  57912. _this._createChromaticAberrationPostProcess(ratio);
  57913. _this._createHighlightsPostProcess(ratio);
  57914. _this._createDepthOfFieldPostProcess(ratio / 4);
  57915. // Set up pipeline
  57916. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  57917. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  57918. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  57919. if (_this._highlightsGain === -1) {
  57920. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  57921. }
  57922. // Finish
  57923. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57924. if (cameras) {
  57925. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57926. }
  57927. return _this;
  57928. }
  57929. // public methods (self explanatory)
  57930. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  57931. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  57932. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  57933. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  57934. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  57935. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  57936. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  57937. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  57938. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  57939. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  57940. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  57941. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  57942. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  57943. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  57944. };
  57945. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  57946. this._highlightsPostProcess.updateEffect();
  57947. };
  57948. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  57949. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  57950. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  57951. this._highlightsGain = amount;
  57952. };
  57953. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  57954. if (this._highlightsGain === -1) {
  57955. this._highlightsGain = 1.0;
  57956. }
  57957. this._highlightsThreshold = amount;
  57958. };
  57959. LensRenderingPipeline.prototype.disableHighlights = function () {
  57960. this._highlightsGain = -1;
  57961. };
  57962. /**
  57963. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  57964. */
  57965. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57966. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57967. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57968. this._chromaticAberrationPostProcess = null;
  57969. this._highlightsPostProcess = null;
  57970. this._depthOfFieldPostProcess = null;
  57971. this._grainTexture.dispose();
  57972. if (disableDepthRender)
  57973. this._scene.disableDepthRenderer();
  57974. };
  57975. // colors shifting and distortion
  57976. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  57977. var _this = this;
  57978. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  57979. [], // samplers
  57980. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57981. this._chromaticAberrationPostProcess.onApply = function (effect) {
  57982. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  57983. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57984. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57985. };
  57986. };
  57987. // highlights enhancing
  57988. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  57989. var _this = this;
  57990. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  57991. [], // samplers
  57992. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  57993. this._highlightsPostProcess.onApply = function (effect) {
  57994. effect.setFloat('gain', _this._highlightsGain);
  57995. effect.setFloat('threshold', _this._highlightsThreshold);
  57996. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  57997. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57998. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57999. };
  58000. };
  58001. // colors shifting and distortion
  58002. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  58003. var _this = this;
  58004. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  58005. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  58006. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  58007. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58008. this._depthOfFieldPostProcess.onApply = function (effect) {
  58009. effect.setTexture("depthSampler", _this._depthTexture);
  58010. effect.setTexture("grainSampler", _this._grainTexture);
  58011. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  58012. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  58013. effect.setFloat('grain_amount', _this._grainAmount);
  58014. effect.setBool('blur_noise', _this._blurNoise);
  58015. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58016. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58017. effect.setFloat('distortion', _this._distortion);
  58018. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  58019. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  58020. effect.setFloat('aperture', _this._dofAperture);
  58021. effect.setFloat('darken', _this._dofDarken);
  58022. effect.setFloat('edge_blur', _this._edgeBlur);
  58023. effect.setBool('highlights', (_this._highlightsGain !== -1));
  58024. if (_this._scene.activeCamera) {
  58025. effect.setFloat('near', _this._scene.activeCamera.minZ);
  58026. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  58027. }
  58028. };
  58029. };
  58030. // creates a black and white random noise texture, 512x512
  58031. LensRenderingPipeline.prototype._createGrainTexture = function () {
  58032. var size = 512;
  58033. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58034. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58035. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58036. var context = this._grainTexture.getContext();
  58037. var rand = function (min, max) {
  58038. return Math.random() * (max - min) + min;
  58039. };
  58040. var value;
  58041. for (var x = 0; x < size; x++) {
  58042. for (var y = 0; y < size; y++) {
  58043. value = Math.floor(rand(0.42, 0.58) * 255);
  58044. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  58045. context.fillRect(x, y, 1, 1);
  58046. }
  58047. }
  58048. this._grainTexture.update(false);
  58049. };
  58050. return LensRenderingPipeline;
  58051. }(BABYLON.PostProcessRenderPipeline));
  58052. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  58053. })(BABYLON || (BABYLON = {}));
  58054. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  58055. var BABYLON;
  58056. (function (BABYLON) {
  58057. var StandardRenderingPipeline = /** @class */ (function (_super) {
  58058. __extends(StandardRenderingPipeline, _super);
  58059. /**
  58060. * @constructor
  58061. * @param {string} name - The rendering pipeline name
  58062. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58063. * @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)
  58064. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  58065. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58066. */
  58067. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  58068. if (originalPostProcess === void 0) { originalPostProcess = null; }
  58069. var _this = _super.call(this, scene.getEngine(), name) || this;
  58070. _this.downSampleX4PostProcess = null;
  58071. _this.brightPassPostProcess = null;
  58072. _this.blurHPostProcesses = [];
  58073. _this.blurVPostProcesses = [];
  58074. _this.textureAdderPostProcess = null;
  58075. _this.volumetricLightPostProcess = null;
  58076. _this.volumetricLightSmoothXPostProcess = null;
  58077. _this.volumetricLightSmoothYPostProcess = null;
  58078. _this.volumetricLightMergePostProces = null;
  58079. _this.volumetricLightFinalPostProcess = null;
  58080. _this.luminancePostProcess = null;
  58081. _this.luminanceDownSamplePostProcesses = [];
  58082. _this.hdrPostProcess = null;
  58083. _this.textureAdderFinalPostProcess = null;
  58084. _this.lensFlareFinalPostProcess = null;
  58085. _this.hdrFinalPostProcess = null;
  58086. _this.lensFlarePostProcess = null;
  58087. _this.lensFlareComposePostProcess = null;
  58088. _this.motionBlurPostProcess = null;
  58089. _this.depthOfFieldPostProcess = null;
  58090. // Values
  58091. _this.brightThreshold = 1.0;
  58092. _this.blurWidth = 512.0;
  58093. _this.horizontalBlur = false;
  58094. _this.exposure = 1.0;
  58095. _this.lensTexture = null;
  58096. _this.volumetricLightCoefficient = 0.2;
  58097. _this.volumetricLightPower = 4.0;
  58098. _this.volumetricLightBlurScale = 64.0;
  58099. _this.sourceLight = null;
  58100. _this.hdrMinimumLuminance = 1.0;
  58101. _this.hdrDecreaseRate = 0.5;
  58102. _this.hdrIncreaseRate = 0.5;
  58103. _this.lensColorTexture = null;
  58104. _this.lensFlareStrength = 20.0;
  58105. _this.lensFlareGhostDispersal = 1.4;
  58106. _this.lensFlareHaloWidth = 0.7;
  58107. _this.lensFlareDistortionStrength = 16.0;
  58108. _this.lensStarTexture = null;
  58109. _this.lensFlareDirtTexture = null;
  58110. _this.depthOfFieldDistance = 10.0;
  58111. _this.depthOfFieldBlurWidth = 64.0;
  58112. _this.motionStrength = 1.0;
  58113. // IAnimatable
  58114. _this.animations = [];
  58115. _this._currentDepthOfFieldSource = null;
  58116. _this._hdrCurrentLuminance = 1.0;
  58117. // Getters and setters
  58118. _this._bloomEnabled = true;
  58119. _this._depthOfFieldEnabled = false;
  58120. _this._vlsEnabled = false;
  58121. _this._lensFlareEnabled = false;
  58122. _this._hdrEnabled = false;
  58123. _this._motionBlurEnabled = false;
  58124. _this._motionBlurSamples = 64.0;
  58125. _this._volumetricLightStepsCount = 50.0;
  58126. _this._cameras = cameras || [];
  58127. // Initialize
  58128. _this._scene = scene;
  58129. _this._basePostProcess = originalPostProcess;
  58130. _this._ratio = ratio;
  58131. // Misc
  58132. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58133. // Finish
  58134. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58135. _this._buildPipeline();
  58136. return _this;
  58137. }
  58138. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  58139. get: function () {
  58140. return this._bloomEnabled;
  58141. },
  58142. set: function (enabled) {
  58143. if (this._bloomEnabled === enabled) {
  58144. return;
  58145. }
  58146. this._bloomEnabled = enabled;
  58147. this._buildPipeline();
  58148. },
  58149. enumerable: true,
  58150. configurable: true
  58151. });
  58152. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  58153. get: function () {
  58154. return this._depthOfFieldEnabled;
  58155. },
  58156. set: function (enabled) {
  58157. if (this._depthOfFieldEnabled === enabled) {
  58158. return;
  58159. }
  58160. this._depthOfFieldEnabled = enabled;
  58161. this._buildPipeline();
  58162. },
  58163. enumerable: true,
  58164. configurable: true
  58165. });
  58166. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  58167. get: function () {
  58168. return this._lensFlareEnabled;
  58169. },
  58170. set: function (enabled) {
  58171. if (this._lensFlareEnabled === enabled) {
  58172. return;
  58173. }
  58174. this._lensFlareEnabled = enabled;
  58175. this._buildPipeline();
  58176. },
  58177. enumerable: true,
  58178. configurable: true
  58179. });
  58180. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  58181. get: function () {
  58182. return this._hdrEnabled;
  58183. },
  58184. set: function (enabled) {
  58185. if (this._hdrEnabled === enabled) {
  58186. return;
  58187. }
  58188. this._hdrEnabled = enabled;
  58189. this._buildPipeline();
  58190. },
  58191. enumerable: true,
  58192. configurable: true
  58193. });
  58194. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  58195. get: function () {
  58196. return this._vlsEnabled;
  58197. },
  58198. set: function (enabled) {
  58199. if (this._vlsEnabled === enabled) {
  58200. return;
  58201. }
  58202. if (enabled) {
  58203. var geometry = this._scene.enableGeometryBufferRenderer();
  58204. if (!geometry) {
  58205. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  58206. return;
  58207. }
  58208. }
  58209. this._vlsEnabled = enabled;
  58210. this._buildPipeline();
  58211. },
  58212. enumerable: true,
  58213. configurable: true
  58214. });
  58215. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  58216. get: function () {
  58217. return this._motionBlurEnabled;
  58218. },
  58219. set: function (enabled) {
  58220. if (this._motionBlurEnabled === enabled) {
  58221. return;
  58222. }
  58223. this._motionBlurEnabled = enabled;
  58224. this._buildPipeline();
  58225. },
  58226. enumerable: true,
  58227. configurable: true
  58228. });
  58229. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  58230. get: function () {
  58231. return this._volumetricLightStepsCount;
  58232. },
  58233. set: function (count) {
  58234. if (this.volumetricLightPostProcess) {
  58235. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  58236. }
  58237. this._volumetricLightStepsCount = count;
  58238. },
  58239. enumerable: true,
  58240. configurable: true
  58241. });
  58242. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  58243. get: function () {
  58244. return this._motionBlurSamples;
  58245. },
  58246. set: function (samples) {
  58247. if (this.motionBlurPostProcess) {
  58248. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  58249. }
  58250. this._motionBlurSamples = samples;
  58251. },
  58252. enumerable: true,
  58253. configurable: true
  58254. });
  58255. StandardRenderingPipeline.prototype._buildPipeline = function () {
  58256. var _this = this;
  58257. var ratio = this._ratio;
  58258. var scene = this._scene;
  58259. this._disposePostProcesses();
  58260. this._reset();
  58261. // Create pass post-process
  58262. if (!this._basePostProcess) {
  58263. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  58264. this.originalPostProcess.onApply = function (effect) {
  58265. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  58266. };
  58267. }
  58268. else {
  58269. this.originalPostProcess = this._basePostProcess;
  58270. }
  58271. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  58272. this._currentDepthOfFieldSource = this.originalPostProcess;
  58273. if (this._vlsEnabled) {
  58274. // Create volumetric light
  58275. this._createVolumetricLightPostProcess(scene, ratio);
  58276. // Create volumetric light final post-process
  58277. 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);
  58278. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  58279. }
  58280. if (this._bloomEnabled) {
  58281. // Create down sample X4 post-process
  58282. this._createDownSampleX4PostProcess(scene, ratio / 2);
  58283. // Create bright pass post-process
  58284. this._createBrightPassPostProcess(scene, ratio / 2);
  58285. // Create gaussian blur post-processes (down sampling blurs)
  58286. this._createBlurPostProcesses(scene, ratio / 4, 1);
  58287. // Create texture adder post-process
  58288. this._createTextureAdderPostProcess(scene, ratio);
  58289. // Create depth-of-field source post-process
  58290. 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);
  58291. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  58292. }
  58293. if (this._lensFlareEnabled) {
  58294. // Create lens flare post-process
  58295. this._createLensFlarePostProcess(scene, ratio);
  58296. // Create depth-of-field source post-process post lens-flare and disable it now
  58297. 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);
  58298. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  58299. }
  58300. if (this._hdrEnabled) {
  58301. // Create luminance
  58302. this._createLuminancePostProcesses(scene, this._floatTextureType);
  58303. // Create HDR
  58304. this._createHdrPostProcess(scene, ratio);
  58305. // Create depth-of-field source post-process post hdr and disable it now
  58306. 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);
  58307. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  58308. }
  58309. if (this._depthOfFieldEnabled) {
  58310. // Create gaussian blur used by depth-of-field
  58311. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  58312. // Create depth-of-field post-process
  58313. this._createDepthOfFieldPostProcess(scene, ratio);
  58314. }
  58315. if (this._motionBlurEnabled) {
  58316. // Create motion blur post-process
  58317. this._createMotionBlurPostProcess(scene, ratio);
  58318. }
  58319. if (this._cameras !== null) {
  58320. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58321. }
  58322. };
  58323. // Down Sample X4 Post-Processs
  58324. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58325. var _this = this;
  58326. var downSampleX4Offsets = new Array(32);
  58327. 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);
  58328. this.downSampleX4PostProcess.onApply = function (effect) {
  58329. var id = 0;
  58330. var width = _this.downSampleX4PostProcess.width;
  58331. var height = _this.downSampleX4PostProcess.height;
  58332. for (var i = -2; i < 2; i++) {
  58333. for (var j = -2; j < 2; j++) {
  58334. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58335. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58336. id += 2;
  58337. }
  58338. }
  58339. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58340. };
  58341. // Add to pipeline
  58342. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58343. };
  58344. // Brightpass Post-Process
  58345. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58346. var _this = this;
  58347. var brightOffsets = new Array(8);
  58348. 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);
  58349. this.brightPassPostProcess.onApply = function (effect) {
  58350. var sU = (1.0 / _this.brightPassPostProcess.width);
  58351. var sV = (1.0 / _this.brightPassPostProcess.height);
  58352. brightOffsets[0] = -0.5 * sU;
  58353. brightOffsets[1] = 0.5 * sV;
  58354. brightOffsets[2] = 0.5 * sU;
  58355. brightOffsets[3] = 0.5 * sV;
  58356. brightOffsets[4] = -0.5 * sU;
  58357. brightOffsets[5] = -0.5 * sV;
  58358. brightOffsets[6] = 0.5 * sU;
  58359. brightOffsets[7] = -0.5 * sV;
  58360. effect.setArray2("dsOffsets", brightOffsets);
  58361. effect.setFloat("brightThreshold", _this.brightThreshold);
  58362. };
  58363. // Add to pipeline
  58364. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58365. };
  58366. // Create blur H&V post-processes
  58367. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58368. var _this = this;
  58369. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58370. var engine = scene.getEngine();
  58371. 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);
  58372. 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);
  58373. blurX.onActivateObservable.add(function () {
  58374. var dw = blurX.width / engine.getRenderWidth();
  58375. blurX.kernel = _this[blurWidthKey] * dw;
  58376. });
  58377. blurY.onActivateObservable.add(function () {
  58378. var dw = blurY.height / engine.getRenderHeight();
  58379. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58380. });
  58381. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58382. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58383. this.blurHPostProcesses.push(blurX);
  58384. this.blurVPostProcesses.push(blurY);
  58385. };
  58386. // Create texture adder post-process
  58387. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58388. var _this = this;
  58389. 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);
  58390. this.textureAdderPostProcess.onApply = function (effect) {
  58391. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58392. effect.setTexture("lensSampler", _this.lensTexture);
  58393. effect.setFloat("exposure", _this.exposure);
  58394. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58395. };
  58396. // Add to pipeline
  58397. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58398. };
  58399. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58400. var _this = this;
  58401. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58402. geometryRenderer.enablePosition = true;
  58403. var geometry = geometryRenderer.getGBuffer();
  58404. // Base post-process
  58405. 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));
  58406. var depthValues = BABYLON.Vector2.Zero();
  58407. this.volumetricLightPostProcess.onApply = function (effect) {
  58408. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  58409. var generator = _this.sourceLight.getShadowGenerator();
  58410. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  58411. effect.setTexture("positionSampler", geometry.textures[2]);
  58412. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  58413. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  58414. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  58415. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  58416. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  58417. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  58418. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  58419. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  58420. effect.setVector2("depthValues", depthValues);
  58421. }
  58422. };
  58423. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  58424. // Smooth
  58425. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  58426. // Merge
  58427. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  58428. this.volumetricLightMergePostProces.onApply = function (effect) {
  58429. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  58430. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  58431. };
  58432. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  58433. };
  58434. // Create luminance
  58435. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  58436. var _this = this;
  58437. // Create luminance
  58438. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  58439. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  58440. var offsets = [];
  58441. this.luminancePostProcess.onApply = function (effect) {
  58442. var sU = (1.0 / _this.luminancePostProcess.width);
  58443. var sV = (1.0 / _this.luminancePostProcess.height);
  58444. offsets[0] = -0.5 * sU;
  58445. offsets[1] = 0.5 * sV;
  58446. offsets[2] = 0.5 * sU;
  58447. offsets[3] = 0.5 * sV;
  58448. offsets[4] = -0.5 * sU;
  58449. offsets[5] = -0.5 * sV;
  58450. offsets[6] = 0.5 * sU;
  58451. offsets[7] = -0.5 * sV;
  58452. effect.setArray2("lumOffsets", offsets);
  58453. };
  58454. // Add to pipeline
  58455. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  58456. // Create down sample luminance
  58457. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  58458. var size = Math.pow(3, i);
  58459. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  58460. if (i === 0) {
  58461. defines += "#define FINAL_DOWN_SAMPLER";
  58462. }
  58463. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  58464. this.luminanceDownSamplePostProcesses.push(postProcess);
  58465. }
  58466. // Create callbacks and add effects
  58467. var lastLuminance = this.luminancePostProcess;
  58468. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  58469. var downSampleOffsets = new Array(18);
  58470. pp.onApply = function (effect) {
  58471. if (!lastLuminance) {
  58472. return;
  58473. }
  58474. var id = 0;
  58475. for (var x = -1; x < 2; x++) {
  58476. for (var y = -1; y < 2; y++) {
  58477. downSampleOffsets[id] = x / lastLuminance.width;
  58478. downSampleOffsets[id + 1] = y / lastLuminance.height;
  58479. id += 2;
  58480. }
  58481. }
  58482. effect.setArray2("dsOffsets", downSampleOffsets);
  58483. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  58484. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58485. lastLuminance = _this.luminancePostProcess;
  58486. }
  58487. else {
  58488. lastLuminance = pp;
  58489. }
  58490. };
  58491. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58492. pp.onAfterRender = function (effect) {
  58493. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  58494. 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);
  58495. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  58496. };
  58497. }
  58498. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  58499. });
  58500. };
  58501. // Create HDR post-process
  58502. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  58503. var _this = this;
  58504. 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);
  58505. var outputLiminance = 1;
  58506. var time = 0;
  58507. var lastTime = 0;
  58508. this.hdrPostProcess.onApply = function (effect) {
  58509. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  58510. time += scene.getEngine().getDeltaTime();
  58511. if (outputLiminance < 0) {
  58512. outputLiminance = _this._hdrCurrentLuminance;
  58513. }
  58514. else {
  58515. var dt = (lastTime - time) / 1000.0;
  58516. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  58517. outputLiminance += _this.hdrDecreaseRate * dt;
  58518. }
  58519. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  58520. outputLiminance -= _this.hdrIncreaseRate * dt;
  58521. }
  58522. else {
  58523. outputLiminance = _this._hdrCurrentLuminance;
  58524. }
  58525. }
  58526. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  58527. effect.setFloat("averageLuminance", outputLiminance);
  58528. lastTime = time;
  58529. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  58530. };
  58531. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  58532. };
  58533. // Create lens flare post-process
  58534. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58535. var _this = this;
  58536. 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);
  58537. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58538. this._createBlurPostProcesses(scene, ratio / 4, 2);
  58539. 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);
  58540. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58541. var resolution = new BABYLON.Vector2(0, 0);
  58542. // Lens flare
  58543. this.lensFlarePostProcess.onApply = function (effect) {
  58544. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  58545. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58546. effect.setFloat("strength", _this.lensFlareStrength);
  58547. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58548. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58549. // Shift
  58550. resolution.x = _this.lensFlarePostProcess.width;
  58551. resolution.y = _this.lensFlarePostProcess.height;
  58552. effect.setVector2("resolution", resolution);
  58553. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58554. };
  58555. // Compose
  58556. 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);
  58557. 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);
  58558. this.lensFlareComposePostProcess.onApply = function (effect) {
  58559. if (!_this._scene.activeCamera) {
  58560. return;
  58561. }
  58562. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58563. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58564. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58565. // Lens start rotation matrix
  58566. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58567. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58568. 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));
  58569. camRot *= 4.0;
  58570. 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);
  58571. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58572. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58573. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  58574. };
  58575. };
  58576. // Create depth-of-field post-process
  58577. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58578. var _this = this;
  58579. 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);
  58580. this.depthOfFieldPostProcess.onApply = function (effect) {
  58581. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58582. effect.setTexture("depthSampler", _this._getDepthTexture());
  58583. effect.setFloat("distance", _this.depthOfFieldDistance);
  58584. };
  58585. // Add to pipeline
  58586. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58587. };
  58588. // Create motion blur post-process
  58589. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  58590. var _this = this;
  58591. 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);
  58592. var motionScale = 0;
  58593. var prevViewProjection = BABYLON.Matrix.Identity();
  58594. var invViewProjection = BABYLON.Matrix.Identity();
  58595. var viewProjection = BABYLON.Matrix.Identity();
  58596. var screenSize = BABYLON.Vector2.Zero();
  58597. this.motionBlurPostProcess.onApply = function (effect) {
  58598. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  58599. viewProjection.invertToRef(invViewProjection);
  58600. effect.setMatrix("inverseViewProjection", invViewProjection);
  58601. effect.setMatrix("prevViewProjection", prevViewProjection);
  58602. prevViewProjection = viewProjection;
  58603. screenSize.x = _this.motionBlurPostProcess.width;
  58604. screenSize.y = _this.motionBlurPostProcess.height;
  58605. effect.setVector2("screenSize", screenSize);
  58606. motionScale = scene.getEngine().getFps() / 60.0;
  58607. effect.setFloat("motionScale", motionScale);
  58608. effect.setFloat("motionStrength", _this.motionStrength);
  58609. effect.setTexture("depthSampler", _this._getDepthTexture());
  58610. };
  58611. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  58612. };
  58613. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  58614. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  58615. var renderer = this._scene.enableGeometryBufferRenderer();
  58616. return renderer.getGBuffer().textures[0];
  58617. }
  58618. return this._scene.enableDepthRenderer().getDepthMap();
  58619. };
  58620. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  58621. for (var i = 0; i < this._cameras.length; i++) {
  58622. var camera = this._cameras[i];
  58623. if (this.originalPostProcess) {
  58624. this.originalPostProcess.dispose(camera);
  58625. }
  58626. if (this.downSampleX4PostProcess) {
  58627. this.downSampleX4PostProcess.dispose(camera);
  58628. }
  58629. if (this.brightPassPostProcess) {
  58630. this.brightPassPostProcess.dispose(camera);
  58631. }
  58632. if (this.textureAdderPostProcess) {
  58633. this.textureAdderPostProcess.dispose(camera);
  58634. }
  58635. if (this.textureAdderFinalPostProcess) {
  58636. this.textureAdderFinalPostProcess.dispose(camera);
  58637. }
  58638. if (this.volumetricLightPostProcess) {
  58639. this.volumetricLightPostProcess.dispose(camera);
  58640. }
  58641. if (this.volumetricLightSmoothXPostProcess) {
  58642. this.volumetricLightSmoothXPostProcess.dispose(camera);
  58643. }
  58644. if (this.volumetricLightSmoothYPostProcess) {
  58645. this.volumetricLightSmoothYPostProcess.dispose(camera);
  58646. }
  58647. if (this.volumetricLightMergePostProces) {
  58648. this.volumetricLightMergePostProces.dispose(camera);
  58649. }
  58650. if (this.volumetricLightFinalPostProcess) {
  58651. this.volumetricLightFinalPostProcess.dispose(camera);
  58652. }
  58653. if (this.lensFlarePostProcess) {
  58654. this.lensFlarePostProcess.dispose(camera);
  58655. }
  58656. if (this.lensFlareComposePostProcess) {
  58657. this.lensFlareComposePostProcess.dispose(camera);
  58658. }
  58659. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  58660. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  58661. }
  58662. if (this.luminancePostProcess) {
  58663. this.luminancePostProcess.dispose(camera);
  58664. }
  58665. if (this.hdrPostProcess) {
  58666. this.hdrPostProcess.dispose(camera);
  58667. }
  58668. if (this.hdrFinalPostProcess) {
  58669. this.hdrFinalPostProcess.dispose(camera);
  58670. }
  58671. if (this.depthOfFieldPostProcess) {
  58672. this.depthOfFieldPostProcess.dispose(camera);
  58673. }
  58674. if (this.motionBlurPostProcess) {
  58675. this.motionBlurPostProcess.dispose(camera);
  58676. }
  58677. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  58678. this.blurHPostProcesses[j].dispose(camera);
  58679. }
  58680. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  58681. this.blurVPostProcesses[j].dispose(camera);
  58682. }
  58683. }
  58684. this.originalPostProcess = null;
  58685. this.downSampleX4PostProcess = null;
  58686. this.brightPassPostProcess = null;
  58687. this.textureAdderPostProcess = null;
  58688. this.textureAdderFinalPostProcess = null;
  58689. this.volumetricLightPostProcess = null;
  58690. this.volumetricLightSmoothXPostProcess = null;
  58691. this.volumetricLightSmoothYPostProcess = null;
  58692. this.volumetricLightMergePostProces = null;
  58693. this.volumetricLightFinalPostProcess = null;
  58694. this.lensFlarePostProcess = null;
  58695. this.lensFlareComposePostProcess = null;
  58696. this.luminancePostProcess = null;
  58697. this.hdrPostProcess = null;
  58698. this.hdrFinalPostProcess = null;
  58699. this.depthOfFieldPostProcess = null;
  58700. this.motionBlurPostProcess = null;
  58701. this.luminanceDownSamplePostProcesses = [];
  58702. this.blurHPostProcesses = [];
  58703. this.blurVPostProcesses = [];
  58704. };
  58705. // Dispose
  58706. StandardRenderingPipeline.prototype.dispose = function () {
  58707. this._disposePostProcesses();
  58708. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58709. _super.prototype.dispose.call(this);
  58710. };
  58711. // Serialize rendering pipeline
  58712. StandardRenderingPipeline.prototype.serialize = function () {
  58713. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58714. serializationObject.customType = "StandardRenderingPipeline";
  58715. return serializationObject;
  58716. };
  58717. /**
  58718. * Static members
  58719. */
  58720. // Parse serialized pipeline
  58721. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58722. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58723. };
  58724. // Luminance steps
  58725. StandardRenderingPipeline.LuminanceSteps = 6;
  58726. __decorate([
  58727. BABYLON.serialize()
  58728. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58729. __decorate([
  58730. BABYLON.serialize()
  58731. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58732. __decorate([
  58733. BABYLON.serialize()
  58734. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58735. __decorate([
  58736. BABYLON.serialize()
  58737. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58738. __decorate([
  58739. BABYLON.serializeAsTexture("lensTexture")
  58740. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58741. __decorate([
  58742. BABYLON.serialize()
  58743. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  58744. __decorate([
  58745. BABYLON.serialize()
  58746. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  58747. __decorate([
  58748. BABYLON.serialize()
  58749. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  58750. __decorate([
  58751. BABYLON.serialize()
  58752. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  58753. __decorate([
  58754. BABYLON.serialize()
  58755. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  58756. __decorate([
  58757. BABYLON.serialize()
  58758. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  58759. __decorate([
  58760. BABYLON.serializeAsTexture("lensColorTexture")
  58761. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  58762. __decorate([
  58763. BABYLON.serialize()
  58764. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  58765. __decorate([
  58766. BABYLON.serialize()
  58767. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  58768. __decorate([
  58769. BABYLON.serialize()
  58770. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  58771. __decorate([
  58772. BABYLON.serialize()
  58773. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  58774. __decorate([
  58775. BABYLON.serializeAsTexture("lensStarTexture")
  58776. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  58777. __decorate([
  58778. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  58779. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  58780. __decorate([
  58781. BABYLON.serialize()
  58782. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  58783. __decorate([
  58784. BABYLON.serialize()
  58785. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  58786. __decorate([
  58787. BABYLON.serialize()
  58788. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  58789. __decorate([
  58790. BABYLON.serialize()
  58791. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  58792. __decorate([
  58793. BABYLON.serialize()
  58794. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  58795. __decorate([
  58796. BABYLON.serialize()
  58797. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  58798. __decorate([
  58799. BABYLON.serialize()
  58800. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  58801. __decorate([
  58802. BABYLON.serialize()
  58803. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  58804. __decorate([
  58805. BABYLON.serialize()
  58806. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  58807. __decorate([
  58808. BABYLON.serialize()
  58809. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  58810. __decorate([
  58811. BABYLON.serialize()
  58812. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  58813. return StandardRenderingPipeline;
  58814. }(BABYLON.PostProcessRenderPipeline));
  58815. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  58816. })(BABYLON || (BABYLON = {}));
  58817. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  58818. var BABYLON;
  58819. (function (BABYLON) {
  58820. var FxaaPostProcess = /** @class */ (function (_super) {
  58821. __extends(FxaaPostProcess, _super);
  58822. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58823. if (camera === void 0) { camera = null; }
  58824. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58825. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  58826. _this.onApplyObservable.add(function (effect) {
  58827. var texelSize = _this.texelSize;
  58828. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  58829. });
  58830. return _this;
  58831. }
  58832. return FxaaPostProcess;
  58833. }(BABYLON.PostProcess));
  58834. BABYLON.FxaaPostProcess = FxaaPostProcess;
  58835. })(BABYLON || (BABYLON = {}));
  58836. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  58837. var BABYLON;
  58838. (function (BABYLON) {
  58839. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  58840. __extends(DefaultRenderingPipeline, _super);
  58841. /**
  58842. * @constructor
  58843. * @param {string} name - The rendering pipeline name
  58844. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58845. * @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)
  58846. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58847. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  58848. */
  58849. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  58850. if (automaticBuild === void 0) { automaticBuild = true; }
  58851. var _this = _super.call(this, scene.getEngine(), name) || this;
  58852. _this.PassPostProcessId = "PassPostProcessEffect";
  58853. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  58854. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  58855. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  58856. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  58857. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  58858. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  58859. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  58860. // IAnimatable
  58861. _this.animations = [];
  58862. // Values
  58863. _this._bloomEnabled = false;
  58864. _this._fxaaEnabled = false;
  58865. _this._imageProcessingEnabled = true;
  58866. _this._bloomScale = 0.6;
  58867. _this._buildAllowed = true;
  58868. /**
  58869. * Specifies the size of the bloom blur kernel, relative to the final output size
  58870. */
  58871. _this.bloomKernel = 64;
  58872. /**
  58873. * Specifies the weight of the bloom in the final rendering
  58874. */
  58875. _this._bloomWeight = 0.15;
  58876. _this._cameras = cameras || [];
  58877. _this._buildAllowed = automaticBuild;
  58878. // Initialize
  58879. _this._scene = scene;
  58880. var caps = _this._scene.getEngine().getCaps();
  58881. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  58882. // Misc
  58883. if (_this._hdr) {
  58884. if (caps.textureHalfFloatRender) {
  58885. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58886. }
  58887. else if (caps.textureFloatRender) {
  58888. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58889. }
  58890. }
  58891. else {
  58892. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58893. }
  58894. // Attach
  58895. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58896. _this._buildPipeline();
  58897. return _this;
  58898. }
  58899. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  58900. get: function () {
  58901. return this._bloomWeight;
  58902. },
  58903. set: function (value) {
  58904. if (this._bloomWeight === value) {
  58905. return;
  58906. }
  58907. this._bloomWeight = value;
  58908. if (this._hdr && this.copyBack) {
  58909. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  58910. }
  58911. },
  58912. enumerable: true,
  58913. configurable: true
  58914. });
  58915. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  58916. get: function () {
  58917. return this._bloomScale;
  58918. },
  58919. set: function (value) {
  58920. if (this._bloomScale === value) {
  58921. return;
  58922. }
  58923. this._bloomScale = value;
  58924. this._buildPipeline();
  58925. },
  58926. enumerable: true,
  58927. configurable: true
  58928. });
  58929. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  58930. get: function () {
  58931. return this._bloomEnabled;
  58932. },
  58933. set: function (enabled) {
  58934. if (this._bloomEnabled === enabled) {
  58935. return;
  58936. }
  58937. this._bloomEnabled = enabled;
  58938. this._buildPipeline();
  58939. },
  58940. enumerable: true,
  58941. configurable: true
  58942. });
  58943. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  58944. get: function () {
  58945. return this._fxaaEnabled;
  58946. },
  58947. set: function (enabled) {
  58948. if (this._fxaaEnabled === enabled) {
  58949. return;
  58950. }
  58951. this._fxaaEnabled = enabled;
  58952. this._buildPipeline();
  58953. },
  58954. enumerable: true,
  58955. configurable: true
  58956. });
  58957. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  58958. get: function () {
  58959. return this._imageProcessingEnabled;
  58960. },
  58961. set: function (enabled) {
  58962. if (this._imageProcessingEnabled === enabled) {
  58963. return;
  58964. }
  58965. this._imageProcessingEnabled = enabled;
  58966. this._buildPipeline();
  58967. },
  58968. enumerable: true,
  58969. configurable: true
  58970. });
  58971. /**
  58972. * Force the compilation of the entire pipeline.
  58973. */
  58974. DefaultRenderingPipeline.prototype.prepare = function () {
  58975. var previousState = this._buildAllowed;
  58976. this._buildAllowed = true;
  58977. this._buildPipeline();
  58978. this._buildAllowed = previousState;
  58979. };
  58980. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  58981. var _this = this;
  58982. if (!this._buildAllowed) {
  58983. return;
  58984. }
  58985. var engine = this._scene.getEngine();
  58986. this._disposePostProcesses();
  58987. this._reset();
  58988. if (this.bloomEnabled) {
  58989. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58990. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  58991. if (!this._hdr) {
  58992. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58993. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  58994. this.highlights.autoClear = false;
  58995. this.highlights.alwaysForcePOT = true;
  58996. }
  58997. 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);
  58998. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  58999. this.blurX.alwaysForcePOT = true;
  59000. this.blurX.autoClear = false;
  59001. this.blurX.onActivateObservable.add(function () {
  59002. var dw = _this.blurX.width / engine.getRenderWidth(true);
  59003. _this.blurX.kernel = _this.bloomKernel * dw;
  59004. });
  59005. 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);
  59006. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  59007. this.blurY.alwaysForcePOT = true;
  59008. this.blurY.autoClear = false;
  59009. this.blurY.onActivateObservable.add(function () {
  59010. var dh = _this.blurY.height / engine.getRenderHeight(true);
  59011. _this.blurY.kernel = _this.bloomKernel * dh;
  59012. });
  59013. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59014. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  59015. this.copyBack.alwaysForcePOT = true;
  59016. if (this._hdr) {
  59017. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  59018. var w = this.bloomWeight;
  59019. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  59020. }
  59021. else {
  59022. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  59023. }
  59024. this.copyBack.autoClear = false;
  59025. }
  59026. if (this._imageProcessingEnabled) {
  59027. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59028. if (this._hdr) {
  59029. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  59030. }
  59031. else {
  59032. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  59033. }
  59034. }
  59035. if (this.fxaaEnabled) {
  59036. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59037. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  59038. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59039. }
  59040. else {
  59041. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59042. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  59043. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59044. }
  59045. if (this.bloomEnabled) {
  59046. if (this._hdr) {
  59047. this.copyBack.shareOutputWith(this.blurX);
  59048. if (this.imageProcessing) {
  59049. this.imageProcessing.shareOutputWith(this.pass);
  59050. this.imageProcessing.autoClear = false;
  59051. }
  59052. else if (this.fxaa) {
  59053. this.fxaa.shareOutputWith(this.pass);
  59054. }
  59055. else {
  59056. this.finalMerge.shareOutputWith(this.pass);
  59057. }
  59058. }
  59059. else {
  59060. if (this.fxaa) {
  59061. this.fxaa.shareOutputWith(this.pass);
  59062. }
  59063. else {
  59064. this.finalMerge.shareOutputWith(this.pass);
  59065. }
  59066. }
  59067. }
  59068. if (this._cameras !== null) {
  59069. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59070. }
  59071. };
  59072. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  59073. for (var i = 0; i < this._cameras.length; i++) {
  59074. var camera = this._cameras[i];
  59075. if (this.pass) {
  59076. this.pass.dispose(camera);
  59077. }
  59078. if (this.highlights) {
  59079. this.highlights.dispose(camera);
  59080. }
  59081. if (this.blurX) {
  59082. this.blurX.dispose(camera);
  59083. }
  59084. if (this.blurY) {
  59085. this.blurY.dispose(camera);
  59086. }
  59087. if (this.copyBack) {
  59088. this.copyBack.dispose(camera);
  59089. }
  59090. if (this.imageProcessing) {
  59091. this.imageProcessing.dispose(camera);
  59092. }
  59093. if (this.fxaa) {
  59094. this.fxaa.dispose(camera);
  59095. }
  59096. if (this.finalMerge) {
  59097. this.finalMerge.dispose(camera);
  59098. }
  59099. }
  59100. this.pass = null;
  59101. this.highlights = null;
  59102. this.blurX = null;
  59103. this.blurY = null;
  59104. this.copyBack = null;
  59105. this.imageProcessing = null;
  59106. this.fxaa = null;
  59107. this.finalMerge = null;
  59108. };
  59109. // Dispose
  59110. DefaultRenderingPipeline.prototype.dispose = function () {
  59111. this._disposePostProcesses();
  59112. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59113. _super.prototype.dispose.call(this);
  59114. };
  59115. // Serialize rendering pipeline
  59116. DefaultRenderingPipeline.prototype.serialize = function () {
  59117. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59118. serializationObject.customType = "DefaultRenderingPipeline";
  59119. return serializationObject;
  59120. };
  59121. // Parse serialized pipeline
  59122. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59123. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  59124. };
  59125. __decorate([
  59126. BABYLON.serialize()
  59127. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  59128. __decorate([
  59129. BABYLON.serialize()
  59130. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  59131. __decorate([
  59132. BABYLON.serialize()
  59133. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  59134. __decorate([
  59135. BABYLON.serialize()
  59136. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  59137. __decorate([
  59138. BABYLON.serialize()
  59139. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  59140. __decorate([
  59141. BABYLON.serialize()
  59142. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  59143. __decorate([
  59144. BABYLON.serialize()
  59145. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  59146. __decorate([
  59147. BABYLON.serialize()
  59148. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  59149. return DefaultRenderingPipeline;
  59150. }(BABYLON.PostProcessRenderPipeline));
  59151. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  59152. })(BABYLON || (BABYLON = {}));
  59153. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  59154. var BABYLON;
  59155. (function (BABYLON) {
  59156. var GeometryBufferRenderer = /** @class */ (function () {
  59157. function GeometryBufferRenderer(scene, ratio) {
  59158. if (ratio === void 0) { ratio = 1; }
  59159. this._enablePosition = false;
  59160. this._scene = scene;
  59161. this._ratio = ratio;
  59162. // Render target
  59163. this._createRenderTargets();
  59164. }
  59165. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  59166. set: function (meshes) {
  59167. this._multiRenderTarget.renderList = meshes;
  59168. },
  59169. enumerable: true,
  59170. configurable: true
  59171. });
  59172. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  59173. get: function () {
  59174. return this._multiRenderTarget.isSupported;
  59175. },
  59176. enumerable: true,
  59177. configurable: true
  59178. });
  59179. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  59180. get: function () {
  59181. return this._enablePosition;
  59182. },
  59183. set: function (enable) {
  59184. this._enablePosition = enable;
  59185. this.dispose();
  59186. this._createRenderTargets();
  59187. },
  59188. enumerable: true,
  59189. configurable: true
  59190. });
  59191. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  59192. var material = subMesh.getMaterial();
  59193. if (material && material.disableDepthWrite) {
  59194. return false;
  59195. }
  59196. var defines = [];
  59197. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59198. var mesh = subMesh.getMesh();
  59199. // Alpha test
  59200. if (material && material.needAlphaTesting()) {
  59201. defines.push("#define ALPHATEST");
  59202. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59203. attribs.push(BABYLON.VertexBuffer.UVKind);
  59204. defines.push("#define UV1");
  59205. }
  59206. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59207. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59208. defines.push("#define UV2");
  59209. }
  59210. }
  59211. // Buffers
  59212. if (this._enablePosition) {
  59213. defines.push("#define POSITION");
  59214. }
  59215. // Bones
  59216. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59217. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59218. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59219. if (mesh.numBoneInfluencers > 4) {
  59220. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59221. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59222. }
  59223. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59224. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59225. }
  59226. else {
  59227. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59228. }
  59229. // Instances
  59230. if (useInstances) {
  59231. defines.push("#define INSTANCES");
  59232. attribs.push("world0");
  59233. attribs.push("world1");
  59234. attribs.push("world2");
  59235. attribs.push("world3");
  59236. }
  59237. // Get correct effect
  59238. var join = defines.join("\n");
  59239. if (this._cachedDefines !== join) {
  59240. this._cachedDefines = join;
  59241. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  59242. }
  59243. return this._effect.isReady();
  59244. };
  59245. GeometryBufferRenderer.prototype.getGBuffer = function () {
  59246. return this._multiRenderTarget;
  59247. };
  59248. // Methods
  59249. GeometryBufferRenderer.prototype.dispose = function () {
  59250. this.getGBuffer().dispose();
  59251. };
  59252. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  59253. var _this = this;
  59254. var engine = this._scene.getEngine();
  59255. var count = this._enablePosition ? 3 : 2;
  59256. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  59257. if (!this.isSupported) {
  59258. return;
  59259. }
  59260. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59261. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59262. this._multiRenderTarget.refreshRate = 1;
  59263. this._multiRenderTarget.renderParticles = false;
  59264. this._multiRenderTarget.renderList = null;
  59265. // set default depth value to 1.0 (far away)
  59266. this._multiRenderTarget.onClearObservable.add(function (engine) {
  59267. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  59268. });
  59269. // Custom render function
  59270. var renderSubMesh = function (subMesh) {
  59271. var mesh = subMesh.getRenderingMesh();
  59272. var scene = _this._scene;
  59273. var engine = scene.getEngine();
  59274. var material = subMesh.getMaterial();
  59275. if (!material) {
  59276. return;
  59277. }
  59278. // Culling
  59279. engine.setState(material.backFaceCulling);
  59280. // Managing instances
  59281. var batch = mesh._getInstancesRenderList(subMesh._id);
  59282. if (batch.mustReturn) {
  59283. return;
  59284. }
  59285. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59286. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59287. engine.enableEffect(_this._effect);
  59288. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59289. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59290. _this._effect.setMatrix("view", scene.getViewMatrix());
  59291. // Alpha test
  59292. if (material && material.needAlphaTesting()) {
  59293. var alphaTexture = material.getAlphaTestTexture();
  59294. if (alphaTexture) {
  59295. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59296. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59297. }
  59298. }
  59299. // Bones
  59300. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59301. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59302. }
  59303. // Draw
  59304. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59305. }
  59306. };
  59307. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59308. var index;
  59309. if (depthOnlySubMeshes.length) {
  59310. engine.setColorWrite(false);
  59311. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59312. renderSubMesh(depthOnlySubMeshes.data[index]);
  59313. }
  59314. engine.setColorWrite(true);
  59315. }
  59316. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59317. renderSubMesh(opaqueSubMeshes.data[index]);
  59318. }
  59319. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59320. renderSubMesh(alphaTestSubMeshes.data[index]);
  59321. }
  59322. };
  59323. };
  59324. return GeometryBufferRenderer;
  59325. }());
  59326. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  59327. })(BABYLON || (BABYLON = {}));
  59328. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59329. var BABYLON;
  59330. (function (BABYLON) {
  59331. var RefractionPostProcess = /** @class */ (function (_super) {
  59332. __extends(RefractionPostProcess, _super);
  59333. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59334. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59335. _this.color = color;
  59336. _this.depth = depth;
  59337. _this.colorLevel = colorLevel;
  59338. _this.onActivateObservable.add(function (cam) {
  59339. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59340. });
  59341. _this.onApplyObservable.add(function (effect) {
  59342. effect.setColor3("baseColor", _this.color);
  59343. effect.setFloat("depth", _this.depth);
  59344. effect.setFloat("colorLevel", _this.colorLevel);
  59345. effect.setTexture("refractionSampler", _this._refRexture);
  59346. });
  59347. return _this;
  59348. }
  59349. // Methods
  59350. RefractionPostProcess.prototype.dispose = function (camera) {
  59351. if (this._refRexture) {
  59352. this._refRexture.dispose();
  59353. }
  59354. _super.prototype.dispose.call(this, camera);
  59355. };
  59356. return RefractionPostProcess;
  59357. }(BABYLON.PostProcess));
  59358. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59359. })(BABYLON || (BABYLON = {}));
  59360. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59361. var BABYLON;
  59362. (function (BABYLON) {
  59363. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59364. __extends(BlackAndWhitePostProcess, _super);
  59365. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59366. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59367. _this.degree = 1;
  59368. _this.onApplyObservable.add(function (effect) {
  59369. effect.setFloat("degree", _this.degree);
  59370. });
  59371. return _this;
  59372. }
  59373. return BlackAndWhitePostProcess;
  59374. }(BABYLON.PostProcess));
  59375. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59376. })(BABYLON || (BABYLON = {}));
  59377. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59378. var BABYLON;
  59379. (function (BABYLON) {
  59380. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59381. __extends(ConvolutionPostProcess, _super);
  59382. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59383. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59384. _this.kernel = kernel;
  59385. _this.onApply = function (effect) {
  59386. effect.setFloat2("screenSize", _this.width, _this.height);
  59387. effect.setArray("kernel", _this.kernel);
  59388. };
  59389. return _this;
  59390. }
  59391. // Statics
  59392. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59393. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59394. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59395. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59396. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59397. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59398. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59399. return ConvolutionPostProcess;
  59400. }(BABYLON.PostProcess));
  59401. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59402. })(BABYLON || (BABYLON = {}));
  59403. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59404. var BABYLON;
  59405. (function (BABYLON) {
  59406. var FilterPostProcess = /** @class */ (function (_super) {
  59407. __extends(FilterPostProcess, _super);
  59408. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  59409. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  59410. _this.kernelMatrix = kernelMatrix;
  59411. _this.onApply = function (effect) {
  59412. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  59413. };
  59414. return _this;
  59415. }
  59416. return FilterPostProcess;
  59417. }(BABYLON.PostProcess));
  59418. BABYLON.FilterPostProcess = FilterPostProcess;
  59419. })(BABYLON || (BABYLON = {}));
  59420. //# sourceMappingURL=babylon.filterPostProcess.js.map
  59421. var BABYLON;
  59422. (function (BABYLON) {
  59423. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  59424. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  59425. __extends(VolumetricLightScatteringPostProcess, _super);
  59426. /**
  59427. * @constructor
  59428. * @param {string} name - The post-process name
  59429. * @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)
  59430. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  59431. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  59432. * @param {number} samples - The post-process quality, default 100
  59433. * @param {number} samplingMode - The post-process filtering mode
  59434. * @param {BABYLON.Engine} engine - The babylon engine
  59435. * @param {boolean} reusable - If the post-process is reusable
  59436. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  59437. */
  59438. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  59439. if (samples === void 0) { samples = 100; }
  59440. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59441. 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;
  59442. _this._screenCoordinates = BABYLON.Vector2.Zero();
  59443. /**
  59444. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  59445. * @type {Vector3}
  59446. */
  59447. _this.customMeshPosition = BABYLON.Vector3.Zero();
  59448. /**
  59449. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  59450. * @type {boolean}
  59451. */
  59452. _this.useCustomMeshPosition = false;
  59453. /**
  59454. * If the post-process should inverse the light scattering direction
  59455. * @type {boolean}
  59456. */
  59457. _this.invert = true;
  59458. /**
  59459. * Array containing the excluded meshes not rendered in the internal pass
  59460. */
  59461. _this.excludedMeshes = new Array();
  59462. /**
  59463. * Controls the overall intensity of the post-process
  59464. * @type {number}
  59465. */
  59466. _this.exposure = 0.3;
  59467. /**
  59468. * Dissipates each sample's contribution in range [0, 1]
  59469. * @type {number}
  59470. */
  59471. _this.decay = 0.96815;
  59472. /**
  59473. * Controls the overall intensity of each sample
  59474. * @type {number}
  59475. */
  59476. _this.weight = 0.58767;
  59477. /**
  59478. * Controls the density of each sample
  59479. * @type {number}
  59480. */
  59481. _this.density = 0.926;
  59482. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  59483. engine = scene.getEngine();
  59484. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59485. // Configure mesh
  59486. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  59487. // Configure
  59488. _this._createPass(scene, ratio.passRatio || ratio);
  59489. _this.onActivate = function (camera) {
  59490. if (!_this.isSupported) {
  59491. _this.dispose(camera);
  59492. }
  59493. _this.onActivate = null;
  59494. };
  59495. _this.onApplyObservable.add(function (effect) {
  59496. _this._updateMeshScreenCoordinates(scene);
  59497. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  59498. effect.setFloat("exposure", _this.exposure);
  59499. effect.setFloat("decay", _this.decay);
  59500. effect.setFloat("weight", _this.weight);
  59501. effect.setFloat("density", _this.density);
  59502. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  59503. });
  59504. return _this;
  59505. }
  59506. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  59507. get: function () {
  59508. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59509. return false;
  59510. },
  59511. set: function (useDiffuseColor) {
  59512. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59513. },
  59514. enumerable: true,
  59515. configurable: true
  59516. });
  59517. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  59518. return "VolumetricLightScatteringPostProcess";
  59519. };
  59520. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  59521. var mesh = subMesh.getMesh();
  59522. // Render this.mesh as default
  59523. if (mesh === this.mesh && mesh.material) {
  59524. return mesh.material.isReady(mesh);
  59525. }
  59526. var defines = [];
  59527. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59528. var material = subMesh.getMaterial();
  59529. // Alpha test
  59530. if (material) {
  59531. if (material.needAlphaTesting()) {
  59532. defines.push("#define ALPHATEST");
  59533. }
  59534. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59535. attribs.push(BABYLON.VertexBuffer.UVKind);
  59536. defines.push("#define UV1");
  59537. }
  59538. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59539. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59540. defines.push("#define UV2");
  59541. }
  59542. }
  59543. // Bones
  59544. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59545. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59546. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59547. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59548. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  59549. }
  59550. else {
  59551. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59552. }
  59553. // Instances
  59554. if (useInstances) {
  59555. defines.push("#define INSTANCES");
  59556. attribs.push("world0");
  59557. attribs.push("world1");
  59558. attribs.push("world2");
  59559. attribs.push("world3");
  59560. }
  59561. // Get correct effect
  59562. var join = defines.join("\n");
  59563. if (this._cachedDefines !== join) {
  59564. this._cachedDefines = join;
  59565. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  59566. }
  59567. return this._volumetricLightScatteringPass.isReady();
  59568. };
  59569. /**
  59570. * Sets the new light position for light scattering effect
  59571. * @param {BABYLON.Vector3} The new custom light position
  59572. */
  59573. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  59574. this.customMeshPosition = position;
  59575. };
  59576. /**
  59577. * Returns the light position for light scattering effect
  59578. * @return {BABYLON.Vector3} The custom light position
  59579. */
  59580. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  59581. return this.customMeshPosition;
  59582. };
  59583. /**
  59584. * Disposes the internal assets and detaches the post-process from the camera
  59585. */
  59586. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  59587. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  59588. if (rttIndex !== -1) {
  59589. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  59590. }
  59591. this._volumetricLightScatteringRTT.dispose();
  59592. _super.prototype.dispose.call(this, camera);
  59593. };
  59594. /**
  59595. * Returns the render target texture used by the post-process
  59596. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  59597. */
  59598. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  59599. return this._volumetricLightScatteringRTT;
  59600. };
  59601. // Private methods
  59602. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  59603. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  59604. return true;
  59605. }
  59606. return false;
  59607. };
  59608. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  59609. var _this = this;
  59610. var engine = scene.getEngine();
  59611. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59612. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59613. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59614. this._volumetricLightScatteringRTT.renderList = null;
  59615. this._volumetricLightScatteringRTT.renderParticles = false;
  59616. var camera = this.getCamera();
  59617. if (camera) {
  59618. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59619. }
  59620. else {
  59621. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59622. }
  59623. // Custom render function for submeshes
  59624. var renderSubMesh = function (subMesh) {
  59625. var mesh = subMesh.getRenderingMesh();
  59626. if (_this._meshExcluded(mesh)) {
  59627. return;
  59628. }
  59629. var material = subMesh.getMaterial();
  59630. if (!material) {
  59631. return;
  59632. }
  59633. var scene = mesh.getScene();
  59634. var engine = scene.getEngine();
  59635. // Culling
  59636. engine.setState(material.backFaceCulling);
  59637. // Managing instances
  59638. var batch = mesh._getInstancesRenderList(subMesh._id);
  59639. if (batch.mustReturn) {
  59640. return;
  59641. }
  59642. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59643. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59644. var effect = _this._volumetricLightScatteringPass;
  59645. if (mesh === _this.mesh) {
  59646. if (subMesh.effect) {
  59647. effect = subMesh.effect;
  59648. }
  59649. else {
  59650. effect = material.getEffect();
  59651. }
  59652. }
  59653. engine.enableEffect(effect);
  59654. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  59655. if (mesh === _this.mesh) {
  59656. material.bind(mesh.getWorldMatrix(), mesh);
  59657. }
  59658. else {
  59659. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  59660. // Alpha test
  59661. if (material && material.needAlphaTesting()) {
  59662. var alphaTexture = material.getAlphaTestTexture();
  59663. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  59664. if (alphaTexture) {
  59665. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59666. }
  59667. }
  59668. // Bones
  59669. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59670. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59671. }
  59672. }
  59673. // Draw
  59674. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  59675. }
  59676. };
  59677. // Render target texture callbacks
  59678. var savedSceneClearColor;
  59679. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  59680. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  59681. savedSceneClearColor = scene.clearColor;
  59682. scene.clearColor = sceneClearColor;
  59683. });
  59684. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  59685. scene.clearColor = savedSceneClearColor;
  59686. });
  59687. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59688. var engine = scene.getEngine();
  59689. var index;
  59690. if (depthOnlySubMeshes.length) {
  59691. engine.setColorWrite(false);
  59692. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59693. renderSubMesh(depthOnlySubMeshes.data[index]);
  59694. }
  59695. engine.setColorWrite(true);
  59696. }
  59697. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59698. renderSubMesh(opaqueSubMeshes.data[index]);
  59699. }
  59700. engine.setAlphaTesting(true);
  59701. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59702. renderSubMesh(alphaTestSubMeshes.data[index]);
  59703. }
  59704. engine.setAlphaTesting(false);
  59705. if (transparentSubMeshes.length) {
  59706. // Sort sub meshes
  59707. for (index = 0; index < transparentSubMeshes.length; index++) {
  59708. var submesh = transparentSubMeshes.data[index];
  59709. var boundingInfo = submesh.getBoundingInfo();
  59710. if (boundingInfo && scene.activeCamera) {
  59711. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  59712. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  59713. }
  59714. }
  59715. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  59716. sortedArray.sort(function (a, b) {
  59717. // Alpha index first
  59718. if (a._alphaIndex > b._alphaIndex) {
  59719. return 1;
  59720. }
  59721. if (a._alphaIndex < b._alphaIndex) {
  59722. return -1;
  59723. }
  59724. // Then distance to camera
  59725. if (a._distanceToCamera < b._distanceToCamera) {
  59726. return 1;
  59727. }
  59728. if (a._distanceToCamera > b._distanceToCamera) {
  59729. return -1;
  59730. }
  59731. return 0;
  59732. });
  59733. // Render sub meshes
  59734. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59735. for (index = 0; index < sortedArray.length; index++) {
  59736. renderSubMesh(sortedArray[index]);
  59737. }
  59738. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59739. }
  59740. };
  59741. };
  59742. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  59743. var transform = scene.getTransformMatrix();
  59744. var meshPosition;
  59745. if (this.useCustomMeshPosition) {
  59746. meshPosition = this.customMeshPosition;
  59747. }
  59748. else if (this.attachedNode) {
  59749. meshPosition = this.attachedNode.position;
  59750. }
  59751. else {
  59752. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  59753. }
  59754. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  59755. this._screenCoordinates.x = pos.x / this._viewPort.width;
  59756. this._screenCoordinates.y = pos.y / this._viewPort.height;
  59757. if (this.invert)
  59758. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  59759. };
  59760. // Static methods
  59761. /**
  59762. * Creates a default mesh for the Volumeric Light Scattering post-process
  59763. * @param {string} The mesh name
  59764. * @param {BABYLON.Scene} The scene where to create the mesh
  59765. * @return {BABYLON.Mesh} the default mesh
  59766. */
  59767. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  59768. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  59769. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59770. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  59771. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  59772. mesh.material = material;
  59773. return mesh;
  59774. };
  59775. __decorate([
  59776. BABYLON.serializeAsVector3()
  59777. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  59778. __decorate([
  59779. BABYLON.serialize()
  59780. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  59781. __decorate([
  59782. BABYLON.serialize()
  59783. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  59784. __decorate([
  59785. BABYLON.serializeAsMeshReference()
  59786. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  59787. __decorate([
  59788. BABYLON.serialize()
  59789. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  59790. __decorate([
  59791. BABYLON.serialize()
  59792. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  59793. __decorate([
  59794. BABYLON.serialize()
  59795. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  59796. __decorate([
  59797. BABYLON.serialize()
  59798. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  59799. __decorate([
  59800. BABYLON.serialize()
  59801. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  59802. return VolumetricLightScatteringPostProcess;
  59803. }(BABYLON.PostProcess));
  59804. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  59805. })(BABYLON || (BABYLON = {}));
  59806. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  59807. //
  59808. // This post-process allows the modification of rendered colors by using
  59809. // a 'look-up table' (LUT). This effect is also called Color Grading.
  59810. //
  59811. // The object needs to be provided an url to a texture containing the color
  59812. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  59813. // Use an image editing software to tweak the LUT to match your needs.
  59814. //
  59815. // For an example of a color LUT, see here:
  59816. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  59817. // For explanations on color grading, see here:
  59818. // http://udn.epicgames.com/Three/ColorGrading.html
  59819. //
  59820. var BABYLON;
  59821. (function (BABYLON) {
  59822. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  59823. __extends(ColorCorrectionPostProcess, _super);
  59824. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  59825. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  59826. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59827. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  59828. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59829. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59830. _this.onApply = function (effect) {
  59831. effect.setTexture("colorTable", _this._colorTableTexture);
  59832. };
  59833. return _this;
  59834. }
  59835. return ColorCorrectionPostProcess;
  59836. }(BABYLON.PostProcess));
  59837. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  59838. })(BABYLON || (BABYLON = {}));
  59839. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  59840. var BABYLON;
  59841. (function (BABYLON) {
  59842. var TonemappingOperator;
  59843. (function (TonemappingOperator) {
  59844. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  59845. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  59846. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  59847. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  59848. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  59849. ;
  59850. var TonemapPostProcess = /** @class */ (function (_super) {
  59851. __extends(TonemapPostProcess, _super);
  59852. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  59853. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59854. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59855. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  59856. _this._operator = _operator;
  59857. _this.exposureAdjustment = exposureAdjustment;
  59858. var defines = "#define ";
  59859. if (_this._operator === TonemappingOperator.Hable)
  59860. defines += "HABLE_TONEMAPPING";
  59861. else if (_this._operator === TonemappingOperator.Reinhard)
  59862. defines += "REINHARD_TONEMAPPING";
  59863. else if (_this._operator === TonemappingOperator.HejiDawson)
  59864. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  59865. else if (_this._operator === TonemappingOperator.Photographic)
  59866. defines += "PHOTOGRAPHIC_TONEMAPPING";
  59867. //sadly a second call to create the effect.
  59868. _this.updateEffect(defines);
  59869. _this.onApply = function (effect) {
  59870. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  59871. };
  59872. return _this;
  59873. }
  59874. return TonemapPostProcess;
  59875. }(BABYLON.PostProcess));
  59876. BABYLON.TonemapPostProcess = TonemapPostProcess;
  59877. })(BABYLON || (BABYLON = {}));
  59878. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  59879. var BABYLON;
  59880. (function (BABYLON) {
  59881. var DisplayPassPostProcess = /** @class */ (function (_super) {
  59882. __extends(DisplayPassPostProcess, _super);
  59883. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  59884. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  59885. }
  59886. return DisplayPassPostProcess;
  59887. }(BABYLON.PostProcess));
  59888. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  59889. })(BABYLON || (BABYLON = {}));
  59890. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  59891. var BABYLON;
  59892. (function (BABYLON) {
  59893. var HighlightsPostProcess = /** @class */ (function (_super) {
  59894. __extends(HighlightsPostProcess, _super);
  59895. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59896. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59897. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  59898. }
  59899. return HighlightsPostProcess;
  59900. }(BABYLON.PostProcess));
  59901. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  59902. })(BABYLON || (BABYLON = {}));
  59903. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  59904. var BABYLON;
  59905. (function (BABYLON) {
  59906. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  59907. __extends(ImageProcessingPostProcess, _super);
  59908. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59909. if (camera === void 0) { camera = null; }
  59910. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59911. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  59912. _this._fromLinearSpace = true;
  59913. /**
  59914. * Defines cache preventing GC.
  59915. */
  59916. _this._defines = {
  59917. IMAGEPROCESSING: false,
  59918. VIGNETTE: false,
  59919. VIGNETTEBLENDMODEMULTIPLY: false,
  59920. VIGNETTEBLENDMODEOPAQUE: false,
  59921. TONEMAPPING: false,
  59922. CONTRAST: false,
  59923. COLORCURVES: false,
  59924. COLORGRADING: false,
  59925. COLORGRADING3D: false,
  59926. FROMLINEARSPACE: false,
  59927. SAMPLER3DGREENDEPTH: false,
  59928. SAMPLER3DBGRMAP: false,
  59929. IMAGEPROCESSINGPOSTPROCESS: false,
  59930. EXPOSURE: false,
  59931. };
  59932. // Setup the default processing configuration to the scene.
  59933. _this._attachImageProcessingConfiguration(null, true);
  59934. _this.imageProcessingConfiguration.applyByPostProcess = true;
  59935. _this.onApply = function (effect) {
  59936. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  59937. };
  59938. return _this;
  59939. }
  59940. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  59941. /**
  59942. * Gets the image processing configuration used either in this material.
  59943. */
  59944. get: function () {
  59945. return this._imageProcessingConfiguration;
  59946. },
  59947. /**
  59948. * Sets the Default image processing configuration used either in the this material.
  59949. *
  59950. * If sets to null, the scene one is in use.
  59951. */
  59952. set: function (value) {
  59953. this._attachImageProcessingConfiguration(value);
  59954. },
  59955. enumerable: true,
  59956. configurable: true
  59957. });
  59958. /**
  59959. * Attaches a new image processing configuration to the PBR Material.
  59960. * @param configuration
  59961. */
  59962. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  59963. var _this = this;
  59964. if (doNotBuild === void 0) { doNotBuild = false; }
  59965. if (configuration === this._imageProcessingConfiguration) {
  59966. return;
  59967. }
  59968. // Detaches observer.
  59969. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59970. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59971. }
  59972. // Pick the scene configuration if needed.
  59973. if (!configuration) {
  59974. var scene = null;
  59975. var engine = this.getEngine();
  59976. var camera = this.getCamera();
  59977. if (camera) {
  59978. scene = camera.getScene();
  59979. }
  59980. else if (engine && engine.scenes) {
  59981. var scenes = engine.scenes;
  59982. scene = scenes[scenes.length - 1];
  59983. }
  59984. else {
  59985. scene = BABYLON.Engine.LastCreatedScene;
  59986. }
  59987. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  59988. }
  59989. else {
  59990. this._imageProcessingConfiguration = configuration;
  59991. }
  59992. // Attaches observer.
  59993. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  59994. _this._updateParameters();
  59995. });
  59996. // Ensure the effect will be rebuilt.
  59997. if (!doNotBuild) {
  59998. this._updateParameters();
  59999. }
  60000. };
  60001. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  60002. /**
  60003. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60004. */
  60005. get: function () {
  60006. return this.imageProcessingConfiguration.colorCurves;
  60007. },
  60008. /**
  60009. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60010. */
  60011. set: function (value) {
  60012. this.imageProcessingConfiguration.colorCurves = value;
  60013. },
  60014. enumerable: true,
  60015. configurable: true
  60016. });
  60017. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  60018. /**
  60019. * Gets wether the color curves effect is enabled.
  60020. */
  60021. get: function () {
  60022. return this.imageProcessingConfiguration.colorCurvesEnabled;
  60023. },
  60024. /**
  60025. * Sets wether the color curves effect is enabled.
  60026. */
  60027. set: function (value) {
  60028. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  60029. },
  60030. enumerable: true,
  60031. configurable: true
  60032. });
  60033. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  60034. /**
  60035. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60036. */
  60037. get: function () {
  60038. return this.imageProcessingConfiguration.colorGradingTexture;
  60039. },
  60040. /**
  60041. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60042. */
  60043. set: function (value) {
  60044. this.imageProcessingConfiguration.colorGradingTexture = value;
  60045. },
  60046. enumerable: true,
  60047. configurable: true
  60048. });
  60049. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  60050. /**
  60051. * Gets wether the color grading effect is enabled.
  60052. */
  60053. get: function () {
  60054. return this.imageProcessingConfiguration.colorGradingEnabled;
  60055. },
  60056. /**
  60057. * Gets wether the color grading effect is enabled.
  60058. */
  60059. set: function (value) {
  60060. this.imageProcessingConfiguration.colorGradingEnabled = value;
  60061. },
  60062. enumerable: true,
  60063. configurable: true
  60064. });
  60065. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  60066. /**
  60067. * Gets exposure used in the effect.
  60068. */
  60069. get: function () {
  60070. return this.imageProcessingConfiguration.exposure;
  60071. },
  60072. /**
  60073. * Sets exposure used in the effect.
  60074. */
  60075. set: function (value) {
  60076. this.imageProcessingConfiguration.exposure = value;
  60077. },
  60078. enumerable: true,
  60079. configurable: true
  60080. });
  60081. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  60082. /**
  60083. * Gets wether tonemapping is enabled or not.
  60084. */
  60085. get: function () {
  60086. return this._imageProcessingConfiguration.toneMappingEnabled;
  60087. },
  60088. /**
  60089. * Sets wether tonemapping is enabled or not
  60090. */
  60091. set: function (value) {
  60092. this._imageProcessingConfiguration.toneMappingEnabled = value;
  60093. },
  60094. enumerable: true,
  60095. configurable: true
  60096. });
  60097. ;
  60098. ;
  60099. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  60100. /**
  60101. * Gets contrast used in the effect.
  60102. */
  60103. get: function () {
  60104. return this.imageProcessingConfiguration.contrast;
  60105. },
  60106. /**
  60107. * Sets contrast used in the effect.
  60108. */
  60109. set: function (value) {
  60110. this.imageProcessingConfiguration.contrast = value;
  60111. },
  60112. enumerable: true,
  60113. configurable: true
  60114. });
  60115. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  60116. /**
  60117. * Gets Vignette stretch size.
  60118. */
  60119. get: function () {
  60120. return this.imageProcessingConfiguration.vignetteStretch;
  60121. },
  60122. /**
  60123. * Sets Vignette stretch size.
  60124. */
  60125. set: function (value) {
  60126. this.imageProcessingConfiguration.vignetteStretch = value;
  60127. },
  60128. enumerable: true,
  60129. configurable: true
  60130. });
  60131. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  60132. /**
  60133. * Gets Vignette centre X Offset.
  60134. */
  60135. get: function () {
  60136. return this.imageProcessingConfiguration.vignetteCentreX;
  60137. },
  60138. /**
  60139. * Sets Vignette centre X Offset.
  60140. */
  60141. set: function (value) {
  60142. this.imageProcessingConfiguration.vignetteCentreX = value;
  60143. },
  60144. enumerable: true,
  60145. configurable: true
  60146. });
  60147. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  60148. /**
  60149. * Gets Vignette centre Y Offset.
  60150. */
  60151. get: function () {
  60152. return this.imageProcessingConfiguration.vignetteCentreY;
  60153. },
  60154. /**
  60155. * Sets Vignette centre Y Offset.
  60156. */
  60157. set: function (value) {
  60158. this.imageProcessingConfiguration.vignetteCentreY = value;
  60159. },
  60160. enumerable: true,
  60161. configurable: true
  60162. });
  60163. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  60164. /**
  60165. * Gets Vignette weight or intensity of the vignette effect.
  60166. */
  60167. get: function () {
  60168. return this.imageProcessingConfiguration.vignetteWeight;
  60169. },
  60170. /**
  60171. * Sets Vignette weight or intensity of the vignette effect.
  60172. */
  60173. set: function (value) {
  60174. this.imageProcessingConfiguration.vignetteWeight = value;
  60175. },
  60176. enumerable: true,
  60177. configurable: true
  60178. });
  60179. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  60180. /**
  60181. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60182. * if vignetteEnabled is set to true.
  60183. */
  60184. get: function () {
  60185. return this.imageProcessingConfiguration.vignetteColor;
  60186. },
  60187. /**
  60188. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60189. * if vignetteEnabled is set to true.
  60190. */
  60191. set: function (value) {
  60192. this.imageProcessingConfiguration.vignetteColor = value;
  60193. },
  60194. enumerable: true,
  60195. configurable: true
  60196. });
  60197. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  60198. /**
  60199. * Gets Camera field of view used by the Vignette effect.
  60200. */
  60201. get: function () {
  60202. return this.imageProcessingConfiguration.vignetteCameraFov;
  60203. },
  60204. /**
  60205. * Sets Camera field of view used by the Vignette effect.
  60206. */
  60207. set: function (value) {
  60208. this.imageProcessingConfiguration.vignetteCameraFov = value;
  60209. },
  60210. enumerable: true,
  60211. configurable: true
  60212. });
  60213. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  60214. /**
  60215. * Gets the vignette blend mode allowing different kind of effect.
  60216. */
  60217. get: function () {
  60218. return this.imageProcessingConfiguration.vignetteBlendMode;
  60219. },
  60220. /**
  60221. * Sets the vignette blend mode allowing different kind of effect.
  60222. */
  60223. set: function (value) {
  60224. this.imageProcessingConfiguration.vignetteBlendMode = value;
  60225. },
  60226. enumerable: true,
  60227. configurable: true
  60228. });
  60229. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  60230. /**
  60231. * Gets wether the vignette effect is enabled.
  60232. */
  60233. get: function () {
  60234. return this.imageProcessingConfiguration.vignetteEnabled;
  60235. },
  60236. /**
  60237. * Sets wether the vignette effect is enabled.
  60238. */
  60239. set: function (value) {
  60240. this.imageProcessingConfiguration.vignetteEnabled = value;
  60241. },
  60242. enumerable: true,
  60243. configurable: true
  60244. });
  60245. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  60246. /**
  60247. * Gets wether the input of the processing is in Gamma or Linear Space.
  60248. */
  60249. get: function () {
  60250. return this._fromLinearSpace;
  60251. },
  60252. /**
  60253. * Sets wether the input of the processing is in Gamma or Linear Space.
  60254. */
  60255. set: function (value) {
  60256. if (this._fromLinearSpace === value) {
  60257. return;
  60258. }
  60259. this._fromLinearSpace = value;
  60260. this._updateParameters();
  60261. },
  60262. enumerable: true,
  60263. configurable: true
  60264. });
  60265. ImageProcessingPostProcess.prototype.getClassName = function () {
  60266. return "ImageProcessingPostProcess";
  60267. };
  60268. ImageProcessingPostProcess.prototype._updateParameters = function () {
  60269. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  60270. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  60271. var defines = "";
  60272. for (var define in this._defines) {
  60273. if (this._defines[define]) {
  60274. defines += "#define " + define + ";\r\n";
  60275. }
  60276. }
  60277. var samplers = ["textureSampler"];
  60278. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  60279. var uniforms = ["scale"];
  60280. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  60281. this.updateEffect(defines, uniforms, samplers);
  60282. };
  60283. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  60284. _super.prototype.dispose.call(this, camera);
  60285. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60286. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60287. }
  60288. this.imageProcessingConfiguration.applyByPostProcess = false;
  60289. };
  60290. __decorate([
  60291. BABYLON.serialize()
  60292. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  60293. return ImageProcessingPostProcess;
  60294. }(BABYLON.PostProcess));
  60295. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  60296. })(BABYLON || (BABYLON = {}));
  60297. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  60298. var BABYLON;
  60299. (function (BABYLON) {
  60300. var BlurPostProcess = /** @class */ (function (_super) {
  60301. __extends(BlurPostProcess, _super);
  60302. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  60303. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60304. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60305. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  60306. _this.direction = direction;
  60307. _this._packedFloat = false;
  60308. _this.onApplyObservable.add(function (effect) {
  60309. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  60310. });
  60311. _this.kernel = kernel;
  60312. return _this;
  60313. }
  60314. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  60315. /**
  60316. * Gets the length in pixels of the blur sample region
  60317. */
  60318. get: function () {
  60319. return this._idealKernel;
  60320. },
  60321. /**
  60322. * Sets the length in pixels of the blur sample region
  60323. */
  60324. set: function (v) {
  60325. if (this._idealKernel === v) {
  60326. return;
  60327. }
  60328. v = Math.max(v, 1);
  60329. this._idealKernel = v;
  60330. this._kernel = this._nearestBestKernel(v);
  60331. this._updateParameters();
  60332. },
  60333. enumerable: true,
  60334. configurable: true
  60335. });
  60336. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60337. /**
  60338. * Gets wether or not the blur is unpacking/repacking floats
  60339. */
  60340. get: function () {
  60341. return this._packedFloat;
  60342. },
  60343. /**
  60344. * Sets wether or not the blur needs to unpack/repack floats
  60345. */
  60346. set: function (v) {
  60347. if (this._packedFloat === v) {
  60348. return;
  60349. }
  60350. this._packedFloat = v;
  60351. this._updateParameters();
  60352. },
  60353. enumerable: true,
  60354. configurable: true
  60355. });
  60356. BlurPostProcess.prototype._updateParameters = function () {
  60357. // Generate sampling offsets and weights
  60358. var N = this._kernel;
  60359. var centerIndex = (N - 1) / 2;
  60360. // Generate Gaussian sampling weights over kernel
  60361. var offsets = [];
  60362. var weights = [];
  60363. var totalWeight = 0;
  60364. for (var i = 0; i < N; i++) {
  60365. var u = i / (N - 1);
  60366. var w = this._gaussianWeight(u * 2.0 - 1);
  60367. offsets[i] = (i - centerIndex);
  60368. weights[i] = w;
  60369. totalWeight += w;
  60370. }
  60371. // Normalize weights
  60372. for (var i = 0; i < weights.length; i++) {
  60373. weights[i] /= totalWeight;
  60374. }
  60375. // Optimize: combine samples to take advantage of hardware linear sampling
  60376. // Walk from left to center, combining pairs (symmetrically)
  60377. var linearSamplingWeights = [];
  60378. var linearSamplingOffsets = [];
  60379. var linearSamplingMap = [];
  60380. for (var i = 0; i <= centerIndex; i += 2) {
  60381. var j = Math.min(i + 1, Math.floor(centerIndex));
  60382. var singleCenterSample = i === j;
  60383. if (singleCenterSample) {
  60384. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60385. }
  60386. else {
  60387. var sharedCell = j === centerIndex;
  60388. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60389. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60390. if (offsetLinear === 0) {
  60391. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60392. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60393. }
  60394. else {
  60395. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60396. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60397. }
  60398. }
  60399. }
  60400. for (var i = 0; i < linearSamplingMap.length; i++) {
  60401. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60402. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60403. }
  60404. // Replace with optimized
  60405. offsets = linearSamplingOffsets;
  60406. weights = linearSamplingWeights;
  60407. // Generate shaders
  60408. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  60409. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  60410. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  60411. var defines = "";
  60412. for (var i = 0; i < varyingCount; i++) {
  60413. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  60414. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  60415. }
  60416. var depCount = 0;
  60417. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  60418. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  60419. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  60420. depCount++;
  60421. }
  60422. if (this.packedFloat) {
  60423. defines += "#define PACKEDFLOAT 1";
  60424. }
  60425. this.updateEffect(defines, null, null, {
  60426. varyingCount: varyingCount,
  60427. depCount: depCount
  60428. });
  60429. };
  60430. /**
  60431. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  60432. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  60433. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  60434. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  60435. * The gaps between physical kernels are compensated for in the weighting of the samples
  60436. * @param idealKernel Ideal blur kernel.
  60437. * @return Nearest best kernel.
  60438. */
  60439. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  60440. var v = Math.round(idealKernel);
  60441. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  60442. var k = _a[_i];
  60443. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  60444. return Math.max(k, 3);
  60445. }
  60446. }
  60447. return Math.max(v, 3);
  60448. };
  60449. /**
  60450. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  60451. * @param x The point on the Gaussian distribution to sample.
  60452. * @return the value of the Gaussian function at x.
  60453. */
  60454. BlurPostProcess.prototype._gaussianWeight = function (x) {
  60455. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  60456. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  60457. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  60458. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  60459. // truncated at around 1.3% of peak strength.
  60460. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  60461. var sigma = (1 / 3);
  60462. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  60463. var exponent = -((x * x) / (2.0 * sigma * sigma));
  60464. var weight = (1.0 / denominator) * Math.exp(exponent);
  60465. return weight;
  60466. };
  60467. /**
  60468. * Generates a string that can be used as a floating point number in GLSL.
  60469. * @param x Value to print.
  60470. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  60471. * @return GLSL float string.
  60472. */
  60473. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  60474. if (decimalFigures === void 0) { decimalFigures = 8; }
  60475. return x.toFixed(decimalFigures).replace(/0+$/, '');
  60476. };
  60477. return BlurPostProcess;
  60478. }(BABYLON.PostProcess));
  60479. BABYLON.BlurPostProcess = BlurPostProcess;
  60480. })(BABYLON || (BABYLON = {}));
  60481. //# sourceMappingURL=babylon.blurPostProcess.js.map
  60482. var BABYLON;
  60483. (function (BABYLON) {
  60484. var Bone = /** @class */ (function (_super) {
  60485. __extends(Bone, _super);
  60486. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  60487. if (parentBone === void 0) { parentBone = null; }
  60488. if (localMatrix === void 0) { localMatrix = null; }
  60489. if (restPose === void 0) { restPose = null; }
  60490. if (baseMatrix === void 0) { baseMatrix = null; }
  60491. if (index === void 0) { index = null; }
  60492. var _this = _super.call(this, name, skeleton.getScene()) || this;
  60493. _this.name = name;
  60494. _this.children = new Array();
  60495. _this.animations = new Array();
  60496. // Set this value to map this bone to a different index in the transform matrices.
  60497. // Set this value to -1 to exclude the bone from the transform matrices.
  60498. _this._index = null;
  60499. _this._worldTransform = new BABYLON.Matrix();
  60500. _this._absoluteTransform = new BABYLON.Matrix();
  60501. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  60502. _this._scaleMatrix = BABYLON.Matrix.Identity();
  60503. _this._scaleVector = BABYLON.Vector3.One();
  60504. _this._negateScaleChildren = BABYLON.Vector3.One();
  60505. _this._scalingDeterminant = 1;
  60506. _this._skeleton = skeleton;
  60507. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  60508. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  60509. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  60510. _this._index = index;
  60511. skeleton.bones.push(_this);
  60512. _this.setParent(parentBone, false);
  60513. _this._updateDifferenceMatrix();
  60514. return _this;
  60515. }
  60516. Object.defineProperty(Bone.prototype, "_matrix", {
  60517. get: function () {
  60518. return this._localMatrix;
  60519. },
  60520. set: function (val) {
  60521. if (this._localMatrix) {
  60522. this._localMatrix.copyFrom(val);
  60523. }
  60524. else {
  60525. this._localMatrix = val;
  60526. }
  60527. },
  60528. enumerable: true,
  60529. configurable: true
  60530. });
  60531. // Members
  60532. Bone.prototype.getSkeleton = function () {
  60533. return this._skeleton;
  60534. };
  60535. Bone.prototype.getParent = function () {
  60536. return this._parent;
  60537. };
  60538. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  60539. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60540. if (this._parent === parent) {
  60541. return;
  60542. }
  60543. if (this._parent) {
  60544. var index = this._parent.children.indexOf(this);
  60545. if (index !== -1) {
  60546. this._parent.children.splice(index, 1);
  60547. }
  60548. }
  60549. this._parent = parent;
  60550. if (this._parent) {
  60551. this._parent.children.push(this);
  60552. }
  60553. if (updateDifferenceMatrix) {
  60554. this._updateDifferenceMatrix();
  60555. }
  60556. };
  60557. Bone.prototype.getLocalMatrix = function () {
  60558. return this._localMatrix;
  60559. };
  60560. Bone.prototype.getBaseMatrix = function () {
  60561. return this._baseMatrix;
  60562. };
  60563. Bone.prototype.getRestPose = function () {
  60564. return this._restPose;
  60565. };
  60566. Bone.prototype.returnToRest = function () {
  60567. this.updateMatrix(this._restPose.clone());
  60568. };
  60569. Bone.prototype.getWorldMatrix = function () {
  60570. return this._worldTransform;
  60571. };
  60572. Bone.prototype.getInvertedAbsoluteTransform = function () {
  60573. return this._invertedAbsoluteTransform;
  60574. };
  60575. Bone.prototype.getAbsoluteTransform = function () {
  60576. return this._absoluteTransform;
  60577. };
  60578. Object.defineProperty(Bone.prototype, "position", {
  60579. // Properties (matches AbstractMesh properties)
  60580. get: function () {
  60581. return this.getPosition();
  60582. },
  60583. set: function (newPosition) {
  60584. this.setPosition(newPosition);
  60585. },
  60586. enumerable: true,
  60587. configurable: true
  60588. });
  60589. Object.defineProperty(Bone.prototype, "rotation", {
  60590. get: function () {
  60591. return this.getRotation();
  60592. },
  60593. set: function (newRotation) {
  60594. this.setRotation(newRotation);
  60595. },
  60596. enumerable: true,
  60597. configurable: true
  60598. });
  60599. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  60600. get: function () {
  60601. return this.getRotationQuaternion();
  60602. },
  60603. set: function (newRotation) {
  60604. this.setRotationQuaternion(newRotation);
  60605. },
  60606. enumerable: true,
  60607. configurable: true
  60608. });
  60609. Object.defineProperty(Bone.prototype, "scaling", {
  60610. get: function () {
  60611. return this.getScale();
  60612. },
  60613. set: function (newScaling) {
  60614. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  60615. },
  60616. enumerable: true,
  60617. configurable: true
  60618. });
  60619. // Methods
  60620. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  60621. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60622. this._baseMatrix = matrix.clone();
  60623. this._localMatrix = matrix.clone();
  60624. this._skeleton._markAsDirty();
  60625. if (updateDifferenceMatrix) {
  60626. this._updateDifferenceMatrix();
  60627. }
  60628. };
  60629. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  60630. if (!rootMatrix) {
  60631. rootMatrix = this._baseMatrix;
  60632. }
  60633. if (this._parent) {
  60634. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60635. }
  60636. else {
  60637. this._absoluteTransform.copyFrom(rootMatrix);
  60638. }
  60639. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  60640. for (var index = 0; index < this.children.length; index++) {
  60641. this.children[index]._updateDifferenceMatrix();
  60642. }
  60643. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  60644. };
  60645. Bone.prototype.markAsDirty = function () {
  60646. this._currentRenderId++;
  60647. this._skeleton._markAsDirty();
  60648. };
  60649. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  60650. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60651. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  60652. // all animation may be coming from a library skeleton, so may need to create animation
  60653. if (this.animations.length === 0) {
  60654. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  60655. this.animations[0].setKeys([]);
  60656. }
  60657. // get animation info / verify there is such a range from the source bone
  60658. var sourceRange = source.animations[0].getRange(rangeName);
  60659. if (!sourceRange) {
  60660. return false;
  60661. }
  60662. var from = sourceRange.from;
  60663. var to = sourceRange.to;
  60664. var sourceKeys = source.animations[0].getKeys();
  60665. // rescaling prep
  60666. var sourceBoneLength = source.length;
  60667. var sourceParent = source.getParent();
  60668. var parent = this.getParent();
  60669. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  60670. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  60671. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  60672. var destKeys = this.animations[0].getKeys();
  60673. // loop vars declaration
  60674. var orig;
  60675. var origTranslation;
  60676. var mat;
  60677. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  60678. orig = sourceKeys[key];
  60679. if (orig.frame >= from && orig.frame <= to) {
  60680. if (rescaleAsRequired) {
  60681. mat = orig.value.clone();
  60682. // scale based on parent ratio, when bone has parent
  60683. if (parentScalingReqd) {
  60684. origTranslation = mat.getTranslation();
  60685. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  60686. // scale based on skeleton dimension ratio when root bone, and value is passed
  60687. }
  60688. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  60689. origTranslation = mat.getTranslation();
  60690. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  60691. // use original when root bone, and no data for skelDimensionsRatio
  60692. }
  60693. else {
  60694. mat = orig.value;
  60695. }
  60696. }
  60697. else {
  60698. mat = orig.value;
  60699. }
  60700. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  60701. }
  60702. }
  60703. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  60704. return true;
  60705. };
  60706. /**
  60707. * Translate the bone in local or world space.
  60708. * @param vec The amount to translate the bone.
  60709. * @param space The space that the translation is in.
  60710. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60711. */
  60712. Bone.prototype.translate = function (vec, space, mesh) {
  60713. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60714. var lm = this.getLocalMatrix();
  60715. if (space == BABYLON.Space.LOCAL) {
  60716. lm.m[12] += vec.x;
  60717. lm.m[13] += vec.y;
  60718. lm.m[14] += vec.z;
  60719. }
  60720. else {
  60721. var wm = null;
  60722. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60723. if (mesh) {
  60724. wm = mesh.getWorldMatrix();
  60725. }
  60726. this._skeleton.computeAbsoluteTransforms();
  60727. var tmat = Bone._tmpMats[0];
  60728. var tvec = Bone._tmpVecs[0];
  60729. if (this._parent) {
  60730. if (mesh && wm) {
  60731. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60732. tmat.multiplyToRef(wm, tmat);
  60733. }
  60734. else {
  60735. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60736. }
  60737. }
  60738. tmat.m[12] = 0;
  60739. tmat.m[13] = 0;
  60740. tmat.m[14] = 0;
  60741. tmat.invert();
  60742. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  60743. lm.m[12] += tvec.x;
  60744. lm.m[13] += tvec.y;
  60745. lm.m[14] += tvec.z;
  60746. }
  60747. this.markAsDirty();
  60748. };
  60749. /**
  60750. * Set the postion of the bone in local or world space.
  60751. * @param position The position to set the bone.
  60752. * @param space The space that the position is in.
  60753. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60754. */
  60755. Bone.prototype.setPosition = function (position, space, mesh) {
  60756. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60757. var lm = this.getLocalMatrix();
  60758. if (space == BABYLON.Space.LOCAL) {
  60759. lm.m[12] = position.x;
  60760. lm.m[13] = position.y;
  60761. lm.m[14] = position.z;
  60762. }
  60763. else {
  60764. var wm = null;
  60765. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60766. if (mesh) {
  60767. wm = mesh.getWorldMatrix();
  60768. }
  60769. this._skeleton.computeAbsoluteTransforms();
  60770. var tmat = Bone._tmpMats[0];
  60771. var vec = Bone._tmpVecs[0];
  60772. if (this._parent) {
  60773. if (mesh && wm) {
  60774. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60775. tmat.multiplyToRef(wm, tmat);
  60776. }
  60777. else {
  60778. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60779. }
  60780. }
  60781. tmat.invert();
  60782. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  60783. lm.m[12] = vec.x;
  60784. lm.m[13] = vec.y;
  60785. lm.m[14] = vec.z;
  60786. }
  60787. this.markAsDirty();
  60788. };
  60789. /**
  60790. * Set the absolute postion of the bone (world space).
  60791. * @param position The position to set the bone.
  60792. * @param mesh The mesh that this bone is attached to.
  60793. */
  60794. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  60795. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  60796. };
  60797. /**
  60798. * Set the scale of the bone on the x, y and z axes.
  60799. * @param x The scale of the bone on the x axis.
  60800. * @param x The scale of the bone on the y axis.
  60801. * @param z The scale of the bone on the z axis.
  60802. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60803. */
  60804. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  60805. if (scaleChildren === void 0) { scaleChildren = false; }
  60806. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  60807. if (!scaleChildren) {
  60808. this._negateScaleChildren.x = 1 / x;
  60809. this._negateScaleChildren.y = 1 / y;
  60810. this._negateScaleChildren.z = 1 / z;
  60811. }
  60812. this._syncScaleVector();
  60813. }
  60814. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  60815. };
  60816. /**
  60817. * Scale the bone on the x, y and z axes.
  60818. * @param x The amount to scale the bone on the x axis.
  60819. * @param x The amount to scale the bone on the y axis.
  60820. * @param z The amount to scale the bone on the z axis.
  60821. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60822. */
  60823. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  60824. if (scaleChildren === void 0) { scaleChildren = false; }
  60825. var locMat = this.getLocalMatrix();
  60826. var origLocMat = Bone._tmpMats[0];
  60827. origLocMat.copyFrom(locMat);
  60828. var origLocMatInv = Bone._tmpMats[1];
  60829. origLocMatInv.copyFrom(origLocMat);
  60830. origLocMatInv.invert();
  60831. var scaleMat = Bone._tmpMats[2];
  60832. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  60833. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  60834. this._scaleVector.x *= x;
  60835. this._scaleVector.y *= y;
  60836. this._scaleVector.z *= z;
  60837. locMat.multiplyToRef(origLocMatInv, locMat);
  60838. locMat.multiplyToRef(scaleMat, locMat);
  60839. locMat.multiplyToRef(origLocMat, locMat);
  60840. var parent = this.getParent();
  60841. if (parent) {
  60842. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  60843. }
  60844. else {
  60845. this.getAbsoluteTransform().copyFrom(locMat);
  60846. }
  60847. var len = this.children.length;
  60848. scaleMat.invert();
  60849. for (var i = 0; i < len; i++) {
  60850. var child = this.children[i];
  60851. var cm = child.getLocalMatrix();
  60852. cm.multiplyToRef(scaleMat, cm);
  60853. var lm = child.getLocalMatrix();
  60854. lm.m[12] *= x;
  60855. lm.m[13] *= y;
  60856. lm.m[14] *= z;
  60857. }
  60858. this.computeAbsoluteTransforms();
  60859. if (scaleChildren) {
  60860. for (var i = 0; i < len; i++) {
  60861. this.children[i].scale(x, y, z, scaleChildren);
  60862. }
  60863. }
  60864. this.markAsDirty();
  60865. };
  60866. /**
  60867. * Set the yaw, pitch, and roll of the bone in local or world space.
  60868. * @param yaw The rotation of the bone on the y axis.
  60869. * @param pitch The rotation of the bone on the x axis.
  60870. * @param roll The rotation of the bone on the z axis.
  60871. * @param space The space that the axes of rotation are in.
  60872. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60873. */
  60874. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  60875. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60876. var rotMat = Bone._tmpMats[0];
  60877. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  60878. var rotMatInv = Bone._tmpMats[1];
  60879. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60880. rotMatInv.multiplyToRef(rotMat, rotMat);
  60881. this._rotateWithMatrix(rotMat, space, mesh);
  60882. };
  60883. /**
  60884. * Rotate the bone on an axis in local or world space.
  60885. * @param axis The axis to rotate the bone on.
  60886. * @param amount The amount to rotate the bone.
  60887. * @param space The space that the axis is in.
  60888. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60889. */
  60890. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  60891. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60892. var rmat = Bone._tmpMats[0];
  60893. rmat.m[12] = 0;
  60894. rmat.m[13] = 0;
  60895. rmat.m[14] = 0;
  60896. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  60897. this._rotateWithMatrix(rmat, space, mesh);
  60898. };
  60899. /**
  60900. * Set the rotation of the bone to a particular axis angle in local or world space.
  60901. * @param axis The axis to rotate the bone on.
  60902. * @param angle The angle that the bone should be rotated to.
  60903. * @param space The space that the axis is in.
  60904. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60905. */
  60906. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  60907. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60908. var rotMat = Bone._tmpMats[0];
  60909. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  60910. var rotMatInv = Bone._tmpMats[1];
  60911. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60912. rotMatInv.multiplyToRef(rotMat, rotMat);
  60913. this._rotateWithMatrix(rotMat, space, mesh);
  60914. };
  60915. /**
  60916. * Set the euler rotation of the bone in local of world space.
  60917. * @param rotation The euler rotation that the bone should be set to.
  60918. * @param space The space that the rotation is in.
  60919. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60920. */
  60921. Bone.prototype.setRotation = function (rotation, space, mesh) {
  60922. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60923. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  60924. };
  60925. /**
  60926. * Set the quaternion rotation of the bone in local of world space.
  60927. * @param quat The quaternion rotation that the bone should be set to.
  60928. * @param space The space that the rotation is in.
  60929. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60930. */
  60931. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  60932. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60933. var rotMatInv = Bone._tmpMats[0];
  60934. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60935. var rotMat = Bone._tmpMats[1];
  60936. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  60937. rotMatInv.multiplyToRef(rotMat, rotMat);
  60938. this._rotateWithMatrix(rotMat, space, mesh);
  60939. };
  60940. /**
  60941. * Set the rotation matrix of the bone in local of world space.
  60942. * @param rotMat The rotation matrix that the bone should be set to.
  60943. * @param space The space that the rotation is in.
  60944. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60945. */
  60946. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  60947. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60948. var rotMatInv = Bone._tmpMats[0];
  60949. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60950. var rotMat2 = Bone._tmpMats[1];
  60951. rotMat2.copyFrom(rotMat);
  60952. rotMatInv.multiplyToRef(rotMat, rotMat2);
  60953. this._rotateWithMatrix(rotMat2, space, mesh);
  60954. };
  60955. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  60956. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60957. var lmat = this.getLocalMatrix();
  60958. var lx = lmat.m[12];
  60959. var ly = lmat.m[13];
  60960. var lz = lmat.m[14];
  60961. var parent = this.getParent();
  60962. var parentScale = Bone._tmpMats[3];
  60963. var parentScaleInv = Bone._tmpMats[4];
  60964. if (parent) {
  60965. if (space == BABYLON.Space.WORLD) {
  60966. if (mesh) {
  60967. parentScale.copyFrom(mesh.getWorldMatrix());
  60968. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  60969. }
  60970. else {
  60971. parentScale.copyFrom(parent.getAbsoluteTransform());
  60972. }
  60973. }
  60974. else {
  60975. parentScale = parent._scaleMatrix;
  60976. }
  60977. parentScaleInv.copyFrom(parentScale);
  60978. parentScaleInv.invert();
  60979. lmat.multiplyToRef(parentScale, lmat);
  60980. lmat.multiplyToRef(rmat, lmat);
  60981. lmat.multiplyToRef(parentScaleInv, lmat);
  60982. }
  60983. else {
  60984. if (space == BABYLON.Space.WORLD && mesh) {
  60985. parentScale.copyFrom(mesh.getWorldMatrix());
  60986. parentScaleInv.copyFrom(parentScale);
  60987. parentScaleInv.invert();
  60988. lmat.multiplyToRef(parentScale, lmat);
  60989. lmat.multiplyToRef(rmat, lmat);
  60990. lmat.multiplyToRef(parentScaleInv, lmat);
  60991. }
  60992. else {
  60993. lmat.multiplyToRef(rmat, lmat);
  60994. }
  60995. }
  60996. lmat.m[12] = lx;
  60997. lmat.m[13] = ly;
  60998. lmat.m[14] = lz;
  60999. this.computeAbsoluteTransforms();
  61000. this.markAsDirty();
  61001. };
  61002. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  61003. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61004. if (space == BABYLON.Space.WORLD) {
  61005. var scaleMatrix = Bone._tmpMats[2];
  61006. scaleMatrix.copyFrom(this._scaleMatrix);
  61007. rotMatInv.copyFrom(this.getAbsoluteTransform());
  61008. if (mesh) {
  61009. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  61010. var meshScale = Bone._tmpMats[3];
  61011. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  61012. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  61013. }
  61014. rotMatInv.invert();
  61015. scaleMatrix.m[0] *= this._scalingDeterminant;
  61016. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61017. }
  61018. else {
  61019. rotMatInv.copyFrom(this.getLocalMatrix());
  61020. rotMatInv.invert();
  61021. var scaleMatrix = Bone._tmpMats[2];
  61022. scaleMatrix.copyFrom(this._scaleMatrix);
  61023. if (this._parent) {
  61024. var pscaleMatrix = Bone._tmpMats[3];
  61025. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  61026. pscaleMatrix.invert();
  61027. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  61028. }
  61029. else {
  61030. scaleMatrix.m[0] *= this._scalingDeterminant;
  61031. }
  61032. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61033. }
  61034. };
  61035. /**
  61036. * Get the scale of the bone
  61037. * @returns the scale of the bone
  61038. */
  61039. Bone.prototype.getScale = function () {
  61040. return this._scaleVector.clone();
  61041. };
  61042. /**
  61043. * Copy the scale of the bone to a vector3.
  61044. * @param result The vector3 to copy the scale to
  61045. */
  61046. Bone.prototype.getScaleToRef = function (result) {
  61047. result.copyFrom(this._scaleVector);
  61048. };
  61049. /**
  61050. * Get the position of the bone in local or world space.
  61051. * @param space The space that the returned position is in.
  61052. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61053. * @returns The position of the bone
  61054. */
  61055. Bone.prototype.getPosition = function (space, mesh) {
  61056. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61057. if (mesh === void 0) { mesh = null; }
  61058. var pos = BABYLON.Vector3.Zero();
  61059. this.getPositionToRef(space, mesh, pos);
  61060. return pos;
  61061. };
  61062. /**
  61063. * Copy the position of the bone to a vector3 in local or world space.
  61064. * @param space The space that the returned position is in.
  61065. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61066. * @param result The vector3 to copy the position to.
  61067. */
  61068. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  61069. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61070. if (space == BABYLON.Space.LOCAL) {
  61071. var lm = this.getLocalMatrix();
  61072. result.x = lm.m[12];
  61073. result.y = lm.m[13];
  61074. result.z = lm.m[14];
  61075. }
  61076. else {
  61077. var wm = null;
  61078. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61079. if (mesh) {
  61080. wm = mesh.getWorldMatrix();
  61081. }
  61082. this._skeleton.computeAbsoluteTransforms();
  61083. var tmat = Bone._tmpMats[0];
  61084. if (mesh && wm) {
  61085. tmat.copyFrom(this.getAbsoluteTransform());
  61086. tmat.multiplyToRef(wm, tmat);
  61087. }
  61088. else {
  61089. tmat = this.getAbsoluteTransform();
  61090. }
  61091. result.x = tmat.m[12];
  61092. result.y = tmat.m[13];
  61093. result.z = tmat.m[14];
  61094. }
  61095. };
  61096. /**
  61097. * Get the absolute position of the bone (world space).
  61098. * @param mesh The mesh that this bone is attached to.
  61099. * @returns The absolute position of the bone
  61100. */
  61101. Bone.prototype.getAbsolutePosition = function (mesh) {
  61102. if (mesh === void 0) { mesh = null; }
  61103. var pos = BABYLON.Vector3.Zero();
  61104. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  61105. return pos;
  61106. };
  61107. /**
  61108. * Copy the absolute position of the bone (world space) to the result param.
  61109. * @param mesh The mesh that this bone is attached to.
  61110. * @param result The vector3 to copy the absolute position to.
  61111. */
  61112. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  61113. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  61114. };
  61115. /**
  61116. * Compute the absolute transforms of this bone and its children.
  61117. */
  61118. Bone.prototype.computeAbsoluteTransforms = function () {
  61119. if (this._parent) {
  61120. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61121. }
  61122. else {
  61123. this._absoluteTransform.copyFrom(this._localMatrix);
  61124. var poseMatrix = this._skeleton.getPoseMatrix();
  61125. if (poseMatrix) {
  61126. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  61127. }
  61128. }
  61129. var children = this.children;
  61130. var len = children.length;
  61131. for (var i = 0; i < len; i++) {
  61132. children[i].computeAbsoluteTransforms();
  61133. }
  61134. };
  61135. Bone.prototype._syncScaleVector = function () {
  61136. var lm = this.getLocalMatrix();
  61137. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  61138. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  61139. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  61140. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  61141. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  61142. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  61143. this._scaleVector.x = xs * Math.sqrt(xsq);
  61144. this._scaleVector.y = ys * Math.sqrt(ysq);
  61145. this._scaleVector.z = zs * Math.sqrt(zsq);
  61146. if (this._parent) {
  61147. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  61148. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  61149. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  61150. }
  61151. 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);
  61152. };
  61153. /**
  61154. * Get the world direction from an axis that is in the local space of the bone.
  61155. * @param localAxis The local direction that is used to compute the world direction.
  61156. * @param mesh The mesh that this bone is attached to.
  61157. * @returns The world direction
  61158. */
  61159. Bone.prototype.getDirection = function (localAxis, mesh) {
  61160. if (mesh === void 0) { mesh = null; }
  61161. var result = BABYLON.Vector3.Zero();
  61162. this.getDirectionToRef(localAxis, mesh, result);
  61163. return result;
  61164. };
  61165. /**
  61166. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  61167. * @param localAxis The local direction that is used to compute the world direction.
  61168. * @param mesh The mesh that this bone is attached to.
  61169. * @param result The vector3 that the world direction will be copied to.
  61170. */
  61171. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  61172. if (mesh === void 0) { mesh = null; }
  61173. var wm = null;
  61174. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61175. if (mesh) {
  61176. wm = mesh.getWorldMatrix();
  61177. }
  61178. this._skeleton.computeAbsoluteTransforms();
  61179. var mat = Bone._tmpMats[0];
  61180. mat.copyFrom(this.getAbsoluteTransform());
  61181. if (mesh && wm) {
  61182. mat.multiplyToRef(wm, mat);
  61183. }
  61184. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  61185. result.normalize();
  61186. };
  61187. /**
  61188. * Get the euler rotation of the bone in local or world space.
  61189. * @param space The space that the rotation should be in.
  61190. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61191. * @returns The euler rotation
  61192. */
  61193. Bone.prototype.getRotation = function (space, mesh) {
  61194. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61195. if (mesh === void 0) { mesh = null; }
  61196. var result = BABYLON.Vector3.Zero();
  61197. this.getRotationToRef(space, mesh, result);
  61198. return result;
  61199. };
  61200. /**
  61201. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  61202. * @param space The space that the rotation should be in.
  61203. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61204. * @param result The vector3 that the rotation should be copied to.
  61205. */
  61206. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  61207. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61208. if (mesh === void 0) { mesh = null; }
  61209. var quat = Bone._tmpQuat;
  61210. this.getRotationQuaternionToRef(space, mesh, quat);
  61211. quat.toEulerAnglesToRef(result);
  61212. };
  61213. /**
  61214. * Get the quaternion rotation of the bone in either local or world space.
  61215. * @param space The space that the rotation should be in.
  61216. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61217. * @returns The quaternion rotation
  61218. */
  61219. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  61220. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61221. if (mesh === void 0) { mesh = null; }
  61222. var result = BABYLON.Quaternion.Identity();
  61223. this.getRotationQuaternionToRef(space, mesh, result);
  61224. return result;
  61225. };
  61226. /**
  61227. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  61228. * @param space The space that the rotation should be in.
  61229. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61230. * @param result The quaternion that the rotation should be copied to.
  61231. */
  61232. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  61233. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61234. if (mesh === void 0) { mesh = null; }
  61235. if (space == BABYLON.Space.LOCAL) {
  61236. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61237. }
  61238. else {
  61239. var mat = Bone._tmpMats[0];
  61240. var amat = this.getAbsoluteTransform();
  61241. if (mesh) {
  61242. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61243. }
  61244. else {
  61245. mat.copyFrom(amat);
  61246. }
  61247. mat.m[0] *= this._scalingDeterminant;
  61248. mat.m[1] *= this._scalingDeterminant;
  61249. mat.m[2] *= this._scalingDeterminant;
  61250. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61251. }
  61252. };
  61253. /**
  61254. * Get the rotation matrix of the bone in local or world space.
  61255. * @param space The space that the rotation should be in.
  61256. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61257. * @returns The rotation matrix
  61258. */
  61259. Bone.prototype.getRotationMatrix = function (space, mesh) {
  61260. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61261. var result = BABYLON.Matrix.Identity();
  61262. this.getRotationMatrixToRef(space, mesh, result);
  61263. return result;
  61264. };
  61265. /**
  61266. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  61267. * @param space The space that the rotation should be in.
  61268. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61269. * @param result The quaternion that the rotation should be copied to.
  61270. */
  61271. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  61272. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61273. if (space == BABYLON.Space.LOCAL) {
  61274. this.getLocalMatrix().getRotationMatrixToRef(result);
  61275. }
  61276. else {
  61277. var mat = Bone._tmpMats[0];
  61278. var amat = this.getAbsoluteTransform();
  61279. if (mesh) {
  61280. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61281. }
  61282. else {
  61283. mat.copyFrom(amat);
  61284. }
  61285. mat.m[0] *= this._scalingDeterminant;
  61286. mat.m[1] *= this._scalingDeterminant;
  61287. mat.m[2] *= this._scalingDeterminant;
  61288. mat.getRotationMatrixToRef(result);
  61289. }
  61290. };
  61291. /**
  61292. * Get the world position of a point that is in the local space of the bone.
  61293. * @param position The local position
  61294. * @param mesh The mesh that this bone is attached to.
  61295. * @returns The world position
  61296. */
  61297. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  61298. if (mesh === void 0) { mesh = null; }
  61299. var result = BABYLON.Vector3.Zero();
  61300. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  61301. return result;
  61302. };
  61303. /**
  61304. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  61305. * @param position The local position
  61306. * @param mesh The mesh that this bone is attached to.
  61307. * @param result The vector3 that the world position should be copied to.
  61308. */
  61309. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  61310. if (mesh === void 0) { mesh = null; }
  61311. var wm = null;
  61312. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61313. if (mesh) {
  61314. wm = mesh.getWorldMatrix();
  61315. }
  61316. this._skeleton.computeAbsoluteTransforms();
  61317. var tmat = Bone._tmpMats[0];
  61318. if (mesh && wm) {
  61319. tmat.copyFrom(this.getAbsoluteTransform());
  61320. tmat.multiplyToRef(wm, tmat);
  61321. }
  61322. else {
  61323. tmat = this.getAbsoluteTransform();
  61324. }
  61325. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61326. };
  61327. /**
  61328. * Get the local position of a point that is in world space.
  61329. * @param position The world position
  61330. * @param mesh The mesh that this bone is attached to.
  61331. * @returns The local position
  61332. */
  61333. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61334. if (mesh === void 0) { mesh = null; }
  61335. var result = BABYLON.Vector3.Zero();
  61336. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61337. return result;
  61338. };
  61339. /**
  61340. * Get the local position of a point that is in world space and copy it to the result param.
  61341. * @param position The world position
  61342. * @param mesh The mesh that this bone is attached to.
  61343. * @param result The vector3 that the local position should be copied to.
  61344. */
  61345. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61346. if (mesh === void 0) { mesh = null; }
  61347. var wm = null;
  61348. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61349. if (mesh) {
  61350. wm = mesh.getWorldMatrix();
  61351. }
  61352. this._skeleton.computeAbsoluteTransforms();
  61353. var tmat = Bone._tmpMats[0];
  61354. tmat.copyFrom(this.getAbsoluteTransform());
  61355. if (mesh && wm) {
  61356. tmat.multiplyToRef(wm, tmat);
  61357. }
  61358. tmat.invert();
  61359. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61360. };
  61361. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61362. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61363. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61364. return Bone;
  61365. }(BABYLON.Node));
  61366. BABYLON.Bone = Bone;
  61367. })(BABYLON || (BABYLON = {}));
  61368. //# sourceMappingURL=babylon.bone.js.map
  61369. var BABYLON;
  61370. (function (BABYLON) {
  61371. var BoneIKController = /** @class */ (function () {
  61372. function BoneIKController(mesh, bone, options) {
  61373. this.targetPosition = BABYLON.Vector3.Zero();
  61374. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61375. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61376. this.poleAngle = 0;
  61377. this.slerpAmount = 1;
  61378. this._bone1Quat = BABYLON.Quaternion.Identity();
  61379. this._bone1Mat = BABYLON.Matrix.Identity();
  61380. this._bone2Ang = Math.PI;
  61381. this._maxAngle = Math.PI;
  61382. this._rightHandedSystem = false;
  61383. this._bendAxis = BABYLON.Vector3.Right();
  61384. this._slerping = false;
  61385. this._adjustRoll = 0;
  61386. this._bone2 = bone;
  61387. this._bone1 = bone.getParent();
  61388. if (!this._bone1) {
  61389. return;
  61390. }
  61391. this.mesh = mesh;
  61392. var bonePos = bone.getPosition();
  61393. if (bone.getAbsoluteTransform().determinant() > 0) {
  61394. this._rightHandedSystem = true;
  61395. this._bendAxis.x = 0;
  61396. this._bendAxis.y = 0;
  61397. this._bendAxis.z = -1;
  61398. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61399. this._adjustRoll = Math.PI * .5;
  61400. this._bendAxis.z = 1;
  61401. }
  61402. }
  61403. if (this._bone1.length) {
  61404. var boneScale1 = this._bone1.getScale();
  61405. var boneScale2 = this._bone2.getScale();
  61406. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  61407. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  61408. }
  61409. else if (this._bone1.children[0]) {
  61410. mesh.computeWorldMatrix(true);
  61411. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  61412. var pos2 = this._bone2.getAbsolutePosition(mesh);
  61413. var pos3 = this._bone1.getAbsolutePosition(mesh);
  61414. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  61415. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  61416. }
  61417. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  61418. this.maxAngle = Math.PI;
  61419. if (options) {
  61420. if (options.targetMesh) {
  61421. this.targetMesh = options.targetMesh;
  61422. this.targetMesh.computeWorldMatrix(true);
  61423. }
  61424. if (options.poleTargetMesh) {
  61425. this.poleTargetMesh = options.poleTargetMesh;
  61426. this.poleTargetMesh.computeWorldMatrix(true);
  61427. }
  61428. else if (options.poleTargetBone) {
  61429. this.poleTargetBone = options.poleTargetBone;
  61430. }
  61431. else if (this._bone1.getParent()) {
  61432. this.poleTargetBone = this._bone1.getParent();
  61433. }
  61434. if (options.poleTargetLocalOffset) {
  61435. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  61436. }
  61437. if (options.poleAngle) {
  61438. this.poleAngle = options.poleAngle;
  61439. }
  61440. if (options.bendAxis) {
  61441. this._bendAxis.copyFrom(options.bendAxis);
  61442. }
  61443. if (options.maxAngle) {
  61444. this.maxAngle = options.maxAngle;
  61445. }
  61446. if (options.slerpAmount) {
  61447. this.slerpAmount = options.slerpAmount;
  61448. }
  61449. }
  61450. }
  61451. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  61452. get: function () {
  61453. return this._maxAngle;
  61454. },
  61455. set: function (value) {
  61456. this._setMaxAngle(value);
  61457. },
  61458. enumerable: true,
  61459. configurable: true
  61460. });
  61461. BoneIKController.prototype._setMaxAngle = function (ang) {
  61462. if (ang < 0) {
  61463. ang = 0;
  61464. }
  61465. if (ang > Math.PI || ang == undefined) {
  61466. ang = Math.PI;
  61467. }
  61468. this._maxAngle = ang;
  61469. var a = this._bone1Length;
  61470. var b = this._bone2Length;
  61471. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  61472. };
  61473. BoneIKController.prototype.update = function () {
  61474. var bone1 = this._bone1;
  61475. if (!bone1) {
  61476. return;
  61477. }
  61478. var target = this.targetPosition;
  61479. var poleTarget = this.poleTargetPosition;
  61480. var mat1 = BoneIKController._tmpMats[0];
  61481. var mat2 = BoneIKController._tmpMats[1];
  61482. if (this.targetMesh) {
  61483. target.copyFrom(this.targetMesh.getAbsolutePosition());
  61484. }
  61485. if (this.poleTargetBone) {
  61486. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  61487. }
  61488. else if (this.poleTargetMesh) {
  61489. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  61490. }
  61491. var bonePos = BoneIKController._tmpVecs[0];
  61492. var zaxis = BoneIKController._tmpVecs[1];
  61493. var xaxis = BoneIKController._tmpVecs[2];
  61494. var yaxis = BoneIKController._tmpVecs[3];
  61495. var upAxis = BoneIKController._tmpVecs[4];
  61496. var _tmpQuat = BoneIKController._tmpQuat;
  61497. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  61498. poleTarget.subtractToRef(bonePos, upAxis);
  61499. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  61500. upAxis.y = 1;
  61501. }
  61502. else {
  61503. upAxis.normalize();
  61504. }
  61505. target.subtractToRef(bonePos, yaxis);
  61506. yaxis.normalize();
  61507. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  61508. zaxis.normalize();
  61509. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  61510. xaxis.normalize();
  61511. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  61512. var a = this._bone1Length;
  61513. var b = this._bone2Length;
  61514. var c = BABYLON.Vector3.Distance(bonePos, target);
  61515. if (this._maxReach > 0) {
  61516. c = Math.min(this._maxReach, c);
  61517. }
  61518. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  61519. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  61520. if (acosa > 1) {
  61521. acosa = 1;
  61522. }
  61523. if (acosb > 1) {
  61524. acosb = 1;
  61525. }
  61526. if (acosa < -1) {
  61527. acosa = -1;
  61528. }
  61529. if (acosb < -1) {
  61530. acosb = -1;
  61531. }
  61532. var angA = Math.acos(acosa);
  61533. var angB = Math.acos(acosb);
  61534. var angC = -angA - angB;
  61535. if (this._rightHandedSystem) {
  61536. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  61537. mat2.multiplyToRef(mat1, mat1);
  61538. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  61539. mat2.multiplyToRef(mat1, mat1);
  61540. }
  61541. else {
  61542. var _tmpVec = BoneIKController._tmpVecs[5];
  61543. _tmpVec.copyFrom(this._bendAxis);
  61544. _tmpVec.x *= -1;
  61545. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  61546. mat2.multiplyToRef(mat1, mat1);
  61547. }
  61548. if (this.poleAngle) {
  61549. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  61550. mat1.multiplyToRef(mat2, mat1);
  61551. }
  61552. if (this._bone1) {
  61553. if (this.slerpAmount < 1) {
  61554. if (!this._slerping) {
  61555. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  61556. }
  61557. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  61558. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  61559. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  61560. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  61561. this._slerping = true;
  61562. }
  61563. else {
  61564. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  61565. this._bone1Mat.copyFrom(mat1);
  61566. this._slerping = false;
  61567. }
  61568. }
  61569. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  61570. this._bone2Ang = angC;
  61571. };
  61572. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61573. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  61574. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61575. return BoneIKController;
  61576. }());
  61577. BABYLON.BoneIKController = BoneIKController;
  61578. })(BABYLON || (BABYLON = {}));
  61579. //# sourceMappingURL=babylon.boneIKController.js.map
  61580. var BABYLON;
  61581. (function (BABYLON) {
  61582. var BoneLookController = /** @class */ (function () {
  61583. /**
  61584. * Create a BoneLookController
  61585. * @param mesh the mesh that the bone belongs to
  61586. * @param bone the bone that will be looking to the target
  61587. * @param target the target Vector3 to look at
  61588. * @param settings optional settings:
  61589. * - maxYaw: the maximum angle the bone will yaw to
  61590. * - minYaw: the minimum angle the bone will yaw to
  61591. * - maxPitch: the maximum angle the bone will pitch to
  61592. * - minPitch: the minimum angle the bone will yaw to
  61593. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  61594. * - upAxis: the up axis of the coordinate system
  61595. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61596. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  61597. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  61598. * - adjustYaw: used to make an adjustment to the yaw of the bone
  61599. * - adjustPitch: used to make an adjustment to the pitch of the bone
  61600. * - adjustRoll: used to make an adjustment to the roll of the bone
  61601. **/
  61602. function BoneLookController(mesh, bone, target, options) {
  61603. /**
  61604. * The up axis of the coordinate system that is used when the bone is rotated.
  61605. */
  61606. this.upAxis = BABYLON.Vector3.Up();
  61607. /**
  61608. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61609. */
  61610. this.upAxisSpace = BABYLON.Space.LOCAL;
  61611. /**
  61612. * Used to make an adjustment to the yaw of the bone.
  61613. */
  61614. this.adjustYaw = 0;
  61615. /**
  61616. * Used to make an adjustment to the pitch of the bone.
  61617. */
  61618. this.adjustPitch = 0;
  61619. /**
  61620. * Used to make an adjustment to the roll of the bone.
  61621. */
  61622. this.adjustRoll = 0;
  61623. /**
  61624. * 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).
  61625. */
  61626. this.slerpAmount = 1;
  61627. this._boneQuat = BABYLON.Quaternion.Identity();
  61628. this._slerping = false;
  61629. this._firstFrameSkipped = false;
  61630. this._fowardAxis = BABYLON.Vector3.Forward();
  61631. this.mesh = mesh;
  61632. this.bone = bone;
  61633. this.target = target;
  61634. if (options) {
  61635. if (options.adjustYaw) {
  61636. this.adjustYaw = options.adjustYaw;
  61637. }
  61638. if (options.adjustPitch) {
  61639. this.adjustPitch = options.adjustPitch;
  61640. }
  61641. if (options.adjustRoll) {
  61642. this.adjustRoll = options.adjustRoll;
  61643. }
  61644. if (options.maxYaw != null) {
  61645. this.maxYaw = options.maxYaw;
  61646. }
  61647. else {
  61648. this.maxYaw = Math.PI;
  61649. }
  61650. if (options.minYaw != null) {
  61651. this.minYaw = options.minYaw;
  61652. }
  61653. else {
  61654. this.minYaw = -Math.PI;
  61655. }
  61656. if (options.maxPitch != null) {
  61657. this.maxPitch = options.maxPitch;
  61658. }
  61659. else {
  61660. this.maxPitch = Math.PI;
  61661. }
  61662. if (options.minPitch != null) {
  61663. this.minPitch = options.minPitch;
  61664. }
  61665. else {
  61666. this.minPitch = -Math.PI;
  61667. }
  61668. if (options.slerpAmount != null) {
  61669. this.slerpAmount = options.slerpAmount;
  61670. }
  61671. if (options.upAxis != null) {
  61672. this.upAxis = options.upAxis;
  61673. }
  61674. if (options.upAxisSpace != null) {
  61675. this.upAxisSpace = options.upAxisSpace;
  61676. }
  61677. if (options.yawAxis != null || options.pitchAxis != null) {
  61678. var newYawAxis = BABYLON.Axis.Y;
  61679. var newPitchAxis = BABYLON.Axis.X;
  61680. if (options.yawAxis != null) {
  61681. newYawAxis = options.yawAxis.clone();
  61682. newYawAxis.normalize();
  61683. }
  61684. if (options.pitchAxis != null) {
  61685. newPitchAxis = options.pitchAxis.clone();
  61686. newPitchAxis.normalize();
  61687. }
  61688. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  61689. this._transformYawPitch = BABYLON.Matrix.Identity();
  61690. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  61691. this._transformYawPitchInv = this._transformYawPitch.clone();
  61692. this._transformYawPitch.invert();
  61693. }
  61694. }
  61695. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  61696. this.upAxisSpace = BABYLON.Space.LOCAL;
  61697. }
  61698. }
  61699. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  61700. /**
  61701. * Get/set the minimum yaw angle that the bone can look to.
  61702. */
  61703. get: function () {
  61704. return this._minYaw;
  61705. },
  61706. set: function (value) {
  61707. this._minYaw = value;
  61708. this._minYawSin = Math.sin(value);
  61709. this._minYawCos = Math.cos(value);
  61710. if (this._maxYaw != null) {
  61711. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61712. this._yawRange = this._maxYaw - this._minYaw;
  61713. }
  61714. },
  61715. enumerable: true,
  61716. configurable: true
  61717. });
  61718. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  61719. /**
  61720. * Get/set the maximum yaw angle that the bone can look to.
  61721. */
  61722. get: function () {
  61723. return this._maxYaw;
  61724. },
  61725. set: function (value) {
  61726. this._maxYaw = value;
  61727. this._maxYawSin = Math.sin(value);
  61728. this._maxYawCos = Math.cos(value);
  61729. if (this._minYaw != null) {
  61730. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61731. this._yawRange = this._maxYaw - this._minYaw;
  61732. }
  61733. },
  61734. enumerable: true,
  61735. configurable: true
  61736. });
  61737. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  61738. /**
  61739. * Get/set the minimum pitch angle that the bone can look to.
  61740. */
  61741. get: function () {
  61742. return this._minPitch;
  61743. },
  61744. set: function (value) {
  61745. this._minPitch = value;
  61746. this._minPitchTan = Math.tan(value);
  61747. },
  61748. enumerable: true,
  61749. configurable: true
  61750. });
  61751. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  61752. /**
  61753. * Get/set the maximum pitch angle that the bone can look to.
  61754. */
  61755. get: function () {
  61756. return this._maxPitch;
  61757. },
  61758. set: function (value) {
  61759. this._maxPitch = value;
  61760. this._maxPitchTan = Math.tan(value);
  61761. },
  61762. enumerable: true,
  61763. configurable: true
  61764. });
  61765. /**
  61766. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  61767. */
  61768. BoneLookController.prototype.update = function () {
  61769. //skip the first frame when slerping so that the mesh rotation is correct
  61770. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  61771. this._firstFrameSkipped = true;
  61772. return;
  61773. }
  61774. var bone = this.bone;
  61775. var bonePos = BoneLookController._tmpVecs[0];
  61776. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  61777. var target = this.target;
  61778. var _tmpMat1 = BoneLookController._tmpMats[0];
  61779. var _tmpMat2 = BoneLookController._tmpMats[1];
  61780. var mesh = this.mesh;
  61781. var parentBone = bone.getParent();
  61782. var upAxis = BoneLookController._tmpVecs[1];
  61783. upAxis.copyFrom(this.upAxis);
  61784. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  61785. if (this._transformYawPitch) {
  61786. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  61787. }
  61788. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  61789. }
  61790. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  61791. mesh.getDirectionToRef(upAxis, upAxis);
  61792. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  61793. upAxis.normalize();
  61794. }
  61795. }
  61796. var checkYaw = false;
  61797. var checkPitch = false;
  61798. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  61799. checkYaw = true;
  61800. }
  61801. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  61802. checkPitch = true;
  61803. }
  61804. if (checkYaw || checkPitch) {
  61805. var spaceMat = BoneLookController._tmpMats[2];
  61806. var spaceMatInv = BoneLookController._tmpMats[3];
  61807. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  61808. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  61809. }
  61810. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  61811. spaceMat.copyFrom(mesh.getWorldMatrix());
  61812. }
  61813. else {
  61814. var forwardAxis = BoneLookController._tmpVecs[2];
  61815. forwardAxis.copyFrom(this._fowardAxis);
  61816. if (this._transformYawPitch) {
  61817. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  61818. }
  61819. if (parentBone) {
  61820. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  61821. }
  61822. else {
  61823. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  61824. }
  61825. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  61826. rightAxis.normalize();
  61827. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  61828. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  61829. }
  61830. spaceMat.invertToRef(spaceMatInv);
  61831. var xzlen = null;
  61832. if (checkPitch) {
  61833. var localTarget = BoneLookController._tmpVecs[3];
  61834. target.subtractToRef(bonePos, localTarget);
  61835. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61836. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61837. var pitch = Math.atan2(localTarget.y, xzlen);
  61838. var newPitch = pitch;
  61839. if (pitch > this._maxPitch) {
  61840. localTarget.y = this._maxPitchTan * xzlen;
  61841. newPitch = this._maxPitch;
  61842. }
  61843. else if (pitch < this._minPitch) {
  61844. localTarget.y = this._minPitchTan * xzlen;
  61845. newPitch = this._minPitch;
  61846. }
  61847. if (pitch != newPitch) {
  61848. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61849. localTarget.addInPlace(bonePos);
  61850. target = localTarget;
  61851. }
  61852. }
  61853. if (checkYaw) {
  61854. var localTarget = BoneLookController._tmpVecs[4];
  61855. target.subtractToRef(bonePos, localTarget);
  61856. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61857. var yaw = Math.atan2(localTarget.x, localTarget.z);
  61858. var newYaw = yaw;
  61859. if (yaw > this._maxYaw || yaw < this._minYaw) {
  61860. if (xzlen == null) {
  61861. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61862. }
  61863. if (this._yawRange > Math.PI) {
  61864. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  61865. localTarget.z = this._maxYawCos * xzlen;
  61866. localTarget.x = this._maxYawSin * xzlen;
  61867. newYaw = this._maxYaw;
  61868. }
  61869. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  61870. localTarget.z = this._minYawCos * xzlen;
  61871. localTarget.x = this._minYawSin * xzlen;
  61872. newYaw = this._minYaw;
  61873. }
  61874. }
  61875. else {
  61876. if (yaw > this._maxYaw) {
  61877. localTarget.z = this._maxYawCos * xzlen;
  61878. localTarget.x = this._maxYawSin * xzlen;
  61879. newYaw = this._maxYaw;
  61880. }
  61881. else if (yaw < this._minYaw) {
  61882. localTarget.z = this._minYawCos * xzlen;
  61883. localTarget.x = this._minYawSin * xzlen;
  61884. newYaw = this._minYaw;
  61885. }
  61886. }
  61887. }
  61888. if (this._slerping && this._yawRange > Math.PI) {
  61889. //are we going to be crossing into the min/max region?
  61890. var boneFwd = BoneLookController._tmpVecs[8];
  61891. boneFwd.copyFrom(BABYLON.Axis.Z);
  61892. if (this._transformYawPitch) {
  61893. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  61894. }
  61895. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  61896. this._boneQuat.toRotationMatrix(boneRotMat);
  61897. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  61898. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  61899. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  61900. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  61901. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  61902. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  61903. if (angBtwTar > angBtwMidYaw) {
  61904. if (xzlen == null) {
  61905. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61906. }
  61907. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  61908. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  61909. if (angBtwMin < angBtwMax) {
  61910. newYaw = boneYaw + Math.PI * .75;
  61911. localTarget.z = Math.cos(newYaw) * xzlen;
  61912. localTarget.x = Math.sin(newYaw) * xzlen;
  61913. }
  61914. else {
  61915. newYaw = boneYaw - Math.PI * .75;
  61916. localTarget.z = Math.cos(newYaw) * xzlen;
  61917. localTarget.x = Math.sin(newYaw) * xzlen;
  61918. }
  61919. }
  61920. }
  61921. if (yaw != newYaw) {
  61922. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61923. localTarget.addInPlace(bonePos);
  61924. target = localTarget;
  61925. }
  61926. }
  61927. }
  61928. var zaxis = BoneLookController._tmpVecs[5];
  61929. var xaxis = BoneLookController._tmpVecs[6];
  61930. var yaxis = BoneLookController._tmpVecs[7];
  61931. var _tmpQuat = BoneLookController._tmpQuat;
  61932. target.subtractToRef(bonePos, zaxis);
  61933. zaxis.normalize();
  61934. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  61935. xaxis.normalize();
  61936. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  61937. yaxis.normalize();
  61938. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  61939. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  61940. return;
  61941. }
  61942. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  61943. return;
  61944. }
  61945. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  61946. return;
  61947. }
  61948. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  61949. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  61950. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  61951. }
  61952. if (this.slerpAmount < 1) {
  61953. if (!this._slerping) {
  61954. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  61955. }
  61956. if (this._transformYawPitch) {
  61957. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61958. }
  61959. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  61960. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  61961. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  61962. this._slerping = true;
  61963. }
  61964. else {
  61965. if (this._transformYawPitch) {
  61966. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61967. }
  61968. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  61969. this._slerping = false;
  61970. }
  61971. };
  61972. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  61973. var angDiff = ang2 - ang1;
  61974. angDiff %= Math.PI * 2;
  61975. if (angDiff > Math.PI) {
  61976. angDiff -= Math.PI * 2;
  61977. }
  61978. else if (angDiff < -Math.PI) {
  61979. angDiff += Math.PI * 2;
  61980. }
  61981. return angDiff;
  61982. };
  61983. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  61984. ang1 %= (2 * Math.PI);
  61985. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61986. ang2 %= (2 * Math.PI);
  61987. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61988. var ab = 0;
  61989. if (ang1 < ang2) {
  61990. ab = ang2 - ang1;
  61991. }
  61992. else {
  61993. ab = ang1 - ang2;
  61994. }
  61995. if (ab > Math.PI) {
  61996. ab = Math.PI * 2 - ab;
  61997. }
  61998. return ab;
  61999. };
  62000. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  62001. ang %= (2 * Math.PI);
  62002. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  62003. ang1 %= (2 * Math.PI);
  62004. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62005. ang2 %= (2 * Math.PI);
  62006. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62007. if (ang1 < ang2) {
  62008. if (ang > ang1 && ang < ang2) {
  62009. return true;
  62010. }
  62011. }
  62012. else {
  62013. if (ang > ang2 && ang < ang1) {
  62014. return true;
  62015. }
  62016. }
  62017. return false;
  62018. };
  62019. 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()];
  62020. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  62021. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62022. return BoneLookController;
  62023. }());
  62024. BABYLON.BoneLookController = BoneLookController;
  62025. })(BABYLON || (BABYLON = {}));
  62026. //# sourceMappingURL=babylon.boneLookController.js.map
  62027. var BABYLON;
  62028. (function (BABYLON) {
  62029. var Skeleton = /** @class */ (function () {
  62030. function Skeleton(name, id, scene) {
  62031. this.name = name;
  62032. this.id = id;
  62033. this.bones = new Array();
  62034. this.needInitialSkinMatrix = false;
  62035. this._isDirty = true;
  62036. this._meshesWithPoseMatrix = new Array();
  62037. this._identity = BABYLON.Matrix.Identity();
  62038. this._ranges = {};
  62039. this._lastAbsoluteTransformsUpdateId = -1;
  62040. // Events
  62041. /**
  62042. * An event triggered before computing the skeleton's matrices
  62043. * @type {BABYLON.Observable}
  62044. */
  62045. this.onBeforeComputeObservable = new BABYLON.Observable();
  62046. this.bones = [];
  62047. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62048. scene.skeletons.push(this);
  62049. //make sure it will recalculate the matrix next time prepare is called.
  62050. this._isDirty = true;
  62051. }
  62052. // Members
  62053. Skeleton.prototype.getTransformMatrices = function (mesh) {
  62054. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  62055. return mesh._bonesTransformMatrices;
  62056. }
  62057. if (!this._transformMatrices) {
  62058. this.prepare();
  62059. }
  62060. return this._transformMatrices;
  62061. };
  62062. Skeleton.prototype.getScene = function () {
  62063. return this._scene;
  62064. };
  62065. // Methods
  62066. /**
  62067. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  62068. */
  62069. Skeleton.prototype.toString = function (fullDetails) {
  62070. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  62071. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  62072. if (fullDetails) {
  62073. ret += ", Ranges: {";
  62074. var first = true;
  62075. for (var name_1 in this._ranges) {
  62076. if (first) {
  62077. ret += ", ";
  62078. first = false;
  62079. }
  62080. ret += name_1;
  62081. }
  62082. ret += "}";
  62083. }
  62084. return ret;
  62085. };
  62086. /**
  62087. * Get bone's index searching by name
  62088. * @param {string} name is bone's name to search for
  62089. * @return {number} Indice of the bone. Returns -1 if not found
  62090. */
  62091. Skeleton.prototype.getBoneIndexByName = function (name) {
  62092. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  62093. if (this.bones[boneIndex].name === name) {
  62094. return boneIndex;
  62095. }
  62096. }
  62097. return -1;
  62098. };
  62099. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  62100. // check name not already in use
  62101. if (!this._ranges[name]) {
  62102. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  62103. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62104. if (this.bones[i].animations[0]) {
  62105. this.bones[i].animations[0].createRange(name, from, to);
  62106. }
  62107. }
  62108. }
  62109. };
  62110. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  62111. if (deleteFrames === void 0) { deleteFrames = true; }
  62112. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62113. if (this.bones[i].animations[0]) {
  62114. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  62115. }
  62116. }
  62117. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  62118. };
  62119. Skeleton.prototype.getAnimationRange = function (name) {
  62120. return this._ranges[name];
  62121. };
  62122. /**
  62123. * Returns as an Array, all AnimationRanges defined on this skeleton
  62124. */
  62125. Skeleton.prototype.getAnimationRanges = function () {
  62126. var animationRanges = [];
  62127. var name;
  62128. var i = 0;
  62129. for (name in this._ranges) {
  62130. animationRanges[i] = this._ranges[name];
  62131. i++;
  62132. }
  62133. return animationRanges;
  62134. };
  62135. /**
  62136. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  62137. */
  62138. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  62139. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  62140. if (this._ranges[name] || !source.getAnimationRange(name)) {
  62141. return false;
  62142. }
  62143. var ret = true;
  62144. var frameOffset = this._getHighestAnimationFrame() + 1;
  62145. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  62146. var boneDict = {};
  62147. var sourceBones = source.bones;
  62148. var nBones;
  62149. var i;
  62150. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  62151. boneDict[sourceBones[i].name] = sourceBones[i];
  62152. }
  62153. if (this.bones.length !== sourceBones.length) {
  62154. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  62155. ret = false;
  62156. }
  62157. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  62158. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  62159. var boneName = this.bones[i].name;
  62160. var sourceBone = boneDict[boneName];
  62161. if (sourceBone) {
  62162. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  62163. }
  62164. else {
  62165. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  62166. ret = false;
  62167. }
  62168. }
  62169. // do not call createAnimationRange(), since it also is done to bones, which was already done
  62170. var range = source.getAnimationRange(name);
  62171. if (range) {
  62172. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  62173. }
  62174. return ret;
  62175. };
  62176. Skeleton.prototype.returnToRest = function () {
  62177. for (var index = 0; index < this.bones.length; index++) {
  62178. this.bones[index].returnToRest();
  62179. }
  62180. };
  62181. Skeleton.prototype._getHighestAnimationFrame = function () {
  62182. var ret = 0;
  62183. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62184. if (this.bones[i].animations[0]) {
  62185. var highest = this.bones[i].animations[0].getHighestFrame();
  62186. if (ret < highest) {
  62187. ret = highest;
  62188. }
  62189. }
  62190. }
  62191. return ret;
  62192. };
  62193. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  62194. var range = this.getAnimationRange(name);
  62195. if (!range) {
  62196. return null;
  62197. }
  62198. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  62199. };
  62200. Skeleton.prototype._markAsDirty = function () {
  62201. this._isDirty = true;
  62202. };
  62203. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  62204. this._meshesWithPoseMatrix.push(mesh);
  62205. };
  62206. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  62207. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  62208. if (index > -1) {
  62209. this._meshesWithPoseMatrix.splice(index, 1);
  62210. }
  62211. };
  62212. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  62213. this.onBeforeComputeObservable.notifyObservers(this);
  62214. for (var index = 0; index < this.bones.length; index++) {
  62215. var bone = this.bones[index];
  62216. var parentBone = bone.getParent();
  62217. if (parentBone) {
  62218. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  62219. }
  62220. else {
  62221. if (initialSkinMatrix) {
  62222. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  62223. }
  62224. else {
  62225. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  62226. }
  62227. }
  62228. if (bone._index !== -1) {
  62229. var mappedIndex = bone._index === null ? index : bone._index;
  62230. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  62231. }
  62232. }
  62233. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  62234. };
  62235. Skeleton.prototype.prepare = function () {
  62236. if (!this._isDirty) {
  62237. return;
  62238. }
  62239. if (this.needInitialSkinMatrix) {
  62240. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  62241. var mesh = this._meshesWithPoseMatrix[index];
  62242. var poseMatrix = mesh.getPoseMatrix();
  62243. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  62244. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62245. }
  62246. if (this._synchronizedWithMesh !== mesh) {
  62247. this._synchronizedWithMesh = mesh;
  62248. // Prepare bones
  62249. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  62250. var bone = this.bones[boneIndex];
  62251. if (!bone.getParent()) {
  62252. var matrix = bone.getBaseMatrix();
  62253. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  62254. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  62255. }
  62256. }
  62257. }
  62258. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  62259. }
  62260. }
  62261. else {
  62262. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  62263. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62264. }
  62265. this._computeTransformMatrices(this._transformMatrices, null);
  62266. }
  62267. this._isDirty = false;
  62268. this._scene._activeBones.addCount(this.bones.length, false);
  62269. };
  62270. Skeleton.prototype.getAnimatables = function () {
  62271. if (!this._animatables || this._animatables.length !== this.bones.length) {
  62272. this._animatables = [];
  62273. for (var index = 0; index < this.bones.length; index++) {
  62274. this._animatables.push(this.bones[index]);
  62275. }
  62276. }
  62277. return this._animatables;
  62278. };
  62279. Skeleton.prototype.clone = function (name, id) {
  62280. var result = new Skeleton(name, id || name, this._scene);
  62281. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62282. for (var index = 0; index < this.bones.length; index++) {
  62283. var source = this.bones[index];
  62284. var parentBone = null;
  62285. var parent_1 = source.getParent();
  62286. if (parent_1) {
  62287. var parentIndex = this.bones.indexOf(parent_1);
  62288. parentBone = result.bones[parentIndex];
  62289. }
  62290. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  62291. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  62292. }
  62293. if (this._ranges) {
  62294. result._ranges = {};
  62295. for (var rangeName in this._ranges) {
  62296. var range = this._ranges[rangeName];
  62297. if (range) {
  62298. result._ranges[rangeName] = range.clone();
  62299. }
  62300. }
  62301. }
  62302. this._isDirty = true;
  62303. return result;
  62304. };
  62305. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  62306. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  62307. this.bones.forEach(function (bone) {
  62308. bone.animations.forEach(function (animation) {
  62309. animation.enableBlending = true;
  62310. animation.blendingSpeed = blendingSpeed;
  62311. });
  62312. });
  62313. };
  62314. Skeleton.prototype.dispose = function () {
  62315. this._meshesWithPoseMatrix = [];
  62316. // Animations
  62317. this.getScene().stopAnimation(this);
  62318. // Remove from scene
  62319. this.getScene().removeSkeleton(this);
  62320. };
  62321. Skeleton.prototype.serialize = function () {
  62322. var serializationObject = {};
  62323. serializationObject.name = this.name;
  62324. serializationObject.id = this.id;
  62325. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  62326. serializationObject.bones = [];
  62327. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62328. for (var index = 0; index < this.bones.length; index++) {
  62329. var bone = this.bones[index];
  62330. var parent_2 = bone.getParent();
  62331. var serializedBone = {
  62332. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62333. name: bone.name,
  62334. matrix: bone.getBaseMatrix().toArray(),
  62335. rest: bone.getRestPose().toArray()
  62336. };
  62337. serializationObject.bones.push(serializedBone);
  62338. if (bone.length) {
  62339. serializedBone.length = bone.length;
  62340. }
  62341. if (bone.animations && bone.animations.length > 0) {
  62342. serializedBone.animation = bone.animations[0].serialize();
  62343. }
  62344. serializationObject.ranges = [];
  62345. for (var name in this._ranges) {
  62346. var source = this._ranges[name];
  62347. if (!source) {
  62348. continue;
  62349. }
  62350. var range = {};
  62351. range.name = name;
  62352. range.from = source.from;
  62353. range.to = source.to;
  62354. serializationObject.ranges.push(range);
  62355. }
  62356. }
  62357. return serializationObject;
  62358. };
  62359. Skeleton.Parse = function (parsedSkeleton, scene) {
  62360. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62361. if (parsedSkeleton.dimensionsAtRest) {
  62362. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62363. }
  62364. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62365. var index;
  62366. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62367. var parsedBone = parsedSkeleton.bones[index];
  62368. var parentBone = null;
  62369. if (parsedBone.parentBoneIndex > -1) {
  62370. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62371. }
  62372. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62373. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62374. if (parsedBone.length) {
  62375. bone.length = parsedBone.length;
  62376. }
  62377. if (parsedBone.animation) {
  62378. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62379. }
  62380. }
  62381. // placed after bones, so createAnimationRange can cascade down
  62382. if (parsedSkeleton.ranges) {
  62383. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62384. var data = parsedSkeleton.ranges[index];
  62385. skeleton.createAnimationRange(data.name, data.from, data.to);
  62386. }
  62387. }
  62388. return skeleton;
  62389. };
  62390. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62391. if (forceUpdate === void 0) { forceUpdate = false; }
  62392. var renderId = this._scene.getRenderId();
  62393. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62394. this.bones[0].computeAbsoluteTransforms();
  62395. this._lastAbsoluteTransformsUpdateId = renderId;
  62396. }
  62397. };
  62398. Skeleton.prototype.getPoseMatrix = function () {
  62399. var poseMatrix = null;
  62400. if (this._meshesWithPoseMatrix.length > 0) {
  62401. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62402. }
  62403. return poseMatrix;
  62404. };
  62405. Skeleton.prototype.sortBones = function () {
  62406. var bones = new Array();
  62407. var visited = new Array(this.bones.length);
  62408. for (var index = 0; index < this.bones.length; index++) {
  62409. this._sortBones(index, bones, visited);
  62410. }
  62411. this.bones = bones;
  62412. };
  62413. Skeleton.prototype._sortBones = function (index, bones, visited) {
  62414. if (visited[index]) {
  62415. return;
  62416. }
  62417. visited[index] = true;
  62418. var bone = this.bones[index];
  62419. if (bone._index === undefined) {
  62420. bone._index = index;
  62421. }
  62422. var parentBone = bone.getParent();
  62423. if (parentBone) {
  62424. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  62425. }
  62426. bones.push(bone);
  62427. };
  62428. return Skeleton;
  62429. }());
  62430. BABYLON.Skeleton = Skeleton;
  62431. })(BABYLON || (BABYLON = {}));
  62432. //# sourceMappingURL=babylon.skeleton.js.map
  62433. var BABYLON;
  62434. (function (BABYLON) {
  62435. var SphericalPolynomial = /** @class */ (function () {
  62436. function SphericalPolynomial() {
  62437. this.x = BABYLON.Vector3.Zero();
  62438. this.y = BABYLON.Vector3.Zero();
  62439. this.z = BABYLON.Vector3.Zero();
  62440. this.xx = BABYLON.Vector3.Zero();
  62441. this.yy = BABYLON.Vector3.Zero();
  62442. this.zz = BABYLON.Vector3.Zero();
  62443. this.xy = BABYLON.Vector3.Zero();
  62444. this.yz = BABYLON.Vector3.Zero();
  62445. this.zx = BABYLON.Vector3.Zero();
  62446. }
  62447. SphericalPolynomial.prototype.addAmbient = function (color) {
  62448. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62449. this.xx = this.xx.add(colorVector);
  62450. this.yy = this.yy.add(colorVector);
  62451. this.zz = this.zz.add(colorVector);
  62452. };
  62453. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  62454. var result = new SphericalPolynomial();
  62455. result.x = harmonics.L11.scale(1.02333);
  62456. result.y = harmonics.L1_1.scale(1.02333);
  62457. result.z = harmonics.L10.scale(1.02333);
  62458. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  62459. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  62460. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  62461. result.yz = harmonics.L2_1.scale(0.858086);
  62462. result.zx = harmonics.L21.scale(0.858086);
  62463. result.xy = harmonics.L2_2.scale(0.858086);
  62464. result.scale(1.0 / Math.PI);
  62465. return result;
  62466. };
  62467. SphericalPolynomial.prototype.scale = function (scale) {
  62468. this.x = this.x.scale(scale);
  62469. this.y = this.y.scale(scale);
  62470. this.z = this.z.scale(scale);
  62471. this.xx = this.xx.scale(scale);
  62472. this.yy = this.yy.scale(scale);
  62473. this.zz = this.zz.scale(scale);
  62474. this.yz = this.yz.scale(scale);
  62475. this.zx = this.zx.scale(scale);
  62476. this.xy = this.xy.scale(scale);
  62477. };
  62478. return SphericalPolynomial;
  62479. }());
  62480. BABYLON.SphericalPolynomial = SphericalPolynomial;
  62481. var SphericalHarmonics = /** @class */ (function () {
  62482. function SphericalHarmonics() {
  62483. this.L00 = BABYLON.Vector3.Zero();
  62484. this.L1_1 = BABYLON.Vector3.Zero();
  62485. this.L10 = BABYLON.Vector3.Zero();
  62486. this.L11 = BABYLON.Vector3.Zero();
  62487. this.L2_2 = BABYLON.Vector3.Zero();
  62488. this.L2_1 = BABYLON.Vector3.Zero();
  62489. this.L20 = BABYLON.Vector3.Zero();
  62490. this.L21 = BABYLON.Vector3.Zero();
  62491. this.L22 = BABYLON.Vector3.Zero();
  62492. }
  62493. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  62494. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62495. var c = colorVector.scale(deltaSolidAngle);
  62496. this.L00 = this.L00.add(c.scale(0.282095));
  62497. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  62498. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  62499. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  62500. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  62501. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  62502. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  62503. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  62504. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  62505. };
  62506. SphericalHarmonics.prototype.scale = function (scale) {
  62507. this.L00 = this.L00.scale(scale);
  62508. this.L1_1 = this.L1_1.scale(scale);
  62509. this.L10 = this.L10.scale(scale);
  62510. this.L11 = this.L11.scale(scale);
  62511. this.L2_2 = this.L2_2.scale(scale);
  62512. this.L2_1 = this.L2_1.scale(scale);
  62513. this.L20 = this.L20.scale(scale);
  62514. this.L21 = this.L21.scale(scale);
  62515. this.L22 = this.L22.scale(scale);
  62516. };
  62517. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  62518. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  62519. //
  62520. // E_lm = A_l * L_lm
  62521. //
  62522. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  62523. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  62524. // the scaling factors are given in equation 9.
  62525. // Constant (Band 0)
  62526. this.L00 = this.L00.scale(3.141593);
  62527. // Linear (Band 1)
  62528. this.L1_1 = this.L1_1.scale(2.094395);
  62529. this.L10 = this.L10.scale(2.094395);
  62530. this.L11 = this.L11.scale(2.094395);
  62531. // Quadratic (Band 2)
  62532. this.L2_2 = this.L2_2.scale(0.785398);
  62533. this.L2_1 = this.L2_1.scale(0.785398);
  62534. this.L20 = this.L20.scale(0.785398);
  62535. this.L21 = this.L21.scale(0.785398);
  62536. this.L22 = this.L22.scale(0.785398);
  62537. };
  62538. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  62539. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  62540. // L = (1/pi) * E * rho
  62541. //
  62542. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  62543. this.scale(1.0 / Math.PI);
  62544. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  62545. // (The pixel shader must apply albedo after texture fetches, etc).
  62546. };
  62547. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  62548. var result = new SphericalHarmonics();
  62549. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  62550. result.L1_1 = polynomial.y.scale(0.977204);
  62551. result.L10 = polynomial.z.scale(0.977204);
  62552. result.L11 = polynomial.x.scale(0.977204);
  62553. result.L2_2 = polynomial.xy.scale(1.16538);
  62554. result.L2_1 = polynomial.yz.scale(1.16538);
  62555. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  62556. result.L21 = polynomial.zx.scale(1.16538);
  62557. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  62558. result.scale(Math.PI);
  62559. return result;
  62560. };
  62561. return SphericalHarmonics;
  62562. }());
  62563. BABYLON.SphericalHarmonics = SphericalHarmonics;
  62564. })(BABYLON || (BABYLON = {}));
  62565. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  62566. var BABYLON;
  62567. (function (BABYLON) {
  62568. var Internals;
  62569. (function (Internals) {
  62570. var FileFaceOrientation = /** @class */ (function () {
  62571. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  62572. this.name = name;
  62573. this.worldAxisForNormal = worldAxisForNormal;
  62574. this.worldAxisForFileX = worldAxisForFileX;
  62575. this.worldAxisForFileY = worldAxisForFileY;
  62576. }
  62577. return FileFaceOrientation;
  62578. }());
  62579. ;
  62580. /**
  62581. * Helper class dealing with the extraction of spherical polynomial dataArray
  62582. * from a cube map.
  62583. */
  62584. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  62585. function CubeMapToSphericalPolynomialTools() {
  62586. }
  62587. /**
  62588. * Converts a texture to the according Spherical Polynomial data.
  62589. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62590. *
  62591. * @param texture The texture to extract the information from.
  62592. * @return The Spherical Polynomial data.
  62593. */
  62594. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  62595. if (!texture.isCube) {
  62596. // Only supports cube Textures currently.
  62597. return null;
  62598. }
  62599. var size = texture.getSize().width;
  62600. var right = texture.readPixels(0);
  62601. var left = texture.readPixels(1);
  62602. var up;
  62603. var down;
  62604. if (texture.isRenderTarget) {
  62605. up = texture.readPixels(3);
  62606. down = texture.readPixels(2);
  62607. }
  62608. else {
  62609. up = texture.readPixels(2);
  62610. down = texture.readPixels(3);
  62611. }
  62612. var front = texture.readPixels(4);
  62613. var back = texture.readPixels(5);
  62614. var gammaSpace = texture.gammaSpace;
  62615. // Always read as RGBA.
  62616. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  62617. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62618. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62619. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62620. }
  62621. var cubeInfo = {
  62622. size: size,
  62623. right: right,
  62624. left: left,
  62625. up: up,
  62626. down: down,
  62627. front: front,
  62628. back: back,
  62629. format: format,
  62630. type: type,
  62631. gammaSpace: gammaSpace,
  62632. };
  62633. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  62634. };
  62635. /**
  62636. * Converts a cubemap to the according Spherical Polynomial data.
  62637. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62638. *
  62639. * @param cubeInfo The Cube map to extract the information from.
  62640. * @return The Spherical Polynomial data.
  62641. */
  62642. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  62643. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  62644. var totalSolidAngle = 0.0;
  62645. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  62646. var du = 2.0 / cubeInfo.size;
  62647. var dv = du;
  62648. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  62649. var minUV = du * 0.5 - 1.0;
  62650. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62651. var fileFace = this.FileFaces[faceIndex];
  62652. var dataArray = cubeInfo[fileFace.name];
  62653. var v = minUV;
  62654. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  62655. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  62656. // Because SP is still linear, so summation is fine in that basis.
  62657. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  62658. for (var y = 0; y < cubeInfo.size; y++) {
  62659. var u = minUV;
  62660. for (var x = 0; x < cubeInfo.size; x++) {
  62661. // World direction (not normalised)
  62662. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  62663. worldDirection.normalize();
  62664. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  62665. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  62666. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  62667. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  62668. // Handle Integer types.
  62669. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62670. r /= 255;
  62671. g /= 255;
  62672. b /= 255;
  62673. }
  62674. // Handle Gamma space textures.
  62675. if (cubeInfo.gammaSpace) {
  62676. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  62677. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  62678. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  62679. }
  62680. var color = new BABYLON.Color3(r, g, b);
  62681. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  62682. totalSolidAngle += deltaSolidAngle;
  62683. u += du;
  62684. }
  62685. v += dv;
  62686. }
  62687. }
  62688. // Solid angle for entire sphere is 4*pi
  62689. var sphereSolidAngle = 4.0 * Math.PI;
  62690. // Adjust the solid angle to allow for how many faces we processed.
  62691. var facesProcessed = 6.0;
  62692. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  62693. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  62694. // This is needed because the numerical integration over the cube uses a
  62695. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  62696. // and also to compensate for accumulative error due to float precision in the summation.
  62697. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  62698. sphericalHarmonics.scale(correctionFactor);
  62699. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  62700. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  62701. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  62702. };
  62703. CubeMapToSphericalPolynomialTools.FileFaces = [
  62704. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  62705. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  62706. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  62707. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  62708. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  62709. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  62710. ];
  62711. return CubeMapToSphericalPolynomialTools;
  62712. }());
  62713. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  62714. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62715. })(BABYLON || (BABYLON = {}));
  62716. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  62717. var BABYLON;
  62718. (function (BABYLON) {
  62719. var Internals;
  62720. (function (Internals) {
  62721. /**
  62722. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  62723. */
  62724. var PanoramaToCubeMapTools = /** @class */ (function () {
  62725. function PanoramaToCubeMapTools() {
  62726. }
  62727. /**
  62728. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  62729. *
  62730. * @param float32Array The source data.
  62731. * @param inputWidth The width of the input panorama.
  62732. * @param inputhHeight The height of the input panorama.
  62733. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  62734. * @return The cubemap data
  62735. */
  62736. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  62737. if (!float32Array) {
  62738. throw "ConvertPanoramaToCubemap: input cannot be null";
  62739. }
  62740. if (float32Array.length != inputWidth * inputHeight * 3) {
  62741. throw "ConvertPanoramaToCubemap: input size is wrong";
  62742. }
  62743. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  62744. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  62745. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  62746. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  62747. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  62748. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  62749. return {
  62750. front: textureFront,
  62751. back: textureBack,
  62752. left: textureLeft,
  62753. right: textureRight,
  62754. up: textureUp,
  62755. down: textureDown,
  62756. size: size,
  62757. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  62758. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  62759. gammaSpace: false,
  62760. };
  62761. };
  62762. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  62763. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  62764. var textureArray = new Float32Array(buffer);
  62765. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  62766. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  62767. var dy = 1 / texSize;
  62768. var fy = 0;
  62769. for (var y = 0; y < texSize; y++) {
  62770. var xv1 = faceData[0];
  62771. var xv2 = faceData[2];
  62772. for (var x = 0; x < texSize; x++) {
  62773. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  62774. v.normalize();
  62775. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  62776. // 3 channels per pixels
  62777. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  62778. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  62779. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  62780. xv1 = xv1.add(rotDX1);
  62781. xv2 = xv2.add(rotDX2);
  62782. }
  62783. fy += dy;
  62784. }
  62785. return textureArray;
  62786. };
  62787. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  62788. var theta = Math.atan2(vDir.z, vDir.x);
  62789. var phi = Math.acos(vDir.y);
  62790. while (theta < -Math.PI)
  62791. theta += 2 * Math.PI;
  62792. while (theta > Math.PI)
  62793. theta -= 2 * Math.PI;
  62794. var dx = theta / Math.PI;
  62795. var dy = phi / Math.PI;
  62796. // recenter.
  62797. dx = dx * 0.5 + 0.5;
  62798. var px = Math.round(dx * inputWidth);
  62799. if (px < 0)
  62800. px = 0;
  62801. else if (px >= inputWidth)
  62802. px = inputWidth - 1;
  62803. var py = Math.round(dy * inputHeight);
  62804. if (py < 0)
  62805. py = 0;
  62806. else if (py >= inputHeight)
  62807. py = inputHeight - 1;
  62808. var inputY = (inputHeight - py - 1);
  62809. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  62810. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  62811. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  62812. return {
  62813. r: r,
  62814. g: g,
  62815. b: b
  62816. };
  62817. };
  62818. PanoramaToCubeMapTools.FACE_FRONT = [
  62819. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62820. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62821. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62822. new BABYLON.Vector3(1.0, 1.0, -1.0)
  62823. ];
  62824. PanoramaToCubeMapTools.FACE_BACK = [
  62825. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62826. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62827. new BABYLON.Vector3(1.0, 1.0, 1.0),
  62828. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  62829. ];
  62830. PanoramaToCubeMapTools.FACE_RIGHT = [
  62831. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62832. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62833. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62834. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62835. ];
  62836. PanoramaToCubeMapTools.FACE_LEFT = [
  62837. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62838. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62839. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62840. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  62841. ];
  62842. PanoramaToCubeMapTools.FACE_DOWN = [
  62843. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62844. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62845. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62846. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62847. ];
  62848. PanoramaToCubeMapTools.FACE_UP = [
  62849. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62850. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62851. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62852. new BABYLON.Vector3(1.0, -1.0, -1.0)
  62853. ];
  62854. return PanoramaToCubeMapTools;
  62855. }());
  62856. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  62857. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62858. })(BABYLON || (BABYLON = {}));
  62859. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  62860. var BABYLON;
  62861. (function (BABYLON) {
  62862. var Internals;
  62863. (function (Internals) {
  62864. ;
  62865. /**
  62866. * This groups tools to convert HDR texture to native colors array.
  62867. */
  62868. var HDRTools = /** @class */ (function () {
  62869. function HDRTools() {
  62870. }
  62871. HDRTools.Ldexp = function (mantissa, exponent) {
  62872. if (exponent > 1023) {
  62873. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  62874. }
  62875. if (exponent < -1074) {
  62876. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  62877. }
  62878. return mantissa * Math.pow(2, exponent);
  62879. };
  62880. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  62881. if (exponent > 0) {
  62882. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  62883. float32array[index + 0] = red * exponent;
  62884. float32array[index + 1] = green * exponent;
  62885. float32array[index + 2] = blue * exponent;
  62886. }
  62887. else {
  62888. float32array[index + 0] = 0;
  62889. float32array[index + 1] = 0;
  62890. float32array[index + 2] = 0;
  62891. }
  62892. };
  62893. HDRTools.readStringLine = function (uint8array, startIndex) {
  62894. var line = "";
  62895. var character = "";
  62896. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  62897. character = String.fromCharCode(uint8array[i]);
  62898. if (character == "\n") {
  62899. break;
  62900. }
  62901. line += character;
  62902. }
  62903. return line;
  62904. };
  62905. /**
  62906. * Reads header information from an RGBE texture stored in a native array.
  62907. * More information on this format are available here:
  62908. * https://en.wikipedia.org/wiki/RGBE_image_format
  62909. *
  62910. * @param uint8array The binary file stored in native array.
  62911. * @return The header information.
  62912. */
  62913. HDRTools.RGBE_ReadHeader = function (uint8array) {
  62914. var height = 0;
  62915. var width = 0;
  62916. var line = this.readStringLine(uint8array, 0);
  62917. if (line[0] != '#' || line[1] != '?') {
  62918. throw "Bad HDR Format.";
  62919. }
  62920. var endOfHeader = false;
  62921. var findFormat = false;
  62922. var lineIndex = 0;
  62923. do {
  62924. lineIndex += (line.length + 1);
  62925. line = this.readStringLine(uint8array, lineIndex);
  62926. if (line == "FORMAT=32-bit_rle_rgbe") {
  62927. findFormat = true;
  62928. }
  62929. else if (line.length == 0) {
  62930. endOfHeader = true;
  62931. }
  62932. } while (!endOfHeader);
  62933. if (!findFormat) {
  62934. throw "HDR Bad header format, unsupported FORMAT";
  62935. }
  62936. lineIndex += (line.length + 1);
  62937. line = this.readStringLine(uint8array, lineIndex);
  62938. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  62939. var match = sizeRegexp.exec(line);
  62940. // TODO. Support +Y and -X if needed.
  62941. if (!match || match.length < 3) {
  62942. throw "HDR Bad header format, no size";
  62943. }
  62944. width = parseInt(match[2]);
  62945. height = parseInt(match[1]);
  62946. if (width < 8 || width > 0x7fff) {
  62947. throw "HDR Bad header format, unsupported size";
  62948. }
  62949. lineIndex += (line.length + 1);
  62950. return {
  62951. height: height,
  62952. width: width,
  62953. dataPosition: lineIndex
  62954. };
  62955. };
  62956. /**
  62957. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  62958. * This RGBE texture needs to store the information as a panorama.
  62959. *
  62960. * More information on this format are available here:
  62961. * https://en.wikipedia.org/wiki/RGBE_image_format
  62962. *
  62963. * @param buffer The binary file stored in an array buffer.
  62964. * @param size The expected size of the extracted cubemap.
  62965. * @return The Cube Map information.
  62966. */
  62967. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  62968. var uint8array = new Uint8Array(buffer);
  62969. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  62970. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62971. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  62972. return cubeMapData;
  62973. };
  62974. /**
  62975. * Returns the pixels data extracted from an RGBE texture.
  62976. * This pixels will be stored left to right up to down in the R G B order in one array.
  62977. *
  62978. * More information on this format are available here:
  62979. * https://en.wikipedia.org/wiki/RGBE_image_format
  62980. *
  62981. * @param uint8array The binary file stored in an array buffer.
  62982. * @param hdrInfo The header information of the file.
  62983. * @return The pixels data in RGB right to left up to down order.
  62984. */
  62985. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  62986. // Keep for multi format supports.
  62987. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62988. };
  62989. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  62990. var num_scanlines = hdrInfo.height;
  62991. var scanline_width = hdrInfo.width;
  62992. var a, b, c, d, count;
  62993. var dataIndex = hdrInfo.dataPosition;
  62994. var index = 0, endIndex = 0, i = 0;
  62995. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  62996. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  62997. // 3 channels of 4 bytes per pixel in float.
  62998. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  62999. var resultArray = new Float32Array(resultBuffer);
  63000. // read in each successive scanline
  63001. while (num_scanlines > 0) {
  63002. a = uint8array[dataIndex++];
  63003. b = uint8array[dataIndex++];
  63004. c = uint8array[dataIndex++];
  63005. d = uint8array[dataIndex++];
  63006. if (a != 2 || b != 2 || (c & 0x80)) {
  63007. // this file is not run length encoded
  63008. throw "HDR Bad header format, not RLE";
  63009. }
  63010. if (((c << 8) | d) != scanline_width) {
  63011. throw "HDR Bad header format, wrong scan line width";
  63012. }
  63013. index = 0;
  63014. // read each of the four channels for the scanline into the buffer
  63015. for (i = 0; i < 4; i++) {
  63016. endIndex = (i + 1) * scanline_width;
  63017. while (index < endIndex) {
  63018. a = uint8array[dataIndex++];
  63019. b = uint8array[dataIndex++];
  63020. if (a > 128) {
  63021. // a run of the same value
  63022. count = a - 128;
  63023. if ((count == 0) || (count > endIndex - index)) {
  63024. throw "HDR Bad Format, bad scanline data (run)";
  63025. }
  63026. while (count-- > 0) {
  63027. scanLineArray[index++] = b;
  63028. }
  63029. }
  63030. else {
  63031. // a non-run
  63032. count = a;
  63033. if ((count == 0) || (count > endIndex - index)) {
  63034. throw "HDR Bad Format, bad scanline data (non-run)";
  63035. }
  63036. scanLineArray[index++] = b;
  63037. if (--count > 0) {
  63038. for (var j = 0; j < count; j++) {
  63039. scanLineArray[index++] = uint8array[dataIndex++];
  63040. }
  63041. }
  63042. }
  63043. }
  63044. }
  63045. // now convert data from buffer into floats
  63046. for (i = 0; i < scanline_width; i++) {
  63047. a = scanLineArray[i];
  63048. b = scanLineArray[i + scanline_width];
  63049. c = scanLineArray[i + 2 * scanline_width];
  63050. d = scanLineArray[i + 3 * scanline_width];
  63051. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  63052. }
  63053. num_scanlines--;
  63054. }
  63055. return resultArray;
  63056. };
  63057. return HDRTools;
  63058. }());
  63059. Internals.HDRTools = HDRTools;
  63060. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63061. })(BABYLON || (BABYLON = {}));
  63062. //# sourceMappingURL=babylon.hdr.js.map
  63063. var BABYLON;
  63064. (function (BABYLON) {
  63065. /**
  63066. * This represents a texture coming from an HDR input.
  63067. *
  63068. * The only supported format is currently panorama picture stored in RGBE format.
  63069. * Example of such files can be found on HDRLib: http://hdrlib.com/
  63070. */
  63071. var HDRCubeTexture = /** @class */ (function (_super) {
  63072. __extends(HDRCubeTexture, _super);
  63073. /**
  63074. * Instantiates an HDRTexture from the following parameters.
  63075. *
  63076. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  63077. * @param scene The scene the texture will be used in
  63078. * @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.
  63079. * @param noMipmap Forces to not generate the mipmap if true
  63080. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  63081. * @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)
  63082. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  63083. */
  63084. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  63085. if (noMipmap === void 0) { noMipmap = false; }
  63086. if (generateHarmonics === void 0) { generateHarmonics = true; }
  63087. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  63088. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  63089. if (onLoad === void 0) { onLoad = null; }
  63090. if (onError === void 0) { onError = null; }
  63091. var _this = _super.call(this, scene) || this;
  63092. _this._useInGammaSpace = false;
  63093. _this._generateHarmonics = true;
  63094. _this._isBABYLONPreprocessed = false;
  63095. _this._onLoad = null;
  63096. _this._onError = null;
  63097. /**
  63098. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  63099. */
  63100. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63101. /**
  63102. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  63103. * This is usefull at run time to apply the good shader.
  63104. */
  63105. _this.isPMREM = false;
  63106. _this._isBlocking = true;
  63107. if (!url) {
  63108. return _this;
  63109. }
  63110. _this.name = url;
  63111. _this.url = url;
  63112. _this.hasAlpha = false;
  63113. _this.isCube = true;
  63114. _this._textureMatrix = BABYLON.Matrix.Identity();
  63115. _this._onLoad = onLoad;
  63116. _this._onError = onError;
  63117. _this.gammaSpace = false;
  63118. var caps = scene.getEngine().getCaps();
  63119. if (size) {
  63120. _this._isBABYLONPreprocessed = false;
  63121. _this._noMipmap = noMipmap;
  63122. _this._size = size;
  63123. _this._useInGammaSpace = useInGammaSpace;
  63124. _this._usePMREMGenerator = usePMREMGenerator &&
  63125. caps.textureLOD &&
  63126. caps.textureFloat &&
  63127. !_this._useInGammaSpace;
  63128. }
  63129. else {
  63130. _this._isBABYLONPreprocessed = true;
  63131. _this._noMipmap = false;
  63132. _this._useInGammaSpace = false;
  63133. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  63134. !_this._useInGammaSpace;
  63135. }
  63136. _this.isPMREM = _this._usePMREMGenerator;
  63137. _this._texture = _this._getFromCache(url, _this._noMipmap);
  63138. if (!_this._texture) {
  63139. if (!scene.useDelayedTextureLoading) {
  63140. _this.loadTexture();
  63141. }
  63142. else {
  63143. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63144. }
  63145. }
  63146. return _this;
  63147. }
  63148. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  63149. /**
  63150. * Gets wether or not the texture is blocking during loading.
  63151. */
  63152. get: function () {
  63153. return this._isBlocking;
  63154. },
  63155. /**
  63156. * Sets wether or not the texture is blocking during loading.
  63157. */
  63158. set: function (value) {
  63159. this._isBlocking = value;
  63160. },
  63161. enumerable: true,
  63162. configurable: true
  63163. });
  63164. /**
  63165. * Occurs when the file is a preprocessed .babylon.hdr file.
  63166. */
  63167. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  63168. var _this = this;
  63169. var mipLevels = 0;
  63170. var floatArrayView = null;
  63171. var scene = this.getScene();
  63172. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  63173. var mips = new Array();
  63174. if (!floatArrayView) {
  63175. return mips;
  63176. }
  63177. var startIndex = 30;
  63178. for (var level = 0; level < mipLevels; level++) {
  63179. mips.push([]);
  63180. // Fill each pixel of the mip level.
  63181. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  63182. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63183. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  63184. mips[level].push(faceData);
  63185. startIndex += faceSize;
  63186. }
  63187. }
  63188. return mips;
  63189. } : null;
  63190. var callback = function (buffer) {
  63191. var scene = _this.getScene();
  63192. if (!scene) {
  63193. return null;
  63194. }
  63195. // Create Native Array Views
  63196. var intArrayView = new Int32Array(buffer);
  63197. floatArrayView = new Float32Array(buffer);
  63198. // Fill header.
  63199. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  63200. _this._size = intArrayView[1]; // CubeMap max mip face size.
  63201. // Update Texture Information.
  63202. if (!_this._texture) {
  63203. return null;
  63204. }
  63205. _this._texture.updateSize(_this._size, _this._size);
  63206. // Fill polynomial information.
  63207. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  63208. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  63209. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  63210. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  63211. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  63212. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  63213. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  63214. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  63215. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  63216. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  63217. _this.sphericalPolynomial = sphericalPolynomial;
  63218. // Fill pixel data.
  63219. mipLevels = intArrayView[29]; // Number of mip levels.
  63220. var startIndex = 30;
  63221. var data = [];
  63222. var faceSize = Math.pow(_this._size, 2) * 3;
  63223. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63224. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  63225. startIndex += faceSize;
  63226. }
  63227. var results = [];
  63228. var byteArray = null;
  63229. // Push each faces.
  63230. for (var k = 0; k < 6; k++) {
  63231. var dataFace = null;
  63232. // To be deprecated.
  63233. if (version === 1) {
  63234. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  63235. dataFace = data[j];
  63236. }
  63237. // If special cases.
  63238. if (!mipmapGenerator && dataFace) {
  63239. if (!scene.getEngine().getCaps().textureFloat) {
  63240. // 3 channels of 1 bytes per pixel in bytes.
  63241. var byteBuffer = new ArrayBuffer(faceSize);
  63242. byteArray = new Uint8Array(byteBuffer);
  63243. }
  63244. for (var i = 0; i < _this._size * _this._size; i++) {
  63245. // Put in gamma space if requested.
  63246. if (_this._useInGammaSpace) {
  63247. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63248. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63249. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63250. }
  63251. // Convert to int texture for fallback.
  63252. if (byteArray) {
  63253. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63254. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63255. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63256. // May use luminance instead if the result is not accurate.
  63257. var max = Math.max(Math.max(r, g), b);
  63258. if (max > 255) {
  63259. var scale = 255 / max;
  63260. r *= scale;
  63261. g *= scale;
  63262. b *= scale;
  63263. }
  63264. byteArray[(i * 3) + 0] = r;
  63265. byteArray[(i * 3) + 1] = g;
  63266. byteArray[(i * 3) + 2] = b;
  63267. }
  63268. }
  63269. }
  63270. // Fill the array accordingly.
  63271. if (byteArray) {
  63272. results.push(byteArray);
  63273. }
  63274. else {
  63275. results.push(dataFace);
  63276. }
  63277. }
  63278. return results;
  63279. };
  63280. if (scene) {
  63281. 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);
  63282. }
  63283. };
  63284. /**
  63285. * Occurs when the file is raw .hdr file.
  63286. */
  63287. HDRCubeTexture.prototype.loadHDRTexture = function () {
  63288. var _this = this;
  63289. var callback = function (buffer) {
  63290. var scene = _this.getScene();
  63291. if (!scene) {
  63292. return null;
  63293. }
  63294. // Extract the raw linear data.
  63295. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  63296. // Generate harmonics if needed.
  63297. if (_this._generateHarmonics) {
  63298. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  63299. _this.sphericalPolynomial = sphericalPolynomial;
  63300. }
  63301. var results = [];
  63302. var byteArray = null;
  63303. // Push each faces.
  63304. for (var j = 0; j < 6; j++) {
  63305. // Create uintarray fallback.
  63306. if (!scene.getEngine().getCaps().textureFloat) {
  63307. // 3 channels of 1 bytes per pixel in bytes.
  63308. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  63309. byteArray = new Uint8Array(byteBuffer);
  63310. }
  63311. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  63312. // If special cases.
  63313. if (_this._useInGammaSpace || byteArray) {
  63314. for (var i = 0; i < _this._size * _this._size; i++) {
  63315. // Put in gamma space if requested.
  63316. if (_this._useInGammaSpace) {
  63317. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63318. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63319. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63320. }
  63321. // Convert to int texture for fallback.
  63322. if (byteArray) {
  63323. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63324. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63325. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63326. // May use luminance instead if the result is not accurate.
  63327. var max = Math.max(Math.max(r, g), b);
  63328. if (max > 255) {
  63329. var scale = 255 / max;
  63330. r *= scale;
  63331. g *= scale;
  63332. b *= scale;
  63333. }
  63334. byteArray[(i * 3) + 0] = r;
  63335. byteArray[(i * 3) + 1] = g;
  63336. byteArray[(i * 3) + 2] = b;
  63337. }
  63338. }
  63339. }
  63340. if (byteArray) {
  63341. results.push(byteArray);
  63342. }
  63343. else {
  63344. results.push(dataFace);
  63345. }
  63346. }
  63347. return results;
  63348. };
  63349. var mipmapGenerator = null;
  63350. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63351. // if (!this._noMipmap &&
  63352. // this._usePMREMGenerator) {
  63353. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63354. // // Custom setup of the generator matching with the PBR shader values.
  63355. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63356. // this._size,
  63357. // this._size,
  63358. // 0,
  63359. // 3,
  63360. // this.getScene().getEngine().getCaps().textureFloat,
  63361. // 2048,
  63362. // 0.25,
  63363. // false,
  63364. // true);
  63365. // return generator.filterCubeMap();
  63366. // };
  63367. // }
  63368. var scene = this.getScene();
  63369. if (scene) {
  63370. 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);
  63371. }
  63372. };
  63373. /**
  63374. * Starts the loading process of the texture.
  63375. */
  63376. HDRCubeTexture.prototype.loadTexture = function () {
  63377. if (this._isBABYLONPreprocessed) {
  63378. this.loadBabylonTexture();
  63379. }
  63380. else {
  63381. this.loadHDRTexture();
  63382. }
  63383. };
  63384. HDRCubeTexture.prototype.clone = function () {
  63385. var scene = this.getScene();
  63386. if (!scene) {
  63387. return this;
  63388. }
  63389. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63390. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63391. // Base texture
  63392. newTexture.level = this.level;
  63393. newTexture.wrapU = this.wrapU;
  63394. newTexture.wrapV = this.wrapV;
  63395. newTexture.coordinatesIndex = this.coordinatesIndex;
  63396. newTexture.coordinatesMode = this.coordinatesMode;
  63397. return newTexture;
  63398. };
  63399. // Methods
  63400. HDRCubeTexture.prototype.delayLoad = function () {
  63401. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63402. return;
  63403. }
  63404. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63405. this._texture = this._getFromCache(this.url, this._noMipmap);
  63406. if (!this._texture) {
  63407. this.loadTexture();
  63408. }
  63409. };
  63410. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  63411. return this._textureMatrix;
  63412. };
  63413. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63414. this._textureMatrix = value;
  63415. };
  63416. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63417. var texture = null;
  63418. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63419. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  63420. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  63421. texture.name = parsedTexture.name;
  63422. texture.hasAlpha = parsedTexture.hasAlpha;
  63423. texture.level = parsedTexture.level;
  63424. texture.coordinatesMode = parsedTexture.coordinatesMode;
  63425. texture.isBlocking = parsedTexture.isBlocking;
  63426. }
  63427. return texture;
  63428. };
  63429. HDRCubeTexture.prototype.serialize = function () {
  63430. if (!this.name) {
  63431. return null;
  63432. }
  63433. var serializationObject = {};
  63434. serializationObject.name = this.name;
  63435. serializationObject.hasAlpha = this.hasAlpha;
  63436. serializationObject.isCube = true;
  63437. serializationObject.level = this.level;
  63438. serializationObject.size = this._size;
  63439. serializationObject.coordinatesMode = this.coordinatesMode;
  63440. serializationObject.useInGammaSpace = this._useInGammaSpace;
  63441. serializationObject.generateHarmonics = this._generateHarmonics;
  63442. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  63443. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  63444. serializationObject.customType = "BABYLON.HDRCubeTexture";
  63445. serializationObject.noMipmap = this._noMipmap;
  63446. serializationObject.isBlocking = this._isBlocking;
  63447. return serializationObject;
  63448. };
  63449. /**
  63450. * Saves as a file the data contained in the texture in a binary format.
  63451. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63452. * as the spherical used in the lighting.
  63453. * @param url The HDR file url.
  63454. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63455. * @param onError Method called if any error happens during download.
  63456. * @return The packed binary data.
  63457. */
  63458. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  63459. if (onError === void 0) { onError = null; }
  63460. var callback = function (buffer) {
  63461. var data = new Blob([buffer], { type: 'application/octet-stream' });
  63462. // Returns a URL you can use as a href.
  63463. var objUrl = window.URL.createObjectURL(data);
  63464. // Simulates a link to it and click to dowload.
  63465. var a = document.createElement("a");
  63466. document.body.appendChild(a);
  63467. a.style.display = "none";
  63468. a.href = objUrl;
  63469. a.download = "envmap.babylon.hdr";
  63470. a.click();
  63471. };
  63472. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  63473. };
  63474. /**
  63475. * Serializes the data contained in the texture in a binary format.
  63476. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63477. * as the spherical used in the lighting.
  63478. * @param url The HDR file url.
  63479. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63480. * @param onError Method called if any error happens during download.
  63481. * @return The packed binary data.
  63482. */
  63483. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  63484. if (onError === void 0) { onError = null; }
  63485. // Needs the url tho create the texture.
  63486. if (!url) {
  63487. return;
  63488. }
  63489. // Check Power of two size.
  63490. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  63491. return;
  63492. }
  63493. // Coming Back in 3.x.
  63494. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  63495. };
  63496. HDRCubeTexture._facesMapping = [
  63497. "right",
  63498. "left",
  63499. "up",
  63500. "down",
  63501. "front",
  63502. "back"
  63503. ];
  63504. return HDRCubeTexture;
  63505. }(BABYLON.BaseTexture));
  63506. BABYLON.HDRCubeTexture = HDRCubeTexture;
  63507. })(BABYLON || (BABYLON = {}));
  63508. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  63509. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  63510. // Huge respect for a such great lib.
  63511. // Earcut license:
  63512. // Copyright (c) 2016, Mapbox
  63513. //
  63514. // Permission to use, copy, modify, and/or distribute this software for any purpose
  63515. // with or without fee is hereby granted, provided that the above copyright notice
  63516. // and this permission notice appear in all copies.
  63517. //
  63518. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  63519. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  63520. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  63521. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  63522. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  63523. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  63524. // THIS SOFTWARE.
  63525. var Earcut;
  63526. (function (Earcut) {
  63527. /**
  63528. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  63529. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  63530. * @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).
  63531. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  63532. */
  63533. function earcut(data, holeIndices, dim) {
  63534. dim = dim || 2;
  63535. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  63536. if (!outerNode)
  63537. return triangles;
  63538. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  63539. if (hasHoles)
  63540. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  63541. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  63542. if (data.length > 80 * dim) {
  63543. minX = maxX = data[0];
  63544. minY = maxY = data[1];
  63545. for (var i = dim; i < outerLen; i += dim) {
  63546. x = data[i];
  63547. y = data[i + 1];
  63548. if (x < minX)
  63549. minX = x;
  63550. if (y < minY)
  63551. minY = y;
  63552. if (x > maxX)
  63553. maxX = x;
  63554. if (y > maxY)
  63555. maxY = y;
  63556. }
  63557. // minX, minY and size are later used to transform coords into integers for z-order calculation
  63558. size = Math.max(maxX - minX, maxY - minY);
  63559. }
  63560. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  63561. return triangles;
  63562. }
  63563. Earcut.earcut = earcut;
  63564. var Node = /** @class */ (function () {
  63565. function Node(i, x, y) {
  63566. this.i = i;
  63567. this.x = x;
  63568. this.y = y;
  63569. this.prev = null;
  63570. this.next = null;
  63571. this.z = null;
  63572. this.prevZ = null;
  63573. this.nextZ = null;
  63574. this.steiner = false;
  63575. }
  63576. return Node;
  63577. }());
  63578. // create a circular doubly linked list from polygon points in the specified winding order
  63579. function linkedList(data, start, end, dim, clockwise) {
  63580. var i, last = null;
  63581. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  63582. for (i = start; i < end; i += dim)
  63583. last = insertNode(i, data[i], data[i + 1], last);
  63584. }
  63585. else {
  63586. for (i = end - dim; i >= start; i -= dim)
  63587. last = insertNode(i, data[i], data[i + 1], last);
  63588. }
  63589. if (last && equals(last, last.next)) {
  63590. removeNode(last);
  63591. last = last.next;
  63592. }
  63593. return last;
  63594. }
  63595. // eliminate colinear or duplicate points
  63596. function filterPoints(start, end) {
  63597. if (!start)
  63598. return start;
  63599. if (!end)
  63600. end = start;
  63601. var p = start, again;
  63602. do {
  63603. again = false;
  63604. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  63605. removeNode(p);
  63606. p = end = p.prev;
  63607. if (p === p.next)
  63608. return undefined;
  63609. again = true;
  63610. }
  63611. else {
  63612. p = p.next;
  63613. }
  63614. } while (again || p !== end);
  63615. return end;
  63616. }
  63617. // main ear slicing loop which triangulates a polygon (given as a linked list)
  63618. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63619. if (!ear)
  63620. return;
  63621. // interlink polygon nodes in z-order
  63622. if (!pass && size)
  63623. indexCurve(ear, minX, minY, size);
  63624. var stop = ear, prev, next;
  63625. // iterate through ears, slicing them one by one
  63626. while (ear.prev !== ear.next) {
  63627. prev = ear.prev;
  63628. next = ear.next;
  63629. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  63630. // cut off the triangle
  63631. triangles.push(prev.i / dim);
  63632. triangles.push(ear.i / dim);
  63633. triangles.push(next.i / dim);
  63634. removeNode(ear);
  63635. // skipping the next vertice leads to less sliver triangles
  63636. ear = next.next;
  63637. stop = next.next;
  63638. continue;
  63639. }
  63640. ear = next;
  63641. // if we looped through the whole remaining polygon and can't find any more ears
  63642. if (ear === stop) {
  63643. // try filtering points and slicing again
  63644. if (!pass) {
  63645. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  63646. // if this didn't work, try curing all small self-intersections locally
  63647. }
  63648. else if (pass === 1) {
  63649. ear = cureLocalIntersections(ear, triangles, dim);
  63650. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  63651. // as a last resort, try splitting the remaining polygon into two
  63652. }
  63653. else if (pass === 2) {
  63654. splitEarcut(ear, triangles, dim, minX, minY, size);
  63655. }
  63656. break;
  63657. }
  63658. }
  63659. }
  63660. // check whether a polygon node forms a valid ear with adjacent nodes
  63661. function isEar(ear) {
  63662. var a = ear.prev, b = ear, c = ear.next;
  63663. if (area(a, b, c) >= 0)
  63664. return false; // reflex, can't be an ear
  63665. // now make sure we don't have other points inside the potential ear
  63666. var p = ear.next.next;
  63667. while (p !== ear.prev) {
  63668. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63669. area(p.prev, p, p.next) >= 0)
  63670. return false;
  63671. p = p.next;
  63672. }
  63673. return true;
  63674. }
  63675. function isEarHashed(ear, minX, minY, size) {
  63676. var a = ear.prev, b = ear, c = ear.next;
  63677. if (area(a, b, c) >= 0)
  63678. return false; // reflex, can't be an ear
  63679. // triangle bbox; min & max are calculated like this for speed
  63680. 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);
  63681. // z-order range for the current triangle bbox;
  63682. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  63683. // first look for points inside the triangle in increasing z-order
  63684. var p = ear.nextZ;
  63685. while (p && p.z <= maxZ) {
  63686. if (p !== ear.prev &&
  63687. p !== ear.next &&
  63688. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63689. area(p.prev, p, p.next) >= 0)
  63690. return false;
  63691. p = p.nextZ;
  63692. }
  63693. // then look for points in decreasing z-order
  63694. p = ear.prevZ;
  63695. while (p && p.z >= minZ) {
  63696. if (p !== ear.prev &&
  63697. p !== ear.next &&
  63698. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63699. area(p.prev, p, p.next) >= 0)
  63700. return false;
  63701. p = p.prevZ;
  63702. }
  63703. return true;
  63704. }
  63705. // go through all polygon nodes and cure small local self-intersections
  63706. function cureLocalIntersections(start, triangles, dim) {
  63707. var p = start;
  63708. do {
  63709. var a = p.prev, b = p.next.next;
  63710. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  63711. triangles.push(a.i / dim);
  63712. triangles.push(p.i / dim);
  63713. triangles.push(b.i / dim);
  63714. // remove two nodes involved
  63715. removeNode(p);
  63716. removeNode(p.next);
  63717. p = start = b;
  63718. }
  63719. p = p.next;
  63720. } while (p !== start);
  63721. return p;
  63722. }
  63723. // try splitting polygon into two and triangulate them independently
  63724. function splitEarcut(start, triangles, dim, minX, minY, size) {
  63725. // look for a valid diagonal that divides the polygon into two
  63726. var a = start;
  63727. do {
  63728. var b = a.next.next;
  63729. while (b !== a.prev) {
  63730. if (a.i !== b.i && isValidDiagonal(a, b)) {
  63731. // split the polygon in two by the diagonal
  63732. var c = splitPolygon(a, b);
  63733. // filter colinear points around the cuts
  63734. a = filterPoints(a, a.next);
  63735. c = filterPoints(c, c.next);
  63736. // run earcut on each half
  63737. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  63738. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  63739. return;
  63740. }
  63741. b = b.next;
  63742. }
  63743. a = a.next;
  63744. } while (a !== start);
  63745. }
  63746. // link every hole into the outer loop, producing a single-ring polygon without holes
  63747. function eliminateHoles(data, holeIndices, outerNode, dim) {
  63748. var queue = [], i, len, start, end, list;
  63749. for (i = 0, len = holeIndices.length; i < len; i++) {
  63750. start = holeIndices[i] * dim;
  63751. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63752. list = linkedList(data, start, end, dim, false);
  63753. if (list === list.next)
  63754. list.steiner = true;
  63755. queue.push(getLeftmost(list));
  63756. }
  63757. queue.sort(compareX);
  63758. // process holes from left to right
  63759. for (i = 0; i < queue.length; i++) {
  63760. eliminateHole(queue[i], outerNode);
  63761. outerNode = filterPoints(outerNode, outerNode.next);
  63762. }
  63763. return outerNode;
  63764. }
  63765. function compareX(a, b) {
  63766. return a.x - b.x;
  63767. }
  63768. // find a bridge between vertices that connects hole with an outer ring and and link it
  63769. function eliminateHole(hole, outerNode) {
  63770. outerNode = findHoleBridge(hole, outerNode);
  63771. if (outerNode) {
  63772. var b = splitPolygon(outerNode, hole);
  63773. filterPoints(b, b.next);
  63774. }
  63775. }
  63776. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  63777. function findHoleBridge(hole, outerNode) {
  63778. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  63779. // find a segment intersected by a ray from the hole's leftmost point to the left;
  63780. // segment's endpoint with lesser x will be potential connection point
  63781. do {
  63782. if (hy <= p.y && hy >= p.next.y) {
  63783. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  63784. if (x <= hx && x > qx) {
  63785. qx = x;
  63786. if (x === hx) {
  63787. if (hy === p.y)
  63788. return p;
  63789. if (hy === p.next.y)
  63790. return p.next;
  63791. }
  63792. m = p.x < p.next.x ? p : p.next;
  63793. }
  63794. }
  63795. p = p.next;
  63796. } while (p !== outerNode);
  63797. if (!m)
  63798. return null;
  63799. if (hx === qx)
  63800. return m.prev; // hole touches outer segment; pick lower endpoint
  63801. // look for points inside the triangle of hole point, segment intersection and endpoint;
  63802. // if there are no points found, we have a valid connection;
  63803. // otherwise choose the point of the minimum angle with the ray as connection point
  63804. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  63805. p = m.next;
  63806. while (p !== stop) {
  63807. if (hx >= p.x &&
  63808. p.x >= mx &&
  63809. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  63810. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  63811. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  63812. m = p;
  63813. tanMin = tan;
  63814. }
  63815. }
  63816. p = p.next;
  63817. }
  63818. return m;
  63819. }
  63820. // interlink polygon nodes in z-order
  63821. function indexCurve(start, minX, minY, size) {
  63822. var p = start;
  63823. do {
  63824. if (p.z === null)
  63825. p.z = zOrder(p.x, p.y, minX, minY, size);
  63826. p.prevZ = p.prev;
  63827. p.nextZ = p.next;
  63828. p = p.next;
  63829. } while (p !== start);
  63830. p.prevZ.nextZ = null;
  63831. p.prevZ = null;
  63832. sortLinked(p);
  63833. }
  63834. // Simon Tatham's linked list merge sort algorithm
  63835. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  63836. function sortLinked(list) {
  63837. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  63838. do {
  63839. p = list;
  63840. list = null;
  63841. tail = null;
  63842. numMerges = 0;
  63843. while (p) {
  63844. numMerges++;
  63845. q = p;
  63846. pSize = 0;
  63847. for (i = 0; i < inSize; i++) {
  63848. pSize++;
  63849. q = q.nextZ;
  63850. if (!q)
  63851. break;
  63852. }
  63853. qSize = inSize;
  63854. while (pSize > 0 || (qSize > 0 && q)) {
  63855. if (pSize === 0) {
  63856. e = q;
  63857. q = q.nextZ;
  63858. qSize--;
  63859. }
  63860. else if (qSize === 0 || !q) {
  63861. e = p;
  63862. p = p.nextZ;
  63863. pSize--;
  63864. }
  63865. else if (p.z <= q.z) {
  63866. e = p;
  63867. p = p.nextZ;
  63868. pSize--;
  63869. }
  63870. else {
  63871. e = q;
  63872. q = q.nextZ;
  63873. qSize--;
  63874. }
  63875. if (tail)
  63876. tail.nextZ = e;
  63877. else
  63878. list = e;
  63879. e.prevZ = tail;
  63880. tail = e;
  63881. }
  63882. p = q;
  63883. }
  63884. tail.nextZ = null;
  63885. inSize *= 2;
  63886. } while (numMerges > 1);
  63887. return list;
  63888. }
  63889. // z-order of a point given coords and size of the data bounding box
  63890. function zOrder(x, y, minX, minY, size) {
  63891. // coords are transformed into non-negative 15-bit integer range
  63892. x = 32767 * (x - minX) / size;
  63893. y = 32767 * (y - minY) / size;
  63894. x = (x | (x << 8)) & 0x00FF00FF;
  63895. x = (x | (x << 4)) & 0x0F0F0F0F;
  63896. x = (x | (x << 2)) & 0x33333333;
  63897. x = (x | (x << 1)) & 0x55555555;
  63898. y = (y | (y << 8)) & 0x00FF00FF;
  63899. y = (y | (y << 4)) & 0x0F0F0F0F;
  63900. y = (y | (y << 2)) & 0x33333333;
  63901. y = (y | (y << 1)) & 0x55555555;
  63902. return x | (y << 1);
  63903. }
  63904. // find the leftmost node of a polygon ring
  63905. function getLeftmost(start) {
  63906. var p = start, leftmost = start;
  63907. do {
  63908. if (p.x < leftmost.x)
  63909. leftmost = p;
  63910. p = p.next;
  63911. } while (p !== start);
  63912. return leftmost;
  63913. }
  63914. // check if a point lies within a convex triangle
  63915. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  63916. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  63917. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  63918. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  63919. }
  63920. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  63921. function isValidDiagonal(a, b) {
  63922. return a.next.i !== b.i &&
  63923. a.prev.i !== b.i &&
  63924. !intersectsPolygon(a, b) &&
  63925. locallyInside(a, b) &&
  63926. locallyInside(b, a) &&
  63927. middleInside(a, b);
  63928. }
  63929. // signed area of a triangle
  63930. function area(p, q, r) {
  63931. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  63932. }
  63933. // check if two points are equal
  63934. function equals(p1, p2) {
  63935. return p1.x === p2.x && p1.y === p2.y;
  63936. }
  63937. // check if two segments intersect
  63938. function intersects(p1, q1, p2, q2) {
  63939. if ((equals(p1, q1) && equals(p2, q2)) ||
  63940. (equals(p1, q2) && equals(p2, q1)))
  63941. return true;
  63942. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  63943. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  63944. }
  63945. // check if a polygon diagonal intersects any polygon segments
  63946. function intersectsPolygon(a, b) {
  63947. var p = a;
  63948. do {
  63949. if (p.i !== a.i &&
  63950. p.next.i !== a.i &&
  63951. p.i !== b.i &&
  63952. p.next.i !== b.i &&
  63953. intersects(p, p.next, a, b))
  63954. return true;
  63955. p = p.next;
  63956. } while (p !== a);
  63957. return false;
  63958. }
  63959. // check if a polygon diagonal is locally inside the polygon
  63960. function locallyInside(a, b) {
  63961. return area(a.prev, a, a.next) < 0
  63962. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  63963. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  63964. }
  63965. // check if the middle point of a polygon diagonal is inside the polygon
  63966. function middleInside(a, b) {
  63967. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  63968. do {
  63969. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  63970. inside = !inside;
  63971. p = p.next;
  63972. } while (p !== a);
  63973. return inside;
  63974. }
  63975. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  63976. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  63977. function splitPolygon(a, b) {
  63978. 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;
  63979. a.next = b;
  63980. b.prev = a;
  63981. a2.next = an;
  63982. an.prev = a2;
  63983. b2.next = a2;
  63984. a2.prev = b2;
  63985. bp.next = b2;
  63986. b2.prev = bp;
  63987. return b2;
  63988. }
  63989. // create a node and optionally link it with previous one (in a circular doubly linked list)
  63990. function insertNode(i, x, y, last) {
  63991. var p = new Node(i, x, y);
  63992. if (!last) {
  63993. p.prev = p;
  63994. p.next = p;
  63995. }
  63996. else {
  63997. p.next = last.next;
  63998. p.prev = last;
  63999. last.next.prev = p;
  64000. last.next = p;
  64001. }
  64002. return p;
  64003. }
  64004. function removeNode(p) {
  64005. p.next.prev = p.prev;
  64006. p.prev.next = p.next;
  64007. if (p.prevZ)
  64008. p.prevZ.nextZ = p.nextZ;
  64009. if (p.nextZ)
  64010. p.nextZ.prevZ = p.prevZ;
  64011. }
  64012. /**
  64013. * return a percentage difference between the polygon area and its triangulation area;
  64014. * used to verify correctness of triangulation
  64015. */
  64016. function deviation(data, holeIndices, dim, triangles) {
  64017. var hasHoles = holeIndices && holeIndices.length;
  64018. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  64019. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  64020. if (hasHoles) {
  64021. for (var i = 0, len = holeIndices.length; i < len; i++) {
  64022. var start = holeIndices[i] * dim;
  64023. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64024. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  64025. }
  64026. }
  64027. var trianglesArea = 0;
  64028. for (i = 0; i < triangles.length; i += 3) {
  64029. var a = triangles[i] * dim;
  64030. var b = triangles[i + 1] * dim;
  64031. var c = triangles[i + 2] * dim;
  64032. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  64033. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  64034. }
  64035. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  64036. }
  64037. Earcut.deviation = deviation;
  64038. ;
  64039. function signedArea(data, start, end, dim) {
  64040. var sum = 0;
  64041. for (var i = start, j = end - dim; i < end; i += dim) {
  64042. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  64043. j = i;
  64044. }
  64045. return sum;
  64046. }
  64047. /**
  64048. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  64049. */
  64050. function flatten(data) {
  64051. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  64052. for (var i = 0; i < data.length; i++) {
  64053. for (var j = 0; j < data[i].length; j++) {
  64054. for (var d = 0; d < dim; d++)
  64055. result.vertices.push(data[i][j][d]);
  64056. }
  64057. if (i > 0) {
  64058. holeIndex += data[i - 1].length;
  64059. result.holes.push(holeIndex);
  64060. }
  64061. }
  64062. return result;
  64063. }
  64064. Earcut.flatten = flatten;
  64065. ;
  64066. })(Earcut || (Earcut = {}));
  64067. //# sourceMappingURL=babylon.earcut.js.map
  64068. var BABYLON;
  64069. (function (BABYLON) {
  64070. var IndexedVector2 = /** @class */ (function (_super) {
  64071. __extends(IndexedVector2, _super);
  64072. function IndexedVector2(original, index) {
  64073. var _this = _super.call(this, original.x, original.y) || this;
  64074. _this.index = index;
  64075. return _this;
  64076. }
  64077. return IndexedVector2;
  64078. }(BABYLON.Vector2));
  64079. var PolygonPoints = /** @class */ (function () {
  64080. function PolygonPoints() {
  64081. this.elements = new Array();
  64082. }
  64083. PolygonPoints.prototype.add = function (originalPoints) {
  64084. var _this = this;
  64085. var result = new Array();
  64086. originalPoints.forEach(function (point) {
  64087. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  64088. var newPoint = new IndexedVector2(point, _this.elements.length);
  64089. result.push(newPoint);
  64090. _this.elements.push(newPoint);
  64091. }
  64092. });
  64093. return result;
  64094. };
  64095. PolygonPoints.prototype.computeBounds = function () {
  64096. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64097. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64098. this.elements.forEach(function (point) {
  64099. // x
  64100. if (point.x < lmin.x) {
  64101. lmin.x = point.x;
  64102. }
  64103. else if (point.x > lmax.x) {
  64104. lmax.x = point.x;
  64105. }
  64106. // y
  64107. if (point.y < lmin.y) {
  64108. lmin.y = point.y;
  64109. }
  64110. else if (point.y > lmax.y) {
  64111. lmax.y = point.y;
  64112. }
  64113. });
  64114. return {
  64115. min: lmin,
  64116. max: lmax,
  64117. width: lmax.x - lmin.x,
  64118. height: lmax.y - lmin.y
  64119. };
  64120. };
  64121. return PolygonPoints;
  64122. }());
  64123. var Polygon = /** @class */ (function () {
  64124. function Polygon() {
  64125. }
  64126. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  64127. return [
  64128. new BABYLON.Vector2(xmin, ymin),
  64129. new BABYLON.Vector2(xmax, ymin),
  64130. new BABYLON.Vector2(xmax, ymax),
  64131. new BABYLON.Vector2(xmin, ymax)
  64132. ];
  64133. };
  64134. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  64135. if (cx === void 0) { cx = 0; }
  64136. if (cy === void 0) { cy = 0; }
  64137. if (numberOfSides === void 0) { numberOfSides = 32; }
  64138. var result = new Array();
  64139. var angle = 0;
  64140. var increment = (Math.PI * 2) / numberOfSides;
  64141. for (var i = 0; i < numberOfSides; i++) {
  64142. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  64143. angle -= increment;
  64144. }
  64145. return result;
  64146. };
  64147. Polygon.Parse = function (input) {
  64148. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  64149. var i, result = [];
  64150. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  64151. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  64152. }
  64153. return result;
  64154. };
  64155. Polygon.StartingAt = function (x, y) {
  64156. return BABYLON.Path2.StartingAt(x, y);
  64157. };
  64158. return Polygon;
  64159. }());
  64160. BABYLON.Polygon = Polygon;
  64161. var PolygonMeshBuilder = /** @class */ (function () {
  64162. function PolygonMeshBuilder(name, contours, scene) {
  64163. this._points = new PolygonPoints();
  64164. this._outlinepoints = new PolygonPoints();
  64165. this._holes = new Array();
  64166. this._epoints = new Array();
  64167. this._eholes = new Array();
  64168. this._name = name;
  64169. this._scene = scene;
  64170. var points;
  64171. if (contours instanceof BABYLON.Path2) {
  64172. points = contours.getPoints();
  64173. }
  64174. else {
  64175. points = contours;
  64176. }
  64177. this._addToepoint(points);
  64178. this._points.add(points);
  64179. this._outlinepoints.add(points);
  64180. }
  64181. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  64182. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  64183. var p = points_1[_i];
  64184. this._epoints.push(p.x, p.y);
  64185. }
  64186. };
  64187. PolygonMeshBuilder.prototype.addHole = function (hole) {
  64188. this._points.add(hole);
  64189. var holepoints = new PolygonPoints();
  64190. holepoints.add(hole);
  64191. this._holes.push(holepoints);
  64192. this._eholes.push(this._epoints.length / 2);
  64193. this._addToepoint(hole);
  64194. return this;
  64195. };
  64196. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  64197. var _this = this;
  64198. if (updatable === void 0) { updatable = false; }
  64199. if (depth === void 0) { depth = 0; }
  64200. var result = new BABYLON.Mesh(this._name, this._scene);
  64201. var normals = new Array();
  64202. var positions = new Array();
  64203. var uvs = new Array();
  64204. var bounds = this._points.computeBounds();
  64205. this._points.elements.forEach(function (p) {
  64206. normals.push(0, 1.0, 0);
  64207. positions.push(p.x, 0, p.y);
  64208. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  64209. });
  64210. var indices = new Array();
  64211. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  64212. for (var i = 0; i < res.length; i++) {
  64213. indices.push(res[i]);
  64214. }
  64215. if (depth > 0) {
  64216. var positionscount = (positions.length / 3); //get the current pointcount
  64217. this._points.elements.forEach(function (p) {
  64218. normals.push(0, -1.0, 0);
  64219. positions.push(p.x, -depth, p.y);
  64220. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  64221. });
  64222. var totalCount = indices.length;
  64223. for (var i = 0; i < totalCount; i += 3) {
  64224. var i0 = indices[i + 0];
  64225. var i1 = indices[i + 1];
  64226. var i2 = indices[i + 2];
  64227. indices.push(i2 + positionscount);
  64228. indices.push(i1 + positionscount);
  64229. indices.push(i0 + positionscount);
  64230. }
  64231. //Add the sides
  64232. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  64233. this._holes.forEach(function (hole) {
  64234. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  64235. });
  64236. }
  64237. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  64238. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  64239. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  64240. result.setIndices(indices);
  64241. return result;
  64242. };
  64243. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  64244. var StartIndex = positions.length / 3;
  64245. var ulength = 0;
  64246. for (var i = 0; i < points.elements.length; i++) {
  64247. var p = points.elements[i];
  64248. var p1;
  64249. if ((i + 1) > points.elements.length - 1) {
  64250. p1 = points.elements[0];
  64251. }
  64252. else {
  64253. p1 = points.elements[i + 1];
  64254. }
  64255. positions.push(p.x, 0, p.y);
  64256. positions.push(p.x, -depth, p.y);
  64257. positions.push(p1.x, 0, p1.y);
  64258. positions.push(p1.x, -depth, p1.y);
  64259. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  64260. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  64261. var v3 = v2.subtract(v1);
  64262. var v4 = new BABYLON.Vector3(0, 1, 0);
  64263. var vn = BABYLON.Vector3.Cross(v3, v4);
  64264. vn = vn.normalize();
  64265. uvs.push(ulength / bounds.width, 0);
  64266. uvs.push(ulength / bounds.width, 1);
  64267. ulength += v3.length();
  64268. uvs.push((ulength / bounds.width), 0);
  64269. uvs.push((ulength / bounds.width), 1);
  64270. if (!flip) {
  64271. normals.push(-vn.x, -vn.y, -vn.z);
  64272. normals.push(-vn.x, -vn.y, -vn.z);
  64273. normals.push(-vn.x, -vn.y, -vn.z);
  64274. normals.push(-vn.x, -vn.y, -vn.z);
  64275. indices.push(StartIndex);
  64276. indices.push(StartIndex + 1);
  64277. indices.push(StartIndex + 2);
  64278. indices.push(StartIndex + 1);
  64279. indices.push(StartIndex + 3);
  64280. indices.push(StartIndex + 2);
  64281. }
  64282. else {
  64283. normals.push(vn.x, vn.y, vn.z);
  64284. normals.push(vn.x, vn.y, vn.z);
  64285. normals.push(vn.x, vn.y, vn.z);
  64286. normals.push(vn.x, vn.y, vn.z);
  64287. indices.push(StartIndex);
  64288. indices.push(StartIndex + 2);
  64289. indices.push(StartIndex + 1);
  64290. indices.push(StartIndex + 1);
  64291. indices.push(StartIndex + 2);
  64292. indices.push(StartIndex + 3);
  64293. }
  64294. StartIndex += 4;
  64295. }
  64296. ;
  64297. };
  64298. return PolygonMeshBuilder;
  64299. }());
  64300. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  64301. })(BABYLON || (BABYLON = {}));
  64302. //# sourceMappingURL=babylon.polygonMesh.js.map
  64303. var BABYLON;
  64304. (function (BABYLON) {
  64305. // Unique ID when we import meshes from Babylon to CSG
  64306. var currentCSGMeshId = 0;
  64307. // # class Vertex
  64308. // Represents a vertex of a polygon. Use your own vertex class instead of this
  64309. // one to provide additional features like texture coordinates and vertex
  64310. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  64311. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  64312. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  64313. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  64314. // is not used anywhere else.
  64315. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  64316. var Vertex = /** @class */ (function () {
  64317. function Vertex(pos, normal, uv) {
  64318. this.pos = pos;
  64319. this.normal = normal;
  64320. this.uv = uv;
  64321. }
  64322. Vertex.prototype.clone = function () {
  64323. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  64324. };
  64325. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  64326. // orientation of a polygon is flipped.
  64327. Vertex.prototype.flip = function () {
  64328. this.normal = this.normal.scale(-1);
  64329. };
  64330. // Create a new vertex between this vertex and `other` by linearly
  64331. // interpolating all properties using a parameter of `t`. Subclasses should
  64332. // override this to interpolate additional properties.
  64333. Vertex.prototype.interpolate = function (other, t) {
  64334. 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));
  64335. };
  64336. return Vertex;
  64337. }());
  64338. // # class Plane
  64339. // Represents a plane in 3D space.
  64340. var Plane = /** @class */ (function () {
  64341. function Plane(normal, w) {
  64342. this.normal = normal;
  64343. this.w = w;
  64344. }
  64345. Plane.FromPoints = function (a, b, c) {
  64346. var v0 = c.subtract(a);
  64347. var v1 = b.subtract(a);
  64348. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64349. return null;
  64350. }
  64351. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64352. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64353. };
  64354. Plane.prototype.clone = function () {
  64355. return new Plane(this.normal.clone(), this.w);
  64356. };
  64357. Plane.prototype.flip = function () {
  64358. this.normal.scaleInPlace(-1);
  64359. this.w = -this.w;
  64360. };
  64361. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64362. // fragments in the appropriate lists. Coplanar polygons go into either
  64363. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64364. // respect to this plane. Polygons in front or in back of this plane go into
  64365. // either `front` or `back`.
  64366. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64367. var COPLANAR = 0;
  64368. var FRONT = 1;
  64369. var BACK = 2;
  64370. var SPANNING = 3;
  64371. // Classify each point as well as the entire polygon into one of the above
  64372. // four classes.
  64373. var polygonType = 0;
  64374. var types = [];
  64375. var i;
  64376. var t;
  64377. for (i = 0; i < polygon.vertices.length; i++) {
  64378. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64379. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64380. polygonType |= type;
  64381. types.push(type);
  64382. }
  64383. // Put the polygon in the correct list, splitting it when necessary.
  64384. switch (polygonType) {
  64385. case COPLANAR:
  64386. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64387. break;
  64388. case FRONT:
  64389. front.push(polygon);
  64390. break;
  64391. case BACK:
  64392. back.push(polygon);
  64393. break;
  64394. case SPANNING:
  64395. var f = [], b = [];
  64396. for (i = 0; i < polygon.vertices.length; i++) {
  64397. var j = (i + 1) % polygon.vertices.length;
  64398. var ti = types[i], tj = types[j];
  64399. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64400. if (ti !== BACK)
  64401. f.push(vi);
  64402. if (ti !== FRONT)
  64403. b.push(ti !== BACK ? vi.clone() : vi);
  64404. if ((ti | tj) === SPANNING) {
  64405. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  64406. var v = vi.interpolate(vj, t);
  64407. f.push(v);
  64408. b.push(v.clone());
  64409. }
  64410. }
  64411. var poly;
  64412. if (f.length >= 3) {
  64413. poly = new Polygon(f, polygon.shared);
  64414. if (poly.plane)
  64415. front.push(poly);
  64416. }
  64417. if (b.length >= 3) {
  64418. poly = new Polygon(b, polygon.shared);
  64419. if (poly.plane)
  64420. back.push(poly);
  64421. }
  64422. break;
  64423. }
  64424. };
  64425. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  64426. // point is on the plane.
  64427. Plane.EPSILON = 1e-5;
  64428. return Plane;
  64429. }());
  64430. // # class Polygon
  64431. // Represents a convex polygon. The vertices used to initialize a polygon must
  64432. // be coplanar and form a convex loop.
  64433. //
  64434. // Each convex polygon has a `shared` property, which is shared between all
  64435. // polygons that are clones of each other or were split from the same polygon.
  64436. // This can be used to define per-polygon properties (such as surface color).
  64437. var Polygon = /** @class */ (function () {
  64438. function Polygon(vertices, shared) {
  64439. this.vertices = vertices;
  64440. this.shared = shared;
  64441. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  64442. }
  64443. Polygon.prototype.clone = function () {
  64444. var vertices = this.vertices.map(function (v) { return v.clone(); });
  64445. return new Polygon(vertices, this.shared);
  64446. };
  64447. Polygon.prototype.flip = function () {
  64448. this.vertices.reverse().map(function (v) { v.flip(); });
  64449. this.plane.flip();
  64450. };
  64451. return Polygon;
  64452. }());
  64453. // # class Node
  64454. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  64455. // by picking a polygon to split along. That polygon (and all other coplanar
  64456. // polygons) are added directly to that node and the other polygons are added to
  64457. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  64458. // no distinction between internal and leaf nodes.
  64459. var Node = /** @class */ (function () {
  64460. function Node(polygons) {
  64461. this.plane = null;
  64462. this.front = null;
  64463. this.back = null;
  64464. this.polygons = new Array();
  64465. if (polygons) {
  64466. this.build(polygons);
  64467. }
  64468. }
  64469. Node.prototype.clone = function () {
  64470. var node = new Node();
  64471. node.plane = this.plane && this.plane.clone();
  64472. node.front = this.front && this.front.clone();
  64473. node.back = this.back && this.back.clone();
  64474. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  64475. return node;
  64476. };
  64477. // Convert solid space to empty space and empty space to solid space.
  64478. Node.prototype.invert = function () {
  64479. for (var i = 0; i < this.polygons.length; i++) {
  64480. this.polygons[i].flip();
  64481. }
  64482. if (this.plane) {
  64483. this.plane.flip();
  64484. }
  64485. if (this.front) {
  64486. this.front.invert();
  64487. }
  64488. if (this.back) {
  64489. this.back.invert();
  64490. }
  64491. var temp = this.front;
  64492. this.front = this.back;
  64493. this.back = temp;
  64494. };
  64495. // Recursively remove all polygons in `polygons` that are inside this BSP
  64496. // tree.
  64497. Node.prototype.clipPolygons = function (polygons) {
  64498. if (!this.plane)
  64499. return polygons.slice();
  64500. var front = new Array(), back = new Array();
  64501. for (var i = 0; i < polygons.length; i++) {
  64502. this.plane.splitPolygon(polygons[i], front, back, front, back);
  64503. }
  64504. if (this.front) {
  64505. front = this.front.clipPolygons(front);
  64506. }
  64507. if (this.back) {
  64508. back = this.back.clipPolygons(back);
  64509. }
  64510. else {
  64511. back = [];
  64512. }
  64513. return front.concat(back);
  64514. };
  64515. // Remove all polygons in this BSP tree that are inside the other BSP tree
  64516. // `bsp`.
  64517. Node.prototype.clipTo = function (bsp) {
  64518. this.polygons = bsp.clipPolygons(this.polygons);
  64519. if (this.front)
  64520. this.front.clipTo(bsp);
  64521. if (this.back)
  64522. this.back.clipTo(bsp);
  64523. };
  64524. // Return a list of all polygons in this BSP tree.
  64525. Node.prototype.allPolygons = function () {
  64526. var polygons = this.polygons.slice();
  64527. if (this.front)
  64528. polygons = polygons.concat(this.front.allPolygons());
  64529. if (this.back)
  64530. polygons = polygons.concat(this.back.allPolygons());
  64531. return polygons;
  64532. };
  64533. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  64534. // new polygons are filtered down to the bottom of the tree and become new
  64535. // nodes there. Each set of polygons is partitioned using the first polygon
  64536. // (no heuristic is used to pick a good split).
  64537. Node.prototype.build = function (polygons) {
  64538. if (!polygons.length)
  64539. return;
  64540. if (!this.plane)
  64541. this.plane = polygons[0].plane.clone();
  64542. var front = new Array(), back = new Array();
  64543. for (var i = 0; i < polygons.length; i++) {
  64544. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  64545. }
  64546. if (front.length) {
  64547. if (!this.front)
  64548. this.front = new Node();
  64549. this.front.build(front);
  64550. }
  64551. if (back.length) {
  64552. if (!this.back)
  64553. this.back = new Node();
  64554. this.back.build(back);
  64555. }
  64556. };
  64557. return Node;
  64558. }());
  64559. var CSG = /** @class */ (function () {
  64560. function CSG() {
  64561. this.polygons = new Array();
  64562. }
  64563. // Convert BABYLON.Mesh to BABYLON.CSG
  64564. CSG.FromMesh = function (mesh) {
  64565. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  64566. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  64567. if (mesh instanceof BABYLON.Mesh) {
  64568. mesh.computeWorldMatrix(true);
  64569. matrix = mesh.getWorldMatrix();
  64570. meshPosition = mesh.position.clone();
  64571. meshRotation = mesh.rotation.clone();
  64572. if (mesh.rotationQuaternion) {
  64573. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  64574. }
  64575. meshScaling = mesh.scaling.clone();
  64576. }
  64577. else {
  64578. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  64579. }
  64580. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64581. var subMeshes = mesh.subMeshes;
  64582. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  64583. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  64584. vertices = [];
  64585. for (var j = 0; j < 3; j++) {
  64586. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  64587. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  64588. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  64589. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  64590. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  64591. vertex = new Vertex(position, normal, uv);
  64592. vertices.push(vertex);
  64593. }
  64594. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  64595. // To handle the case of degenerated triangle
  64596. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  64597. if (polygon.plane)
  64598. polygons.push(polygon);
  64599. }
  64600. }
  64601. var csg = CSG.FromPolygons(polygons);
  64602. csg.matrix = matrix;
  64603. csg.position = meshPosition;
  64604. csg.rotation = meshRotation;
  64605. csg.scaling = meshScaling;
  64606. csg.rotationQuaternion = meshRotationQuaternion;
  64607. currentCSGMeshId++;
  64608. return csg;
  64609. };
  64610. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  64611. CSG.FromPolygons = function (polygons) {
  64612. var csg = new CSG();
  64613. csg.polygons = polygons;
  64614. return csg;
  64615. };
  64616. CSG.prototype.clone = function () {
  64617. var csg = new CSG();
  64618. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  64619. csg.copyTransformAttributes(this);
  64620. return csg;
  64621. };
  64622. CSG.prototype.union = function (csg) {
  64623. var a = new Node(this.clone().polygons);
  64624. var b = new Node(csg.clone().polygons);
  64625. a.clipTo(b);
  64626. b.clipTo(a);
  64627. b.invert();
  64628. b.clipTo(a);
  64629. b.invert();
  64630. a.build(b.allPolygons());
  64631. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64632. };
  64633. CSG.prototype.unionInPlace = function (csg) {
  64634. var a = new Node(this.polygons);
  64635. var b = new Node(csg.polygons);
  64636. a.clipTo(b);
  64637. b.clipTo(a);
  64638. b.invert();
  64639. b.clipTo(a);
  64640. b.invert();
  64641. a.build(b.allPolygons());
  64642. this.polygons = a.allPolygons();
  64643. };
  64644. CSG.prototype.subtract = function (csg) {
  64645. var a = new Node(this.clone().polygons);
  64646. var b = new Node(csg.clone().polygons);
  64647. a.invert();
  64648. a.clipTo(b);
  64649. b.clipTo(a);
  64650. b.invert();
  64651. b.clipTo(a);
  64652. b.invert();
  64653. a.build(b.allPolygons());
  64654. a.invert();
  64655. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64656. };
  64657. CSG.prototype.subtractInPlace = function (csg) {
  64658. var a = new Node(this.polygons);
  64659. var b = new Node(csg.polygons);
  64660. a.invert();
  64661. a.clipTo(b);
  64662. b.clipTo(a);
  64663. b.invert();
  64664. b.clipTo(a);
  64665. b.invert();
  64666. a.build(b.allPolygons());
  64667. a.invert();
  64668. this.polygons = a.allPolygons();
  64669. };
  64670. CSG.prototype.intersect = function (csg) {
  64671. var a = new Node(this.clone().polygons);
  64672. var b = new Node(csg.clone().polygons);
  64673. a.invert();
  64674. b.clipTo(a);
  64675. b.invert();
  64676. a.clipTo(b);
  64677. b.clipTo(a);
  64678. a.build(b.allPolygons());
  64679. a.invert();
  64680. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64681. };
  64682. CSG.prototype.intersectInPlace = function (csg) {
  64683. var a = new Node(this.polygons);
  64684. var b = new Node(csg.polygons);
  64685. a.invert();
  64686. b.clipTo(a);
  64687. b.invert();
  64688. a.clipTo(b);
  64689. b.clipTo(a);
  64690. a.build(b.allPolygons());
  64691. a.invert();
  64692. this.polygons = a.allPolygons();
  64693. };
  64694. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  64695. // not modified.
  64696. CSG.prototype.inverse = function () {
  64697. var csg = this.clone();
  64698. csg.inverseInPlace();
  64699. return csg;
  64700. };
  64701. CSG.prototype.inverseInPlace = function () {
  64702. this.polygons.map(function (p) { p.flip(); });
  64703. };
  64704. // This is used to keep meshes transformations so they can be restored
  64705. // when we build back a Babylon Mesh
  64706. // NB : All CSG operations are performed in world coordinates
  64707. CSG.prototype.copyTransformAttributes = function (csg) {
  64708. this.matrix = csg.matrix;
  64709. this.position = csg.position;
  64710. this.rotation = csg.rotation;
  64711. this.scaling = csg.scaling;
  64712. this.rotationQuaternion = csg.rotationQuaternion;
  64713. return this;
  64714. };
  64715. // Build Raw mesh from CSG
  64716. // Coordinates here are in world space
  64717. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  64718. var matrix = this.matrix.clone();
  64719. matrix.invert();
  64720. 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;
  64721. if (keepSubMeshes) {
  64722. // Sort Polygons, since subMeshes are indices range
  64723. polygons.sort(function (a, b) {
  64724. if (a.shared.meshId === b.shared.meshId) {
  64725. return a.shared.subMeshId - b.shared.subMeshId;
  64726. }
  64727. else {
  64728. return a.shared.meshId - b.shared.meshId;
  64729. }
  64730. });
  64731. }
  64732. for (var i = 0, il = polygons.length; i < il; i++) {
  64733. polygon = polygons[i];
  64734. // Building SubMeshes
  64735. if (!subMesh_dict[polygon.shared.meshId]) {
  64736. subMesh_dict[polygon.shared.meshId] = {};
  64737. }
  64738. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  64739. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  64740. indexStart: +Infinity,
  64741. indexEnd: -Infinity,
  64742. materialIndex: polygon.shared.materialIndex
  64743. };
  64744. }
  64745. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  64746. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  64747. polygonIndices[0] = 0;
  64748. polygonIndices[1] = j - 1;
  64749. polygonIndices[2] = j;
  64750. for (var k = 0; k < 3; k++) {
  64751. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  64752. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  64753. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  64754. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  64755. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  64756. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  64757. // Check if 2 points can be merged
  64758. if (!(typeof vertex_idx !== 'undefined' &&
  64759. normals[vertex_idx * 3] === localNormal.x &&
  64760. normals[vertex_idx * 3 + 1] === localNormal.y &&
  64761. normals[vertex_idx * 3 + 2] === localNormal.z &&
  64762. uvs[vertex_idx * 2] === uv.x &&
  64763. uvs[vertex_idx * 2 + 1] === uv.y)) {
  64764. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  64765. uvs.push(uv.x, uv.y);
  64766. normals.push(normal.x, normal.y, normal.z);
  64767. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  64768. }
  64769. indices.push(vertex_idx);
  64770. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  64771. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  64772. currentIndex++;
  64773. }
  64774. }
  64775. }
  64776. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  64777. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  64778. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  64779. mesh.setIndices(indices, null);
  64780. if (keepSubMeshes) {
  64781. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  64782. var materialIndexOffset = 0, materialMaxIndex;
  64783. mesh.subMeshes = new Array();
  64784. for (var m in subMesh_dict) {
  64785. materialMaxIndex = -1;
  64786. for (var sm in subMesh_dict[m]) {
  64787. subMesh_obj = subMesh_dict[m][sm];
  64788. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  64789. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  64790. }
  64791. materialIndexOffset += ++materialMaxIndex;
  64792. }
  64793. }
  64794. return mesh;
  64795. };
  64796. // Build Mesh from CSG taking material and transforms into account
  64797. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  64798. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  64799. mesh.material = material;
  64800. mesh.position.copyFrom(this.position);
  64801. mesh.rotation.copyFrom(this.rotation);
  64802. if (this.rotationQuaternion) {
  64803. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  64804. }
  64805. mesh.scaling.copyFrom(this.scaling);
  64806. mesh.computeWorldMatrix(true);
  64807. return mesh;
  64808. };
  64809. return CSG;
  64810. }());
  64811. BABYLON.CSG = CSG;
  64812. })(BABYLON || (BABYLON = {}));
  64813. //# sourceMappingURL=babylon.csg.js.map
  64814. var BABYLON;
  64815. (function (BABYLON) {
  64816. var LensFlare = /** @class */ (function () {
  64817. function LensFlare(size, position, color, imgUrl, system) {
  64818. this.size = size;
  64819. this.position = position;
  64820. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  64821. this.color = color || new BABYLON.Color3(1, 1, 1);
  64822. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  64823. this._system = system;
  64824. system.lensFlares.push(this);
  64825. }
  64826. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  64827. return new LensFlare(size, position, color, imgUrl, system);
  64828. };
  64829. LensFlare.prototype.dispose = function () {
  64830. if (this.texture) {
  64831. this.texture.dispose();
  64832. }
  64833. // Remove from scene
  64834. var index = this._system.lensFlares.indexOf(this);
  64835. this._system.lensFlares.splice(index, 1);
  64836. };
  64837. ;
  64838. return LensFlare;
  64839. }());
  64840. BABYLON.LensFlare = LensFlare;
  64841. })(BABYLON || (BABYLON = {}));
  64842. //# sourceMappingURL=babylon.lensFlare.js.map
  64843. var BABYLON;
  64844. (function (BABYLON) {
  64845. var LensFlareSystem = /** @class */ (function () {
  64846. function LensFlareSystem(name, emitter, scene) {
  64847. this.name = name;
  64848. this.lensFlares = new Array();
  64849. this.borderLimit = 300;
  64850. this.viewportBorder = 0;
  64851. this.layerMask = 0x0FFFFFFF;
  64852. this._vertexBuffers = {};
  64853. this._isEnabled = true;
  64854. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64855. this._emitter = emitter;
  64856. this.id = name;
  64857. scene.lensFlareSystems.push(this);
  64858. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  64859. var engine = scene.getEngine();
  64860. // VBO
  64861. var vertices = [];
  64862. vertices.push(1, 1);
  64863. vertices.push(-1, 1);
  64864. vertices.push(-1, -1);
  64865. vertices.push(1, -1);
  64866. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64867. // Indices
  64868. var indices = [];
  64869. indices.push(0);
  64870. indices.push(1);
  64871. indices.push(2);
  64872. indices.push(0);
  64873. indices.push(2);
  64874. indices.push(3);
  64875. this._indexBuffer = engine.createIndexBuffer(indices);
  64876. // Effects
  64877. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  64878. }
  64879. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  64880. get: function () {
  64881. return this._isEnabled;
  64882. },
  64883. set: function (value) {
  64884. this._isEnabled = value;
  64885. },
  64886. enumerable: true,
  64887. configurable: true
  64888. });
  64889. LensFlareSystem.prototype.getScene = function () {
  64890. return this._scene;
  64891. };
  64892. LensFlareSystem.prototype.getEmitter = function () {
  64893. return this._emitter;
  64894. };
  64895. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  64896. this._emitter = newEmitter;
  64897. };
  64898. LensFlareSystem.prototype.getEmitterPosition = function () {
  64899. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  64900. };
  64901. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  64902. var position = this.getEmitterPosition();
  64903. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  64904. this._positionX = position.x;
  64905. this._positionY = position.y;
  64906. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  64907. if (this.viewportBorder > 0) {
  64908. globalViewport.x -= this.viewportBorder;
  64909. globalViewport.y -= this.viewportBorder;
  64910. globalViewport.width += this.viewportBorder * 2;
  64911. globalViewport.height += this.viewportBorder * 2;
  64912. position.x += this.viewportBorder;
  64913. position.y += this.viewportBorder;
  64914. this._positionX += this.viewportBorder;
  64915. this._positionY += this.viewportBorder;
  64916. }
  64917. if (position.z > 0) {
  64918. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  64919. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  64920. return true;
  64921. }
  64922. return true;
  64923. }
  64924. return false;
  64925. };
  64926. LensFlareSystem.prototype._isVisible = function () {
  64927. if (!this._isEnabled || !this._scene.activeCamera) {
  64928. return false;
  64929. }
  64930. var emitterPosition = this.getEmitterPosition();
  64931. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  64932. var distance = direction.length();
  64933. direction.normalize();
  64934. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  64935. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  64936. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  64937. };
  64938. LensFlareSystem.prototype.render = function () {
  64939. if (!this._effect.isReady() || !this._scene.activeCamera)
  64940. return false;
  64941. var engine = this._scene.getEngine();
  64942. var viewport = this._scene.activeCamera.viewport;
  64943. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  64944. // Position
  64945. if (!this.computeEffectivePosition(globalViewport)) {
  64946. return false;
  64947. }
  64948. // Visibility
  64949. if (!this._isVisible()) {
  64950. return false;
  64951. }
  64952. // Intensity
  64953. var awayX;
  64954. var awayY;
  64955. if (this._positionX < this.borderLimit + globalViewport.x) {
  64956. awayX = this.borderLimit + globalViewport.x - this._positionX;
  64957. }
  64958. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  64959. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  64960. }
  64961. else {
  64962. awayX = 0;
  64963. }
  64964. if (this._positionY < this.borderLimit + globalViewport.y) {
  64965. awayY = this.borderLimit + globalViewport.y - this._positionY;
  64966. }
  64967. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  64968. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  64969. }
  64970. else {
  64971. awayY = 0;
  64972. }
  64973. var away = (awayX > awayY) ? awayX : awayY;
  64974. away -= this.viewportBorder;
  64975. if (away > this.borderLimit) {
  64976. away = this.borderLimit;
  64977. }
  64978. var intensity = 1.0 - (away / this.borderLimit);
  64979. if (intensity < 0) {
  64980. return false;
  64981. }
  64982. if (intensity > 1.0) {
  64983. intensity = 1.0;
  64984. }
  64985. if (this.viewportBorder > 0) {
  64986. globalViewport.x += this.viewportBorder;
  64987. globalViewport.y += this.viewportBorder;
  64988. globalViewport.width -= this.viewportBorder * 2;
  64989. globalViewport.height -= this.viewportBorder * 2;
  64990. this._positionX -= this.viewportBorder;
  64991. this._positionY -= this.viewportBorder;
  64992. }
  64993. // Position
  64994. var centerX = globalViewport.x + globalViewport.width / 2;
  64995. var centerY = globalViewport.y + globalViewport.height / 2;
  64996. var distX = centerX - this._positionX;
  64997. var distY = centerY - this._positionY;
  64998. // Effects
  64999. engine.enableEffect(this._effect);
  65000. engine.setState(false);
  65001. engine.setDepthBuffer(false);
  65002. // VBOs
  65003. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65004. // Flares
  65005. for (var index = 0; index < this.lensFlares.length; index++) {
  65006. var flare = this.lensFlares[index];
  65007. engine.setAlphaMode(flare.alphaMode);
  65008. var x = centerX - (distX * flare.position);
  65009. var y = centerY - (distY * flare.position);
  65010. var cw = flare.size;
  65011. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  65012. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  65013. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  65014. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  65015. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  65016. // Texture
  65017. this._effect.setTexture("textureSampler", flare.texture);
  65018. // Color
  65019. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  65020. // Draw order
  65021. engine.draw(true, 0, 6);
  65022. }
  65023. engine.setDepthBuffer(true);
  65024. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65025. return true;
  65026. };
  65027. LensFlareSystem.prototype.dispose = function () {
  65028. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65029. if (vertexBuffer) {
  65030. vertexBuffer.dispose();
  65031. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65032. }
  65033. if (this._indexBuffer) {
  65034. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65035. this._indexBuffer = null;
  65036. }
  65037. while (this.lensFlares.length) {
  65038. this.lensFlares[0].dispose();
  65039. }
  65040. // Remove from scene
  65041. var index = this._scene.lensFlareSystems.indexOf(this);
  65042. this._scene.lensFlareSystems.splice(index, 1);
  65043. };
  65044. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  65045. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  65046. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  65047. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  65048. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  65049. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  65050. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  65051. var parsedFlare = parsedLensFlareSystem.flares[index];
  65052. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  65053. }
  65054. return lensFlareSystem;
  65055. };
  65056. LensFlareSystem.prototype.serialize = function () {
  65057. var serializationObject = {};
  65058. serializationObject.id = this.id;
  65059. serializationObject.name = this.name;
  65060. serializationObject.emitterId = this.getEmitter().id;
  65061. serializationObject.borderLimit = this.borderLimit;
  65062. serializationObject.flares = [];
  65063. for (var index = 0; index < this.lensFlares.length; index++) {
  65064. var flare = this.lensFlares[index];
  65065. serializationObject.flares.push({
  65066. size: flare.size,
  65067. position: flare.position,
  65068. color: flare.color.asArray(),
  65069. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  65070. });
  65071. }
  65072. return serializationObject;
  65073. };
  65074. return LensFlareSystem;
  65075. }());
  65076. BABYLON.LensFlareSystem = LensFlareSystem;
  65077. })(BABYLON || (BABYLON = {}));
  65078. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  65079. var BABYLON;
  65080. (function (BABYLON) {
  65081. /**
  65082. * This is a holder class for the physics joint created by the physics plugin.
  65083. * It holds a set of functions to control the underlying joint.
  65084. */
  65085. var PhysicsJoint = /** @class */ (function () {
  65086. function PhysicsJoint(type, jointData) {
  65087. this.type = type;
  65088. this.jointData = jointData;
  65089. jointData.nativeParams = jointData.nativeParams || {};
  65090. }
  65091. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  65092. get: function () {
  65093. return this._physicsJoint;
  65094. },
  65095. set: function (newJoint) {
  65096. if (this._physicsJoint) {
  65097. //remove from the wolrd
  65098. }
  65099. this._physicsJoint = newJoint;
  65100. },
  65101. enumerable: true,
  65102. configurable: true
  65103. });
  65104. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  65105. set: function (physicsPlugin) {
  65106. this._physicsPlugin = physicsPlugin;
  65107. },
  65108. enumerable: true,
  65109. configurable: true
  65110. });
  65111. /**
  65112. * Execute a function that is physics-plugin specific.
  65113. * @param {Function} func the function that will be executed.
  65114. * It accepts two parameters: the physics world and the physics joint.
  65115. */
  65116. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  65117. func(this._physicsPlugin.world, this._physicsJoint);
  65118. };
  65119. //TODO check if the native joints are the same
  65120. //Joint Types
  65121. PhysicsJoint.DistanceJoint = 0;
  65122. PhysicsJoint.HingeJoint = 1;
  65123. PhysicsJoint.BallAndSocketJoint = 2;
  65124. PhysicsJoint.WheelJoint = 3;
  65125. PhysicsJoint.SliderJoint = 4;
  65126. //OIMO
  65127. PhysicsJoint.PrismaticJoint = 5;
  65128. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  65129. PhysicsJoint.UniversalJoint = 6;
  65130. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  65131. //Cannon
  65132. //Similar to a Ball-Joint. Different in params
  65133. PhysicsJoint.PointToPointJoint = 8;
  65134. //Cannon only at the moment
  65135. PhysicsJoint.SpringJoint = 9;
  65136. PhysicsJoint.LockJoint = 10;
  65137. return PhysicsJoint;
  65138. }());
  65139. BABYLON.PhysicsJoint = PhysicsJoint;
  65140. /**
  65141. * A class representing a physics distance joint.
  65142. */
  65143. var DistanceJoint = /** @class */ (function (_super) {
  65144. __extends(DistanceJoint, _super);
  65145. function DistanceJoint(jointData) {
  65146. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  65147. }
  65148. /**
  65149. * Update the predefined distance.
  65150. */
  65151. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  65152. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  65153. };
  65154. return DistanceJoint;
  65155. }(PhysicsJoint));
  65156. BABYLON.DistanceJoint = DistanceJoint;
  65157. var MotorEnabledJoint = /** @class */ (function (_super) {
  65158. __extends(MotorEnabledJoint, _super);
  65159. function MotorEnabledJoint(type, jointData) {
  65160. return _super.call(this, type, jointData) || this;
  65161. }
  65162. /**
  65163. * Set the motor values.
  65164. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65165. * @param {number} force the force to apply
  65166. * @param {number} maxForce max force for this motor.
  65167. */
  65168. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  65169. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65170. };
  65171. /**
  65172. * Set the motor's limits.
  65173. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65174. */
  65175. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65176. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65177. };
  65178. return MotorEnabledJoint;
  65179. }(PhysicsJoint));
  65180. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  65181. /**
  65182. * This class represents a single hinge physics joint
  65183. */
  65184. var HingeJoint = /** @class */ (function (_super) {
  65185. __extends(HingeJoint, _super);
  65186. function HingeJoint(jointData) {
  65187. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  65188. }
  65189. /**
  65190. * Set the motor values.
  65191. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65192. * @param {number} force the force to apply
  65193. * @param {number} maxForce max force for this motor.
  65194. */
  65195. HingeJoint.prototype.setMotor = function (force, maxForce) {
  65196. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65197. };
  65198. /**
  65199. * Set the motor's limits.
  65200. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65201. */
  65202. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65203. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65204. };
  65205. return HingeJoint;
  65206. }(MotorEnabledJoint));
  65207. BABYLON.HingeJoint = HingeJoint;
  65208. /**
  65209. * This class represents a dual hinge physics joint (same as wheel joint)
  65210. */
  65211. var Hinge2Joint = /** @class */ (function (_super) {
  65212. __extends(Hinge2Joint, _super);
  65213. function Hinge2Joint(jointData) {
  65214. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  65215. }
  65216. /**
  65217. * Set the motor values.
  65218. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65219. * @param {number} force the force to apply
  65220. * @param {number} maxForce max force for this motor.
  65221. * @param {motorIndex} the motor's index, 0 or 1.
  65222. */
  65223. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  65224. if (motorIndex === void 0) { motorIndex = 0; }
  65225. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  65226. };
  65227. /**
  65228. * Set the motor limits.
  65229. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65230. * @param {number} upperLimit the upper limit
  65231. * @param {number} lowerLimit lower limit
  65232. * @param {motorIndex} the motor's index, 0 or 1.
  65233. */
  65234. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  65235. if (motorIndex === void 0) { motorIndex = 0; }
  65236. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  65237. };
  65238. return Hinge2Joint;
  65239. }(MotorEnabledJoint));
  65240. BABYLON.Hinge2Joint = Hinge2Joint;
  65241. })(BABYLON || (BABYLON = {}));
  65242. //# sourceMappingURL=babylon.physicsJoint.js.map
  65243. var BABYLON;
  65244. (function (BABYLON) {
  65245. var PhysicsImpostor = /** @class */ (function () {
  65246. function PhysicsImpostor(object, type, _options, _scene) {
  65247. if (_options === void 0) { _options = { mass: 0 }; }
  65248. var _this = this;
  65249. this.object = object;
  65250. this.type = type;
  65251. this._options = _options;
  65252. this._scene = _scene;
  65253. this._bodyUpdateRequired = false;
  65254. this._onBeforePhysicsStepCallbacks = new Array();
  65255. this._onAfterPhysicsStepCallbacks = new Array();
  65256. this._onPhysicsCollideCallbacks = [];
  65257. this._deltaPosition = BABYLON.Vector3.Zero();
  65258. this._isDisposed = false;
  65259. //temp variables for parent rotation calculations
  65260. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  65261. this._tmpQuat = new BABYLON.Quaternion();
  65262. this._tmpQuat2 = new BABYLON.Quaternion();
  65263. /**
  65264. * this function is executed by the physics engine.
  65265. */
  65266. this.beforeStep = function () {
  65267. if (!_this._physicsEngine) {
  65268. return;
  65269. }
  65270. _this.object.translate(_this._deltaPosition, -1);
  65271. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  65272. _this.object.computeWorldMatrix(false);
  65273. if (_this.object.parent && _this.object.rotationQuaternion) {
  65274. _this.getParentsRotation();
  65275. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  65276. }
  65277. else {
  65278. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  65279. }
  65280. if (!_this._options.disableBidirectionalTransformation) {
  65281. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  65282. }
  65283. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  65284. func(_this);
  65285. });
  65286. };
  65287. /**
  65288. * this function is executed by the physics engine.
  65289. */
  65290. this.afterStep = function () {
  65291. if (!_this._physicsEngine) {
  65292. return;
  65293. }
  65294. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  65295. func(_this);
  65296. });
  65297. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  65298. // object has now its world rotation. needs to be converted to local.
  65299. if (_this.object.parent && _this.object.rotationQuaternion) {
  65300. _this.getParentsRotation();
  65301. _this._tmpQuat.conjugateInPlace();
  65302. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  65303. }
  65304. // take the position set and make it the absolute position of this object.
  65305. _this.object.setAbsolutePosition(_this.object.position);
  65306. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  65307. _this.object.translate(_this._deltaPosition, 1);
  65308. };
  65309. /**
  65310. * Legacy collision detection event support
  65311. */
  65312. this.onCollideEvent = null;
  65313. //event and body object due to cannon's event-based architecture.
  65314. this.onCollide = function (e) {
  65315. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  65316. return;
  65317. }
  65318. if (!_this._physicsEngine) {
  65319. return;
  65320. }
  65321. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  65322. if (otherImpostor) {
  65323. // Legacy collision detection event support
  65324. if (_this.onCollideEvent) {
  65325. _this.onCollideEvent(_this, otherImpostor);
  65326. }
  65327. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65328. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65329. }).forEach(function (obj) {
  65330. obj.callback(_this, otherImpostor);
  65331. });
  65332. }
  65333. };
  65334. //sanity check!
  65335. if (!this.object) {
  65336. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65337. return;
  65338. }
  65339. //legacy support for old syntax.
  65340. if (!this._scene && object.getScene) {
  65341. this._scene = object.getScene();
  65342. }
  65343. if (!this._scene) {
  65344. return;
  65345. }
  65346. this._physicsEngine = this._scene.getPhysicsEngine();
  65347. if (!this._physicsEngine) {
  65348. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65349. }
  65350. else {
  65351. //set the object's quaternion, if not set
  65352. if (!this.object.rotationQuaternion) {
  65353. if (this.object.rotation) {
  65354. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65355. }
  65356. else {
  65357. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65358. }
  65359. }
  65360. //default options params
  65361. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65362. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65363. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65364. this._joints = [];
  65365. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65366. if (!this.object.parent || this._options.ignoreParent) {
  65367. this._init();
  65368. }
  65369. else if (this.object.parent.physicsImpostor) {
  65370. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65371. }
  65372. }
  65373. }
  65374. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65375. get: function () {
  65376. return this._isDisposed;
  65377. },
  65378. enumerable: true,
  65379. configurable: true
  65380. });
  65381. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65382. get: function () {
  65383. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65384. },
  65385. set: function (value) {
  65386. this.setMass(value);
  65387. },
  65388. enumerable: true,
  65389. configurable: true
  65390. });
  65391. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65392. get: function () {
  65393. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65394. },
  65395. set: function (value) {
  65396. if (!this._physicsEngine) {
  65397. return;
  65398. }
  65399. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65400. },
  65401. enumerable: true,
  65402. configurable: true
  65403. });
  65404. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  65405. get: function () {
  65406. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  65407. },
  65408. set: function (value) {
  65409. if (!this._physicsEngine) {
  65410. return;
  65411. }
  65412. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  65413. },
  65414. enumerable: true,
  65415. configurable: true
  65416. });
  65417. /**
  65418. * This function will completly initialize this impostor.
  65419. * It will create a new body - but only if this mesh has no parent.
  65420. * If it has, this impostor will not be used other than to define the impostor
  65421. * of the child mesh.
  65422. */
  65423. PhysicsImpostor.prototype._init = function () {
  65424. if (!this._physicsEngine) {
  65425. return;
  65426. }
  65427. this._physicsEngine.removeImpostor(this);
  65428. this.physicsBody = null;
  65429. this._parent = this._parent || this._getPhysicsParent();
  65430. if (!this.parent || this._options.ignoreParent) {
  65431. this._physicsEngine.addImpostor(this);
  65432. }
  65433. };
  65434. PhysicsImpostor.prototype._getPhysicsParent = function () {
  65435. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  65436. var parentMesh = this.object.parent;
  65437. return parentMesh.physicsImpostor;
  65438. }
  65439. return null;
  65440. };
  65441. /**
  65442. * Should a new body be generated.
  65443. */
  65444. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  65445. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  65446. };
  65447. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  65448. this.forceUpdate();
  65449. };
  65450. /**
  65451. * Force a regeneration of this or the parent's impostor's body.
  65452. * Use under cautious - This will remove all joints already implemented.
  65453. */
  65454. PhysicsImpostor.prototype.forceUpdate = function () {
  65455. this._init();
  65456. if (this.parent && !this._options.ignoreParent) {
  65457. this.parent.forceUpdate();
  65458. }
  65459. };
  65460. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  65461. /*public get mesh(): AbstractMesh {
  65462. return this._mesh;
  65463. }*/
  65464. /**
  65465. * Gets the body that holds this impostor. Either its own, or its parent.
  65466. */
  65467. get: function () {
  65468. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  65469. },
  65470. /**
  65471. * Set the physics body. Used mainly by the physics engine/plugin
  65472. */
  65473. set: function (physicsBody) {
  65474. if (this._physicsBody && this._physicsEngine) {
  65475. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  65476. }
  65477. this._physicsBody = physicsBody;
  65478. this.resetUpdateFlags();
  65479. },
  65480. enumerable: true,
  65481. configurable: true
  65482. });
  65483. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  65484. get: function () {
  65485. return !this._options.ignoreParent && this._parent ? this._parent : null;
  65486. },
  65487. set: function (value) {
  65488. this._parent = value;
  65489. },
  65490. enumerable: true,
  65491. configurable: true
  65492. });
  65493. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  65494. this._bodyUpdateRequired = false;
  65495. };
  65496. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  65497. if (this.object.getBoundingInfo) {
  65498. var q = this.object.rotationQuaternion;
  65499. //reset rotation
  65500. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  65501. //calculate the world matrix with no rotation
  65502. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65503. var boundingInfo = this.object.getBoundingInfo();
  65504. var size = void 0;
  65505. if (boundingInfo) {
  65506. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  65507. }
  65508. else {
  65509. size = BABYLON.Vector3.Zero();
  65510. }
  65511. //bring back the rotation
  65512. this.object.rotationQuaternion = q;
  65513. //calculate the world matrix with the new rotation
  65514. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65515. return size;
  65516. }
  65517. else {
  65518. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  65519. }
  65520. };
  65521. PhysicsImpostor.prototype.getObjectCenter = function () {
  65522. if (this.object.getBoundingInfo) {
  65523. var boundingInfo = this.object.getBoundingInfo();
  65524. if (!boundingInfo) {
  65525. return this.object.position;
  65526. }
  65527. return boundingInfo.boundingBox.centerWorld;
  65528. }
  65529. else {
  65530. return this.object.position;
  65531. }
  65532. };
  65533. /**
  65534. * Get a specific parametes from the options parameter.
  65535. */
  65536. PhysicsImpostor.prototype.getParam = function (paramName) {
  65537. return this._options[paramName];
  65538. };
  65539. /**
  65540. * Sets a specific parameter in the options given to the physics plugin
  65541. */
  65542. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  65543. this._options[paramName] = value;
  65544. this._bodyUpdateRequired = true;
  65545. };
  65546. /**
  65547. * Specifically change the body's mass option. Won't recreate the physics body object
  65548. */
  65549. PhysicsImpostor.prototype.setMass = function (mass) {
  65550. if (this.getParam("mass") !== mass) {
  65551. this.setParam("mass", mass);
  65552. }
  65553. if (this._physicsEngine) {
  65554. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  65555. }
  65556. };
  65557. PhysicsImpostor.prototype.getLinearVelocity = function () {
  65558. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  65559. };
  65560. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  65561. if (this._physicsEngine) {
  65562. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  65563. }
  65564. };
  65565. PhysicsImpostor.prototype.getAngularVelocity = function () {
  65566. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  65567. };
  65568. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  65569. if (this._physicsEngine) {
  65570. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  65571. }
  65572. };
  65573. /**
  65574. * Execute a function with the physics plugin native code.
  65575. * Provide a function the will have two variables - the world object and the physics body object.
  65576. */
  65577. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  65578. if (this._physicsEngine) {
  65579. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  65580. }
  65581. };
  65582. /**
  65583. * Register a function that will be executed before the physics world is stepping forward.
  65584. */
  65585. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  65586. this._onBeforePhysicsStepCallbacks.push(func);
  65587. };
  65588. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  65589. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  65590. if (index > -1) {
  65591. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  65592. }
  65593. else {
  65594. BABYLON.Tools.Warn("Function to remove was not found");
  65595. }
  65596. };
  65597. /**
  65598. * Register a function that will be executed after the physics step
  65599. */
  65600. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  65601. this._onAfterPhysicsStepCallbacks.push(func);
  65602. };
  65603. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  65604. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  65605. if (index > -1) {
  65606. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  65607. }
  65608. else {
  65609. BABYLON.Tools.Warn("Function to remove was not found");
  65610. }
  65611. };
  65612. /**
  65613. * register a function that will be executed when this impostor collides against a different body.
  65614. */
  65615. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  65616. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65617. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  65618. };
  65619. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  65620. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65621. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  65622. if (index > -1) {
  65623. this._onPhysicsCollideCallbacks.splice(index, 1);
  65624. }
  65625. else {
  65626. BABYLON.Tools.Warn("Function to remove was not found");
  65627. }
  65628. };
  65629. PhysicsImpostor.prototype.getParentsRotation = function () {
  65630. var parent = this.object.parent;
  65631. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  65632. while (parent) {
  65633. if (parent.rotationQuaternion) {
  65634. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  65635. }
  65636. else {
  65637. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  65638. }
  65639. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  65640. parent = parent.parent;
  65641. }
  65642. return this._tmpQuat;
  65643. };
  65644. /**
  65645. * Apply a force
  65646. */
  65647. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  65648. if (this._physicsEngine) {
  65649. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  65650. }
  65651. return this;
  65652. };
  65653. /**
  65654. * Apply an impulse
  65655. */
  65656. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  65657. if (this._physicsEngine) {
  65658. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  65659. }
  65660. return this;
  65661. };
  65662. /**
  65663. * A help function to create a joint.
  65664. */
  65665. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  65666. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  65667. this.addJoint(otherImpostor, joint);
  65668. return this;
  65669. };
  65670. /**
  65671. * Add a joint to this impostor with a different impostor.
  65672. */
  65673. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  65674. this._joints.push({
  65675. otherImpostor: otherImpostor,
  65676. joint: joint
  65677. });
  65678. if (this._physicsEngine) {
  65679. this._physicsEngine.addJoint(this, otherImpostor, joint);
  65680. }
  65681. return this;
  65682. };
  65683. /**
  65684. * Will keep this body still, in a sleep mode.
  65685. */
  65686. PhysicsImpostor.prototype.sleep = function () {
  65687. if (this._physicsEngine) {
  65688. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  65689. }
  65690. return this;
  65691. };
  65692. /**
  65693. * Wake the body up.
  65694. */
  65695. PhysicsImpostor.prototype.wakeUp = function () {
  65696. if (this._physicsEngine) {
  65697. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  65698. }
  65699. return this;
  65700. };
  65701. PhysicsImpostor.prototype.clone = function (newObject) {
  65702. if (!newObject)
  65703. return null;
  65704. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  65705. };
  65706. PhysicsImpostor.prototype.dispose = function () {
  65707. var _this = this;
  65708. //no dispose if no physics engine is available.
  65709. if (!this._physicsEngine) {
  65710. return;
  65711. }
  65712. this._joints.forEach(function (j) {
  65713. if (_this._physicsEngine) {
  65714. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  65715. }
  65716. });
  65717. //dispose the physics body
  65718. this._physicsEngine.removeImpostor(this);
  65719. if (this.parent) {
  65720. this.parent.forceUpdate();
  65721. }
  65722. else {
  65723. /*this._object.getChildMeshes().forEach(function(mesh) {
  65724. if (mesh.physicsImpostor) {
  65725. if (disposeChildren) {
  65726. mesh.physicsImpostor.dispose();
  65727. mesh.physicsImpostor = null;
  65728. }
  65729. }
  65730. })*/
  65731. }
  65732. this._isDisposed = true;
  65733. };
  65734. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  65735. this._deltaPosition.copyFrom(position);
  65736. };
  65737. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  65738. if (!this._deltaRotation) {
  65739. this._deltaRotation = new BABYLON.Quaternion();
  65740. }
  65741. this._deltaRotation.copyFrom(rotation);
  65742. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  65743. };
  65744. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  65745. if (this._physicsEngine) {
  65746. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  65747. }
  65748. return this;
  65749. };
  65750. PhysicsImpostor.prototype.getRadius = function () {
  65751. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  65752. };
  65753. /**
  65754. * Sync a bone with this impostor
  65755. * @param bone The bone to sync to the impostor.
  65756. * @param boneMesh The mesh that the bone is influencing.
  65757. * @param jointPivot The pivot of the joint / bone in local space.
  65758. * @param distToJoint Optional distance from the impostor to the joint.
  65759. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65760. */
  65761. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  65762. var tempVec = PhysicsImpostor._tmpVecs[0];
  65763. var mesh = this.object;
  65764. if (mesh.rotationQuaternion) {
  65765. if (adjustRotation) {
  65766. var tempQuat = PhysicsImpostor._tmpQuat;
  65767. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  65768. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  65769. }
  65770. else {
  65771. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  65772. }
  65773. }
  65774. tempVec.x = 0;
  65775. tempVec.y = 0;
  65776. tempVec.z = 0;
  65777. if (jointPivot) {
  65778. tempVec.x = jointPivot.x;
  65779. tempVec.y = jointPivot.y;
  65780. tempVec.z = jointPivot.z;
  65781. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  65782. if (distToJoint === undefined || distToJoint === null) {
  65783. distToJoint = jointPivot.length();
  65784. }
  65785. tempVec.x *= distToJoint;
  65786. tempVec.y *= distToJoint;
  65787. tempVec.z *= distToJoint;
  65788. }
  65789. if (bone.getParent()) {
  65790. tempVec.addInPlace(mesh.getAbsolutePosition());
  65791. bone.setAbsolutePosition(tempVec, boneMesh);
  65792. }
  65793. else {
  65794. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  65795. boneMesh.position.x -= tempVec.x;
  65796. boneMesh.position.y -= tempVec.y;
  65797. boneMesh.position.z -= tempVec.z;
  65798. }
  65799. };
  65800. /**
  65801. * Sync impostor to a bone
  65802. * @param bone The bone that the impostor will be synced to.
  65803. * @param boneMesh The mesh that the bone is influencing.
  65804. * @param jointPivot The pivot of the joint / bone in local space.
  65805. * @param distToJoint Optional distance from the impostor to the joint.
  65806. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65807. * @param boneAxis Optional vector3 axis the bone is aligned with
  65808. */
  65809. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  65810. var mesh = this.object;
  65811. if (mesh.rotationQuaternion) {
  65812. if (adjustRotation) {
  65813. var tempQuat = PhysicsImpostor._tmpQuat;
  65814. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  65815. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  65816. }
  65817. else {
  65818. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  65819. }
  65820. }
  65821. var pos = PhysicsImpostor._tmpVecs[0];
  65822. var boneDir = PhysicsImpostor._tmpVecs[1];
  65823. if (!boneAxis) {
  65824. boneAxis = PhysicsImpostor._tmpVecs[2];
  65825. boneAxis.x = 0;
  65826. boneAxis.y = 1;
  65827. boneAxis.z = 0;
  65828. }
  65829. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  65830. bone.getAbsolutePositionToRef(boneMesh, pos);
  65831. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  65832. distToJoint = jointPivot.length();
  65833. }
  65834. if (distToJoint !== undefined && distToJoint !== null) {
  65835. pos.x += boneDir.x * distToJoint;
  65836. pos.y += boneDir.y * distToJoint;
  65837. pos.z += boneDir.z * distToJoint;
  65838. }
  65839. mesh.setAbsolutePosition(pos);
  65840. };
  65841. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  65842. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  65843. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65844. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  65845. //Impostor types
  65846. PhysicsImpostor.NoImpostor = 0;
  65847. PhysicsImpostor.SphereImpostor = 1;
  65848. PhysicsImpostor.BoxImpostor = 2;
  65849. PhysicsImpostor.PlaneImpostor = 3;
  65850. PhysicsImpostor.MeshImpostor = 4;
  65851. PhysicsImpostor.CylinderImpostor = 7;
  65852. PhysicsImpostor.ParticleImpostor = 8;
  65853. PhysicsImpostor.HeightmapImpostor = 9;
  65854. return PhysicsImpostor;
  65855. }());
  65856. BABYLON.PhysicsImpostor = PhysicsImpostor;
  65857. })(BABYLON || (BABYLON = {}));
  65858. //# sourceMappingURL=babylon.physicsImpostor.js.map
  65859. var BABYLON;
  65860. (function (BABYLON) {
  65861. var PhysicsEngine = /** @class */ (function () {
  65862. function PhysicsEngine(gravity, _physicsPlugin) {
  65863. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  65864. this._physicsPlugin = _physicsPlugin;
  65865. //new methods and parameters
  65866. this._impostors = [];
  65867. this._joints = [];
  65868. if (!this._physicsPlugin.isSupported()) {
  65869. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  65870. + "Please make sure it is included.");
  65871. }
  65872. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  65873. this.setGravity(gravity);
  65874. this.setTimeStep();
  65875. }
  65876. PhysicsEngine.prototype.setGravity = function (gravity) {
  65877. this.gravity = gravity;
  65878. this._physicsPlugin.setGravity(this.gravity);
  65879. };
  65880. /**
  65881. * Set the time step of the physics engine.
  65882. * default is 1/60.
  65883. * To slow it down, enter 1/600 for example.
  65884. * To speed it up, 1/30
  65885. * @param {number} newTimeStep the new timestep to apply to this world.
  65886. */
  65887. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  65888. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  65889. this._physicsPlugin.setTimeStep(newTimeStep);
  65890. };
  65891. /**
  65892. * Get the time step of the physics engine.
  65893. */
  65894. PhysicsEngine.prototype.getTimeStep = function () {
  65895. return this._physicsPlugin.getTimeStep();
  65896. };
  65897. PhysicsEngine.prototype.dispose = function () {
  65898. this._impostors.forEach(function (impostor) {
  65899. impostor.dispose();
  65900. });
  65901. this._physicsPlugin.dispose();
  65902. };
  65903. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  65904. return this._physicsPlugin.name;
  65905. };
  65906. /**
  65907. * Adding a new impostor for the impostor tracking.
  65908. * This will be done by the impostor itself.
  65909. * @param {PhysicsImpostor} impostor the impostor to add
  65910. */
  65911. PhysicsEngine.prototype.addImpostor = function (impostor) {
  65912. impostor.uniqueId = this._impostors.push(impostor);
  65913. //if no parent, generate the body
  65914. if (!impostor.parent) {
  65915. this._physicsPlugin.generatePhysicsBody(impostor);
  65916. }
  65917. };
  65918. /**
  65919. * Remove an impostor from the engine.
  65920. * This impostor and its mesh will not longer be updated by the physics engine.
  65921. * @param {PhysicsImpostor} impostor the impostor to remove
  65922. */
  65923. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  65924. var index = this._impostors.indexOf(impostor);
  65925. if (index > -1) {
  65926. var removed = this._impostors.splice(index, 1);
  65927. //Is it needed?
  65928. if (removed.length) {
  65929. //this will also remove it from the world.
  65930. removed[0].physicsBody = null;
  65931. }
  65932. }
  65933. };
  65934. /**
  65935. * Add a joint to the physics engine
  65936. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  65937. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  65938. * @param {PhysicsJoint} the joint that will connect both impostors.
  65939. */
  65940. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  65941. var impostorJoint = {
  65942. mainImpostor: mainImpostor,
  65943. connectedImpostor: connectedImpostor,
  65944. joint: joint
  65945. };
  65946. joint.physicsPlugin = this._physicsPlugin;
  65947. this._joints.push(impostorJoint);
  65948. this._physicsPlugin.generateJoint(impostorJoint);
  65949. };
  65950. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  65951. var matchingJoints = this._joints.filter(function (impostorJoint) {
  65952. return (impostorJoint.connectedImpostor === connectedImpostor
  65953. && impostorJoint.joint === joint
  65954. && impostorJoint.mainImpostor === mainImpostor);
  65955. });
  65956. if (matchingJoints.length) {
  65957. this._physicsPlugin.removeJoint(matchingJoints[0]);
  65958. //TODO remove it from the list as well
  65959. }
  65960. };
  65961. /**
  65962. * Called by the scene. no need to call it.
  65963. */
  65964. PhysicsEngine.prototype._step = function (delta) {
  65965. var _this = this;
  65966. //check if any mesh has no body / requires an update
  65967. this._impostors.forEach(function (impostor) {
  65968. if (impostor.isBodyInitRequired()) {
  65969. _this._physicsPlugin.generatePhysicsBody(impostor);
  65970. }
  65971. });
  65972. if (delta > 0.1) {
  65973. delta = 0.1;
  65974. }
  65975. else if (delta <= 0) {
  65976. delta = 1.0 / 60.0;
  65977. }
  65978. this._physicsPlugin.executeStep(delta, this._impostors);
  65979. };
  65980. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  65981. return this._physicsPlugin;
  65982. };
  65983. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  65984. for (var i = 0; i < this._impostors.length; ++i) {
  65985. if (this._impostors[i].object === object) {
  65986. return this._impostors[i];
  65987. }
  65988. }
  65989. return null;
  65990. };
  65991. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  65992. for (var i = 0; i < this._impostors.length; ++i) {
  65993. if (this._impostors[i].physicsBody === body) {
  65994. return this._impostors[i];
  65995. }
  65996. }
  65997. return null;
  65998. };
  65999. // Statics
  66000. PhysicsEngine.Epsilon = 0.001;
  66001. return PhysicsEngine;
  66002. }());
  66003. BABYLON.PhysicsEngine = PhysicsEngine;
  66004. })(BABYLON || (BABYLON = {}));
  66005. //# sourceMappingURL=babylon.physicsEngine.js.map
  66006. var BABYLON;
  66007. (function (BABYLON) {
  66008. var CannonJSPlugin = /** @class */ (function () {
  66009. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  66010. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  66011. if (iterations === void 0) { iterations = 10; }
  66012. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  66013. this.name = "CannonJSPlugin";
  66014. this._physicsMaterials = new Array();
  66015. this._fixedTimeStep = 1 / 60;
  66016. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  66017. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  66018. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  66019. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  66020. this._tmpPosition = BABYLON.Vector3.Zero();
  66021. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  66022. this._tmpUnityRotation = new BABYLON.Quaternion();
  66023. if (!this.isSupported()) {
  66024. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  66025. return;
  66026. }
  66027. this.world = new this.BJSCANNON.World();
  66028. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  66029. this.world.solver.iterations = iterations;
  66030. }
  66031. CannonJSPlugin.prototype.setGravity = function (gravity) {
  66032. this.world.gravity.copy(gravity);
  66033. };
  66034. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  66035. this._fixedTimeStep = timeStep;
  66036. };
  66037. CannonJSPlugin.prototype.getTimeStep = function () {
  66038. return this._fixedTimeStep;
  66039. };
  66040. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  66041. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  66042. };
  66043. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66044. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66045. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66046. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  66047. };
  66048. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66049. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66050. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66051. impostor.physicsBody.applyForce(impulse, worldPoint);
  66052. };
  66053. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66054. //parent-child relationship. Does this impostor has a parent impostor?
  66055. if (impostor.parent) {
  66056. if (impostor.physicsBody) {
  66057. this.removePhysicsBody(impostor);
  66058. //TODO is that needed?
  66059. impostor.forceUpdate();
  66060. }
  66061. return;
  66062. }
  66063. //should a new body be created for this impostor?
  66064. if (impostor.isBodyInitRequired()) {
  66065. var shape = this._createShape(impostor);
  66066. //unregister events, if body is being changed
  66067. var oldBody = impostor.physicsBody;
  66068. if (oldBody) {
  66069. this.removePhysicsBody(impostor);
  66070. }
  66071. //create the body and material
  66072. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  66073. var bodyCreationObject = {
  66074. mass: impostor.getParam("mass"),
  66075. material: material
  66076. };
  66077. // A simple extend, in case native options were used.
  66078. var nativeOptions = impostor.getParam("nativeOptions");
  66079. for (var key in nativeOptions) {
  66080. if (nativeOptions.hasOwnProperty(key)) {
  66081. bodyCreationObject[key] = nativeOptions[key];
  66082. }
  66083. }
  66084. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  66085. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  66086. this.world.addEventListener("preStep", impostor.beforeStep);
  66087. this.world.addEventListener("postStep", impostor.afterStep);
  66088. impostor.physicsBody.addShape(shape);
  66089. this.world.add(impostor.physicsBody);
  66090. //try to keep the body moving in the right direction by taking old properties.
  66091. //Should be tested!
  66092. if (oldBody) {
  66093. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  66094. impostor.physicsBody[param].copy(oldBody[param]);
  66095. });
  66096. }
  66097. this._processChildMeshes(impostor);
  66098. }
  66099. //now update the body's transformation
  66100. this._updatePhysicsBodyTransformation(impostor);
  66101. };
  66102. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  66103. var _this = this;
  66104. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  66105. var currentRotation = mainImpostor.object.rotationQuaternion;
  66106. if (meshChildren.length) {
  66107. var processMesh = function (localPosition, mesh) {
  66108. if (!currentRotation || !mesh.rotationQuaternion) {
  66109. return;
  66110. }
  66111. var childImpostor = mesh.getPhysicsImpostor();
  66112. if (childImpostor) {
  66113. var parent = childImpostor.parent;
  66114. if (parent !== mainImpostor) {
  66115. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  66116. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  66117. if (childImpostor.physicsBody) {
  66118. _this.removePhysicsBody(childImpostor);
  66119. childImpostor.physicsBody = null;
  66120. }
  66121. childImpostor.parent = mainImpostor;
  66122. childImpostor.resetUpdateFlags();
  66123. 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));
  66124. //Add the mass of the children.
  66125. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  66126. }
  66127. }
  66128. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  66129. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  66130. };
  66131. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  66132. }
  66133. };
  66134. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66135. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  66136. this.world.removeEventListener("preStep", impostor.beforeStep);
  66137. this.world.removeEventListener("postStep", impostor.afterStep);
  66138. this.world.remove(impostor.physicsBody);
  66139. };
  66140. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66141. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66142. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66143. if (!mainBody || !connectedBody) {
  66144. return;
  66145. }
  66146. var constraint;
  66147. var jointData = impostorJoint.joint.jointData;
  66148. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  66149. var constraintData = {
  66150. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  66151. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  66152. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  66153. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  66154. maxForce: jointData.nativeParams.maxForce,
  66155. collideConnected: !!jointData.collision
  66156. };
  66157. switch (impostorJoint.joint.type) {
  66158. case BABYLON.PhysicsJoint.HingeJoint:
  66159. case BABYLON.PhysicsJoint.Hinge2Joint:
  66160. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  66161. break;
  66162. case BABYLON.PhysicsJoint.DistanceJoint:
  66163. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  66164. break;
  66165. case BABYLON.PhysicsJoint.SpringJoint:
  66166. var springData = jointData;
  66167. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  66168. restLength: springData.length,
  66169. stiffness: springData.stiffness,
  66170. damping: springData.damping,
  66171. localAnchorA: constraintData.pivotA,
  66172. localAnchorB: constraintData.pivotB
  66173. });
  66174. break;
  66175. case BABYLON.PhysicsJoint.LockJoint:
  66176. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  66177. break;
  66178. case BABYLON.PhysicsJoint.PointToPointJoint:
  66179. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66180. default:
  66181. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  66182. break;
  66183. }
  66184. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  66185. constraint.collideConnected = !!jointData.collision;
  66186. impostorJoint.joint.physicsJoint = constraint;
  66187. //don't add spring as constraint, as it is not one.
  66188. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  66189. this.world.addConstraint(constraint);
  66190. }
  66191. else {
  66192. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  66193. constraint.applyForce();
  66194. });
  66195. }
  66196. };
  66197. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66198. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  66199. };
  66200. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  66201. var index;
  66202. var mat;
  66203. for (index = 0; index < this._physicsMaterials.length; index++) {
  66204. mat = this._physicsMaterials[index];
  66205. if (mat.friction === friction && mat.restitution === restitution) {
  66206. return mat;
  66207. }
  66208. }
  66209. var currentMat = new this.BJSCANNON.Material(name);
  66210. currentMat.friction = friction;
  66211. currentMat.restitution = restitution;
  66212. this._physicsMaterials.push(currentMat);
  66213. return currentMat;
  66214. };
  66215. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  66216. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  66217. };
  66218. CannonJSPlugin.prototype._createShape = function (impostor) {
  66219. var object = impostor.object;
  66220. var returnValue;
  66221. var extendSize = impostor.getObjectExtendSize();
  66222. switch (impostor.type) {
  66223. case BABYLON.PhysicsImpostor.SphereImpostor:
  66224. var radiusX = extendSize.x;
  66225. var radiusY = extendSize.y;
  66226. var radiusZ = extendSize.z;
  66227. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  66228. break;
  66229. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  66230. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66231. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  66232. break;
  66233. case BABYLON.PhysicsImpostor.BoxImpostor:
  66234. var box = extendSize.scale(0.5);
  66235. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  66236. break;
  66237. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66238. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  66239. returnValue = new this.BJSCANNON.Plane();
  66240. break;
  66241. case BABYLON.PhysicsImpostor.MeshImpostor:
  66242. // should transform the vertex data to world coordinates!!
  66243. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  66244. var rawFaces = object.getIndices ? object.getIndices() : [];
  66245. if (!rawVerts)
  66246. return;
  66247. // get only scale! so the object could transform correctly.
  66248. var oldPosition = object.position.clone();
  66249. var oldRotation = object.rotation && object.rotation.clone();
  66250. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  66251. object.position.copyFromFloats(0, 0, 0);
  66252. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66253. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66254. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66255. var transform = object.computeWorldMatrix(true);
  66256. // convert rawVerts to object space
  66257. var temp = new Array();
  66258. var index;
  66259. for (index = 0; index < rawVerts.length; index += 3) {
  66260. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  66261. }
  66262. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  66263. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  66264. //now set back the transformation!
  66265. object.position.copyFrom(oldPosition);
  66266. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  66267. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  66268. break;
  66269. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  66270. var oldPosition2 = object.position.clone();
  66271. var oldRotation2 = object.rotation && object.rotation.clone();
  66272. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  66273. object.position.copyFromFloats(0, 0, 0);
  66274. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66275. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66276. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66277. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  66278. returnValue = this._createHeightmap(object);
  66279. object.position.copyFrom(oldPosition2);
  66280. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  66281. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  66282. object.computeWorldMatrix(true);
  66283. break;
  66284. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66285. returnValue = new this.BJSCANNON.Particle();
  66286. break;
  66287. }
  66288. return returnValue;
  66289. };
  66290. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  66291. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  66292. var transform = object.computeWorldMatrix(true);
  66293. // convert rawVerts to object space
  66294. var temp = new Array();
  66295. var index;
  66296. for (index = 0; index < pos.length; index += 3) {
  66297. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  66298. }
  66299. pos = temp;
  66300. var matrix = new Array();
  66301. //For now pointDepth will not be used and will be automatically calculated.
  66302. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  66303. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  66304. var boundingInfo = (object.getBoundingInfo());
  66305. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  66306. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  66307. var elementSize = dim * 2 / arraySize;
  66308. for (var i = 0; i < pos.length; i = i + 3) {
  66309. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  66310. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  66311. var y = -pos[i + 2] + minY;
  66312. if (!matrix[x]) {
  66313. matrix[x] = [];
  66314. }
  66315. if (!matrix[x][z]) {
  66316. matrix[x][z] = y;
  66317. }
  66318. matrix[x][z] = Math.max(y, matrix[x][z]);
  66319. }
  66320. for (var x = 0; x <= arraySize; ++x) {
  66321. if (!matrix[x]) {
  66322. var loc = 1;
  66323. while (!matrix[(x + loc) % arraySize]) {
  66324. loc++;
  66325. }
  66326. matrix[x] = matrix[(x + loc) % arraySize].slice();
  66327. //console.log("missing x", x);
  66328. }
  66329. for (var z = 0; z <= arraySize; ++z) {
  66330. if (!matrix[x][z]) {
  66331. var loc = 1;
  66332. var newValue;
  66333. while (newValue === undefined) {
  66334. newValue = matrix[x][(z + loc++) % arraySize];
  66335. }
  66336. matrix[x][z] = newValue;
  66337. }
  66338. }
  66339. }
  66340. var shape = new this.BJSCANNON.Heightfield(matrix, {
  66341. elementSize: elementSize
  66342. });
  66343. //For future reference, needed for body transformation
  66344. shape.minY = minY;
  66345. return shape;
  66346. };
  66347. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  66348. var object = impostor.object;
  66349. //make sure it is updated...
  66350. object.computeWorldMatrix && object.computeWorldMatrix(true);
  66351. // The delta between the mesh position and the mesh bounding box center
  66352. var bInfo = object.getBoundingInfo();
  66353. if (!bInfo)
  66354. return;
  66355. var center = impostor.getObjectCenter();
  66356. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  66357. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  66358. this._tmpPosition.copyFrom(center);
  66359. var quaternion = object.rotationQuaternion;
  66360. if (!quaternion) {
  66361. return;
  66362. }
  66363. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  66364. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  66365. //-90 DEG in X, precalculated
  66366. quaternion = quaternion.multiply(this._minus90X);
  66367. //Invert! (Precalculated, 90 deg in X)
  66368. //No need to clone. this will never change.
  66369. impostor.setDeltaRotation(this._plus90X);
  66370. }
  66371. //If it is a heightfield, if should be centered.
  66372. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  66373. var mesh = object;
  66374. var boundingInfo = mesh.getBoundingInfo();
  66375. //calculate the correct body position:
  66376. var rotationQuaternion = mesh.rotationQuaternion;
  66377. mesh.rotationQuaternion = this._tmpUnityRotation;
  66378. mesh.computeWorldMatrix(true);
  66379. //get original center with no rotation
  66380. var c = center.clone();
  66381. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  66382. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  66383. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  66384. mesh.setPivotMatrix(p);
  66385. mesh.computeWorldMatrix(true);
  66386. //calculate the translation
  66387. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  66388. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  66389. //add it inverted to the delta
  66390. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66391. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66392. //rotation is back
  66393. mesh.rotationQuaternion = rotationQuaternion;
  66394. mesh.setPivotMatrix(oldPivot);
  66395. mesh.computeWorldMatrix(true);
  66396. }
  66397. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66398. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66399. //this._tmpPosition.copyFrom(object.position);
  66400. }
  66401. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66402. //Now update the impostor object
  66403. impostor.physicsBody.position.copy(this._tmpPosition);
  66404. impostor.physicsBody.quaternion.copy(quaternion);
  66405. };
  66406. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66407. impostor.object.position.copyFrom(impostor.physicsBody.position);
  66408. if (impostor.object.rotationQuaternion) {
  66409. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  66410. }
  66411. };
  66412. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66413. impostor.physicsBody.position.copy(newPosition);
  66414. impostor.physicsBody.quaternion.copy(newRotation);
  66415. };
  66416. CannonJSPlugin.prototype.isSupported = function () {
  66417. return this.BJSCANNON !== undefined;
  66418. };
  66419. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66420. impostor.physicsBody.velocity.copy(velocity);
  66421. };
  66422. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66423. impostor.physicsBody.angularVelocity.copy(velocity);
  66424. };
  66425. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66426. var v = impostor.physicsBody.velocity;
  66427. if (!v) {
  66428. return null;
  66429. }
  66430. return new BABYLON.Vector3(v.x, v.y, v.z);
  66431. };
  66432. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66433. var v = impostor.physicsBody.angularVelocity;
  66434. if (!v) {
  66435. return null;
  66436. }
  66437. return new BABYLON.Vector3(v.x, v.y, v.z);
  66438. };
  66439. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66440. impostor.physicsBody.mass = mass;
  66441. impostor.physicsBody.updateMassProperties();
  66442. };
  66443. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  66444. return impostor.physicsBody.mass;
  66445. };
  66446. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  66447. return impostor.physicsBody.material.friction;
  66448. };
  66449. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66450. impostor.physicsBody.material.friction = friction;
  66451. };
  66452. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66453. return impostor.physicsBody.material.restitution;
  66454. };
  66455. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66456. impostor.physicsBody.material.restitution = restitution;
  66457. };
  66458. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  66459. impostor.physicsBody.sleep();
  66460. };
  66461. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  66462. impostor.physicsBody.wakeUp();
  66463. };
  66464. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66465. joint.physicsJoint.distance = maxDistance;
  66466. };
  66467. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66468. // if (!motorIndex) {
  66469. // joint.physicsJoint.enableMotor();
  66470. // }
  66471. // }
  66472. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66473. // if (!motorIndex) {
  66474. // joint.physicsJoint.disableMotor();
  66475. // }
  66476. // }
  66477. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66478. if (!motorIndex) {
  66479. joint.physicsJoint.enableMotor();
  66480. joint.physicsJoint.setMotorSpeed(speed);
  66481. if (maxForce) {
  66482. this.setLimit(joint, maxForce);
  66483. }
  66484. }
  66485. };
  66486. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  66487. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  66488. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  66489. };
  66490. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66491. var body = impostor.physicsBody;
  66492. mesh.position.x = body.position.x;
  66493. mesh.position.y = body.position.y;
  66494. mesh.position.z = body.position.z;
  66495. if (mesh.rotationQuaternion) {
  66496. mesh.rotationQuaternion.x = body.quaternion.x;
  66497. mesh.rotationQuaternion.y = body.quaternion.y;
  66498. mesh.rotationQuaternion.z = body.quaternion.z;
  66499. mesh.rotationQuaternion.w = body.quaternion.w;
  66500. }
  66501. };
  66502. CannonJSPlugin.prototype.getRadius = function (impostor) {
  66503. var shape = impostor.physicsBody.shapes[0];
  66504. return shape.boundingSphereRadius;
  66505. };
  66506. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66507. var shape = impostor.physicsBody.shapes[0];
  66508. result.x = shape.halfExtents.x * 2;
  66509. result.y = shape.halfExtents.y * 2;
  66510. result.z = shape.halfExtents.z * 2;
  66511. };
  66512. CannonJSPlugin.prototype.dispose = function () {
  66513. };
  66514. return CannonJSPlugin;
  66515. }());
  66516. BABYLON.CannonJSPlugin = CannonJSPlugin;
  66517. })(BABYLON || (BABYLON = {}));
  66518. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  66519. var BABYLON;
  66520. (function (BABYLON) {
  66521. var OimoJSPlugin = /** @class */ (function () {
  66522. function OimoJSPlugin(iterations) {
  66523. this.name = "OimoJSPlugin";
  66524. this._tmpImpostorsArray = [];
  66525. this._tmpPositionVector = BABYLON.Vector3.Zero();
  66526. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  66527. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  66528. this.world.worldscale(1);
  66529. this.world.clear();
  66530. //making sure no stats are calculated
  66531. this.world.isNoStat = true;
  66532. }
  66533. OimoJSPlugin.prototype.setGravity = function (gravity) {
  66534. this.world.gravity.copy(gravity);
  66535. };
  66536. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  66537. this.world.timeStep = timeStep;
  66538. };
  66539. OimoJSPlugin.prototype.getTimeStep = function () {
  66540. return this.world.timeStep;
  66541. };
  66542. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  66543. var _this = this;
  66544. impostors.forEach(function (impostor) {
  66545. impostor.beforeStep();
  66546. });
  66547. this.world.step();
  66548. impostors.forEach(function (impostor) {
  66549. impostor.afterStep();
  66550. //update the ordered impostors array
  66551. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  66552. });
  66553. //check for collisions
  66554. var contact = this.world.contacts;
  66555. while (contact !== null) {
  66556. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  66557. contact = contact.next;
  66558. continue;
  66559. }
  66560. //is this body colliding with any other? get the impostor
  66561. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  66562. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  66563. if (!mainImpostor || !collidingImpostor) {
  66564. contact = contact.next;
  66565. continue;
  66566. }
  66567. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  66568. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  66569. contact = contact.next;
  66570. }
  66571. };
  66572. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66573. var mass = impostor.physicsBody.massInfo.mass;
  66574. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  66575. };
  66576. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66577. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  66578. this.applyImpulse(impostor, force, contactPoint);
  66579. };
  66580. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66581. var _this = this;
  66582. //parent-child relationship. Does this impostor has a parent impostor?
  66583. if (impostor.parent) {
  66584. if (impostor.physicsBody) {
  66585. this.removePhysicsBody(impostor);
  66586. //TODO is that needed?
  66587. impostor.forceUpdate();
  66588. }
  66589. return;
  66590. }
  66591. if (impostor.isBodyInitRequired()) {
  66592. var bodyConfig = {
  66593. name: impostor.uniqueId,
  66594. //Oimo must have mass, also for static objects.
  66595. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  66596. size: [],
  66597. type: [],
  66598. pos: [],
  66599. rot: [],
  66600. move: impostor.getParam("mass") !== 0,
  66601. //Supporting older versions of Oimo
  66602. world: this.world
  66603. };
  66604. var impostors = [impostor];
  66605. var addToArray = function (parent) {
  66606. if (!parent.getChildMeshes)
  66607. return;
  66608. parent.getChildMeshes().forEach(function (m) {
  66609. if (m.physicsImpostor) {
  66610. impostors.push(m.physicsImpostor);
  66611. //m.physicsImpostor._init();
  66612. }
  66613. });
  66614. };
  66615. addToArray(impostor.object);
  66616. var checkWithEpsilon_1 = function (value) {
  66617. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  66618. };
  66619. impostors.forEach(function (i) {
  66620. if (!impostor.object.rotationQuaternion) {
  66621. return;
  66622. }
  66623. //get the correct bounding box
  66624. var oldQuaternion = i.object.rotationQuaternion;
  66625. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  66626. x: impostor.object.rotationQuaternion.x,
  66627. y: impostor.object.rotationQuaternion.y,
  66628. z: impostor.object.rotationQuaternion.z,
  66629. s: impostor.object.rotationQuaternion.w
  66630. });
  66631. var extendSize = i.getObjectExtendSize();
  66632. if (i === impostor) {
  66633. var center = impostor.getObjectCenter();
  66634. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  66635. //Can also use Array.prototype.push.apply
  66636. bodyConfig.pos.push(center.x);
  66637. bodyConfig.pos.push(center.y);
  66638. bodyConfig.pos.push(center.z);
  66639. //tmp solution
  66640. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66641. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66642. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66643. }
  66644. else {
  66645. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  66646. bodyConfig.pos.push(localPosition.x);
  66647. bodyConfig.pos.push(localPosition.y);
  66648. bodyConfig.pos.push(localPosition.z);
  66649. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  66650. bodyConfig.rot.push(0);
  66651. bodyConfig.rot.push(0);
  66652. bodyConfig.rot.push(0);
  66653. }
  66654. // register mesh
  66655. switch (i.type) {
  66656. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66657. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  66658. case BABYLON.PhysicsImpostor.SphereImpostor:
  66659. var radiusX = extendSize.x;
  66660. var radiusY = extendSize.y;
  66661. var radiusZ = extendSize.z;
  66662. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  66663. bodyConfig.type.push('sphere');
  66664. //due to the way oimo works with compounds, add 3 times
  66665. bodyConfig.size.push(size);
  66666. bodyConfig.size.push(size);
  66667. bodyConfig.size.push(size);
  66668. break;
  66669. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66670. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  66671. var sizeY = checkWithEpsilon_1(extendSize.y);
  66672. bodyConfig.type.push('cylinder');
  66673. bodyConfig.size.push(sizeX);
  66674. bodyConfig.size.push(sizeY);
  66675. //due to the way oimo works with compounds, add one more value.
  66676. bodyConfig.size.push(sizeY);
  66677. break;
  66678. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66679. case BABYLON.PhysicsImpostor.BoxImpostor:
  66680. default:
  66681. var sizeX = checkWithEpsilon_1(extendSize.x);
  66682. var sizeY = checkWithEpsilon_1(extendSize.y);
  66683. var sizeZ = checkWithEpsilon_1(extendSize.z);
  66684. bodyConfig.type.push('box');
  66685. bodyConfig.size.push(sizeX);
  66686. bodyConfig.size.push(sizeY);
  66687. bodyConfig.size.push(sizeZ);
  66688. break;
  66689. }
  66690. //actually not needed, but hey...
  66691. i.object.rotationQuaternion = oldQuaternion;
  66692. });
  66693. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  66694. }
  66695. else {
  66696. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  66697. }
  66698. impostor.setDeltaPosition(this._tmpPositionVector);
  66699. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  66700. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  66701. };
  66702. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66703. //impostor.physicsBody.dispose();
  66704. //Same as : (older oimo versions)
  66705. this.world.removeRigidBody(impostor.physicsBody);
  66706. };
  66707. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66708. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66709. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66710. if (!mainBody || !connectedBody) {
  66711. return;
  66712. }
  66713. var jointData = impostorJoint.joint.jointData;
  66714. var options = jointData.nativeParams || {};
  66715. var type;
  66716. var nativeJointData = {
  66717. body1: mainBody,
  66718. body2: connectedBody,
  66719. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  66720. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  66721. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  66722. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  66723. min: options.min,
  66724. max: options.max,
  66725. collision: options.collision || jointData.collision,
  66726. spring: options.spring,
  66727. //supporting older version of Oimo
  66728. world: this.world
  66729. };
  66730. switch (impostorJoint.joint.type) {
  66731. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66732. type = "jointBall";
  66733. break;
  66734. case BABYLON.PhysicsJoint.SpringJoint:
  66735. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  66736. var springData = jointData;
  66737. nativeJointData.min = springData.length || nativeJointData.min;
  66738. //Max should also be set, just make sure it is at least min
  66739. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  66740. case BABYLON.PhysicsJoint.DistanceJoint:
  66741. type = "jointDistance";
  66742. nativeJointData.max = jointData.maxDistance;
  66743. break;
  66744. case BABYLON.PhysicsJoint.PrismaticJoint:
  66745. type = "jointPrisme";
  66746. break;
  66747. case BABYLON.PhysicsJoint.SliderJoint:
  66748. type = "jointSlide";
  66749. break;
  66750. case BABYLON.PhysicsJoint.WheelJoint:
  66751. type = "jointWheel";
  66752. break;
  66753. case BABYLON.PhysicsJoint.HingeJoint:
  66754. default:
  66755. type = "jointHinge";
  66756. break;
  66757. }
  66758. nativeJointData.type = type;
  66759. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  66760. };
  66761. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66762. //Bug in Oimo prevents us from disposing a joint in the playground
  66763. //joint.joint.physicsJoint.dispose();
  66764. //So we will bruteforce it!
  66765. try {
  66766. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  66767. }
  66768. catch (e) {
  66769. BABYLON.Tools.Warn(e);
  66770. }
  66771. };
  66772. OimoJSPlugin.prototype.isSupported = function () {
  66773. return this.BJSOIMO !== undefined;
  66774. };
  66775. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66776. if (!impostor.physicsBody.sleeping) {
  66777. //TODO check that
  66778. if (impostor.physicsBody.shapes.next) {
  66779. var parentShape = this._getLastShape(impostor.physicsBody);
  66780. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  66781. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  66782. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  66783. }
  66784. else {
  66785. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  66786. }
  66787. if (impostor.object.rotationQuaternion) {
  66788. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  66789. impostor.object.rotationQuaternion.normalize();
  66790. }
  66791. }
  66792. };
  66793. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66794. var body = impostor.physicsBody;
  66795. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  66796. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  66797. body.syncShapes();
  66798. body.awake();
  66799. };
  66800. OimoJSPlugin.prototype._getLastShape = function (body) {
  66801. var lastShape = body.shapes;
  66802. while (lastShape.next) {
  66803. lastShape = lastShape.next;
  66804. }
  66805. return lastShape;
  66806. };
  66807. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66808. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  66809. };
  66810. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66811. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  66812. };
  66813. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66814. var v = impostor.physicsBody.linearVelocity;
  66815. if (!v) {
  66816. return null;
  66817. }
  66818. return new BABYLON.Vector3(v.x, v.y, v.z);
  66819. };
  66820. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66821. var v = impostor.physicsBody.angularVelocity;
  66822. if (!v) {
  66823. return null;
  66824. }
  66825. return new BABYLON.Vector3(v.x, v.y, v.z);
  66826. };
  66827. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66828. var staticBody = mass === 0;
  66829. //this will actually set the body's density and not its mass.
  66830. //But this is how oimo treats the mass variable.
  66831. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  66832. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  66833. };
  66834. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  66835. return impostor.physicsBody.shapes.density;
  66836. };
  66837. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  66838. return impostor.physicsBody.shapes.friction;
  66839. };
  66840. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66841. impostor.physicsBody.shapes.friction = friction;
  66842. };
  66843. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66844. return impostor.physicsBody.shapes.restitution;
  66845. };
  66846. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66847. impostor.physicsBody.shapes.restitution = restitution;
  66848. };
  66849. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  66850. impostor.physicsBody.sleep();
  66851. };
  66852. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  66853. impostor.physicsBody.awake();
  66854. };
  66855. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66856. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  66857. if (minDistance !== void 0) {
  66858. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  66859. }
  66860. };
  66861. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66862. //TODO separate rotational and transational motors.
  66863. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66864. if (motor) {
  66865. motor.setMotor(speed, maxForce);
  66866. }
  66867. };
  66868. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  66869. //TODO separate rotational and transational motors.
  66870. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66871. if (motor) {
  66872. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  66873. }
  66874. };
  66875. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66876. var body = impostor.physicsBody;
  66877. mesh.position.x = body.position.x;
  66878. mesh.position.y = body.position.y;
  66879. mesh.position.z = body.position.z;
  66880. if (mesh.rotationQuaternion) {
  66881. mesh.rotationQuaternion.x = body.orientation.x;
  66882. mesh.rotationQuaternion.y = body.orientation.y;
  66883. mesh.rotationQuaternion.z = body.orientation.z;
  66884. mesh.rotationQuaternion.w = body.orientation.s;
  66885. }
  66886. };
  66887. OimoJSPlugin.prototype.getRadius = function (impostor) {
  66888. return impostor.physicsBody.shapes.radius;
  66889. };
  66890. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66891. var shape = impostor.physicsBody.shapes;
  66892. result.x = shape.halfWidth * 2;
  66893. result.y = shape.halfHeight * 2;
  66894. result.z = shape.halfDepth * 2;
  66895. };
  66896. OimoJSPlugin.prototype.dispose = function () {
  66897. this.world.clear();
  66898. };
  66899. return OimoJSPlugin;
  66900. }());
  66901. BABYLON.OimoJSPlugin = OimoJSPlugin;
  66902. })(BABYLON || (BABYLON = {}));
  66903. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  66904. var BABYLON;
  66905. (function (BABYLON) {
  66906. var Internals;
  66907. (function (Internals) {
  66908. /*
  66909. * Based on jsTGALoader - Javascript loader for TGA file
  66910. * By Vincent Thibault
  66911. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  66912. */
  66913. var TGATools = /** @class */ (function () {
  66914. function TGATools() {
  66915. }
  66916. TGATools.GetTGAHeader = function (data) {
  66917. var offset = 0;
  66918. var header = {
  66919. id_length: data[offset++],
  66920. colormap_type: data[offset++],
  66921. image_type: data[offset++],
  66922. colormap_index: data[offset++] | data[offset++] << 8,
  66923. colormap_length: data[offset++] | data[offset++] << 8,
  66924. colormap_size: data[offset++],
  66925. origin: [
  66926. data[offset++] | data[offset++] << 8,
  66927. data[offset++] | data[offset++] << 8
  66928. ],
  66929. width: data[offset++] | data[offset++] << 8,
  66930. height: data[offset++] | data[offset++] << 8,
  66931. pixel_size: data[offset++],
  66932. flags: data[offset++]
  66933. };
  66934. return header;
  66935. };
  66936. TGATools.UploadContent = function (gl, data) {
  66937. // Not enough data to contain header ?
  66938. if (data.length < 19) {
  66939. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  66940. return;
  66941. }
  66942. // Read Header
  66943. var offset = 18;
  66944. var header = TGATools.GetTGAHeader(data);
  66945. // Assume it's a valid Targa file.
  66946. if (header.id_length + offset > data.length) {
  66947. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  66948. return;
  66949. }
  66950. // Skip not needed data
  66951. offset += header.id_length;
  66952. var use_rle = false;
  66953. var use_pal = false;
  66954. var use_rgb = false;
  66955. var use_grey = false;
  66956. // Get some informations.
  66957. switch (header.image_type) {
  66958. case TGATools._TYPE_RLE_INDEXED:
  66959. use_rle = true;
  66960. case TGATools._TYPE_INDEXED:
  66961. use_pal = true;
  66962. break;
  66963. case TGATools._TYPE_RLE_RGB:
  66964. use_rle = true;
  66965. case TGATools._TYPE_RGB:
  66966. use_rgb = true;
  66967. break;
  66968. case TGATools._TYPE_RLE_GREY:
  66969. use_rle = true;
  66970. case TGATools._TYPE_GREY:
  66971. use_grey = true;
  66972. break;
  66973. }
  66974. var pixel_data;
  66975. // var numAlphaBits = header.flags & 0xf;
  66976. var pixel_size = header.pixel_size >> 3;
  66977. var pixel_total = header.width * header.height * pixel_size;
  66978. // Read palettes
  66979. var palettes;
  66980. if (use_pal) {
  66981. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  66982. }
  66983. // Read LRE
  66984. if (use_rle) {
  66985. pixel_data = new Uint8Array(pixel_total);
  66986. var c, count, i;
  66987. var localOffset = 0;
  66988. var pixels = new Uint8Array(pixel_size);
  66989. while (offset < pixel_total && localOffset < pixel_total) {
  66990. c = data[offset++];
  66991. count = (c & 0x7f) + 1;
  66992. // RLE pixels
  66993. if (c & 0x80) {
  66994. // Bind pixel tmp array
  66995. for (i = 0; i < pixel_size; ++i) {
  66996. pixels[i] = data[offset++];
  66997. }
  66998. // Copy pixel array
  66999. for (i = 0; i < count; ++i) {
  67000. pixel_data.set(pixels, localOffset + i * pixel_size);
  67001. }
  67002. localOffset += pixel_size * count;
  67003. }
  67004. else {
  67005. count *= pixel_size;
  67006. for (i = 0; i < count; ++i) {
  67007. pixel_data[localOffset + i] = data[offset++];
  67008. }
  67009. localOffset += count;
  67010. }
  67011. }
  67012. }
  67013. else {
  67014. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  67015. }
  67016. // Load to texture
  67017. var x_start, y_start, x_step, y_step, y_end, x_end;
  67018. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  67019. default:
  67020. case TGATools._ORIGIN_UL:
  67021. x_start = 0;
  67022. x_step = 1;
  67023. x_end = header.width;
  67024. y_start = 0;
  67025. y_step = 1;
  67026. y_end = header.height;
  67027. break;
  67028. case TGATools._ORIGIN_BL:
  67029. x_start = 0;
  67030. x_step = 1;
  67031. x_end = header.width;
  67032. y_start = header.height - 1;
  67033. y_step = -1;
  67034. y_end = -1;
  67035. break;
  67036. case TGATools._ORIGIN_UR:
  67037. x_start = header.width - 1;
  67038. x_step = -1;
  67039. x_end = -1;
  67040. y_start = 0;
  67041. y_step = 1;
  67042. y_end = header.height;
  67043. break;
  67044. case TGATools._ORIGIN_BR:
  67045. x_start = header.width - 1;
  67046. x_step = -1;
  67047. x_end = -1;
  67048. y_start = header.height - 1;
  67049. y_step = -1;
  67050. y_end = -1;
  67051. break;
  67052. }
  67053. // Load the specify method
  67054. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  67055. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  67056. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  67057. };
  67058. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67059. var image = pixel_data, colormap = palettes;
  67060. var width = header.width, height = header.height;
  67061. var color, i = 0, x, y;
  67062. var imageData = new Uint8Array(width * height * 4);
  67063. for (y = y_start; y !== y_end; y += y_step) {
  67064. for (x = x_start; x !== x_end; x += x_step, i++) {
  67065. color = image[i];
  67066. imageData[(x + width * y) * 4 + 3] = 255;
  67067. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  67068. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  67069. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  67070. }
  67071. }
  67072. return imageData;
  67073. };
  67074. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67075. var image = pixel_data;
  67076. var width = header.width, height = header.height;
  67077. var color, i = 0, x, y;
  67078. var imageData = new Uint8Array(width * height * 4);
  67079. for (y = y_start; y !== y_end; y += y_step) {
  67080. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67081. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  67082. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  67083. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  67084. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  67085. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  67086. }
  67087. }
  67088. return imageData;
  67089. };
  67090. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67091. var image = pixel_data;
  67092. var width = header.width, height = header.height;
  67093. var i = 0, x, y;
  67094. var imageData = new Uint8Array(width * height * 4);
  67095. for (y = y_start; y !== y_end; y += y_step) {
  67096. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  67097. imageData[(x + width * y) * 4 + 3] = 255;
  67098. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67099. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67100. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67101. }
  67102. }
  67103. return imageData;
  67104. };
  67105. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67106. var image = pixel_data;
  67107. var width = header.width, height = header.height;
  67108. var i = 0, x, y;
  67109. var imageData = new Uint8Array(width * height * 4);
  67110. for (y = y_start; y !== y_end; y += y_step) {
  67111. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  67112. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67113. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67114. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67115. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  67116. }
  67117. }
  67118. return imageData;
  67119. };
  67120. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67121. var image = pixel_data;
  67122. var width = header.width, height = header.height;
  67123. var color, i = 0, x, y;
  67124. var imageData = new Uint8Array(width * height * 4);
  67125. for (y = y_start; y !== y_end; y += y_step) {
  67126. for (x = x_start; x !== x_end; x += x_step, i++) {
  67127. color = image[i];
  67128. imageData[(x + width * y) * 4 + 0] = color;
  67129. imageData[(x + width * y) * 4 + 1] = color;
  67130. imageData[(x + width * y) * 4 + 2] = color;
  67131. imageData[(x + width * y) * 4 + 3] = 255;
  67132. }
  67133. }
  67134. return imageData;
  67135. };
  67136. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67137. var image = pixel_data;
  67138. var width = header.width, height = header.height;
  67139. var i = 0, x, y;
  67140. var imageData = new Uint8Array(width * height * 4);
  67141. for (y = y_start; y !== y_end; y += y_step) {
  67142. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67143. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  67144. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  67145. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67146. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  67147. }
  67148. }
  67149. return imageData;
  67150. };
  67151. //private static _TYPE_NO_DATA = 0;
  67152. TGATools._TYPE_INDEXED = 1;
  67153. TGATools._TYPE_RGB = 2;
  67154. TGATools._TYPE_GREY = 3;
  67155. TGATools._TYPE_RLE_INDEXED = 9;
  67156. TGATools._TYPE_RLE_RGB = 10;
  67157. TGATools._TYPE_RLE_GREY = 11;
  67158. TGATools._ORIGIN_MASK = 0x30;
  67159. TGATools._ORIGIN_SHIFT = 0x04;
  67160. TGATools._ORIGIN_BL = 0x00;
  67161. TGATools._ORIGIN_BR = 0x01;
  67162. TGATools._ORIGIN_UL = 0x02;
  67163. TGATools._ORIGIN_UR = 0x03;
  67164. return TGATools;
  67165. }());
  67166. Internals.TGATools = TGATools;
  67167. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67168. })(BABYLON || (BABYLON = {}));
  67169. //# sourceMappingURL=babylon.tga.js.map
  67170. var BABYLON;
  67171. (function (BABYLON) {
  67172. var Internals;
  67173. (function (Internals) {
  67174. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  67175. // All values and structures referenced from:
  67176. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  67177. var DDS_MAGIC = 0x20534444;
  67178. var
  67179. //DDSD_CAPS = 0x1,
  67180. //DDSD_HEIGHT = 0x2,
  67181. //DDSD_WIDTH = 0x4,
  67182. //DDSD_PITCH = 0x8,
  67183. //DDSD_PIXELFORMAT = 0x1000,
  67184. DDSD_MIPMAPCOUNT = 0x20000;
  67185. //DDSD_LINEARSIZE = 0x80000,
  67186. //DDSD_DEPTH = 0x800000;
  67187. // var DDSCAPS_COMPLEX = 0x8,
  67188. // DDSCAPS_MIPMAP = 0x400000,
  67189. // DDSCAPS_TEXTURE = 0x1000;
  67190. var DDSCAPS2_CUBEMAP = 0x200;
  67191. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  67192. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  67193. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  67194. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  67195. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  67196. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  67197. // DDSCAPS2_VOLUME = 0x200000;
  67198. var
  67199. //DDPF_ALPHAPIXELS = 0x1,
  67200. //DDPF_ALPHA = 0x2,
  67201. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  67202. //DDPF_YUV = 0x200,
  67203. DDPF_LUMINANCE = 0x20000;
  67204. function FourCCToInt32(value) {
  67205. return value.charCodeAt(0) +
  67206. (value.charCodeAt(1) << 8) +
  67207. (value.charCodeAt(2) << 16) +
  67208. (value.charCodeAt(3) << 24);
  67209. }
  67210. function Int32ToFourCC(value) {
  67211. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  67212. }
  67213. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  67214. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  67215. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  67216. var FOURCC_DX10 = FourCCToInt32("DX10");
  67217. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  67218. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  67219. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  67220. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  67221. var headerLengthInt = 31; // The header length in 32 bit ints
  67222. // Offsets into the header array
  67223. var off_magic = 0;
  67224. var off_size = 1;
  67225. var off_flags = 2;
  67226. var off_height = 3;
  67227. var off_width = 4;
  67228. var off_mipmapCount = 7;
  67229. var off_pfFlags = 20;
  67230. var off_pfFourCC = 21;
  67231. var off_RGBbpp = 22;
  67232. // var off_RMask = 23;
  67233. // var off_GMask = 24;
  67234. // var off_BMask = 25;
  67235. // var off_AMask = 26;
  67236. // var off_caps1 = 27;
  67237. var off_caps2 = 28;
  67238. // var off_caps3 = 29;
  67239. // var off_caps4 = 30;
  67240. var off_dxgiFormat = 32;
  67241. ;
  67242. var DDSTools = /** @class */ (function () {
  67243. function DDSTools() {
  67244. }
  67245. DDSTools.GetDDSInfo = function (arrayBuffer) {
  67246. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  67247. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  67248. var mipmapCount = 1;
  67249. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  67250. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67251. }
  67252. var fourCC = header[off_pfFourCC];
  67253. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  67254. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67255. switch (fourCC) {
  67256. case FOURCC_D3DFMT_R16G16B16A16F:
  67257. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67258. break;
  67259. case FOURCC_D3DFMT_R32G32B32A32F:
  67260. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67261. break;
  67262. case FOURCC_DX10:
  67263. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  67264. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67265. break;
  67266. }
  67267. }
  67268. return {
  67269. width: header[off_width],
  67270. height: header[off_height],
  67271. mipmapCount: mipmapCount,
  67272. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  67273. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  67274. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  67275. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  67276. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  67277. dxgiFormat: dxgiFormat,
  67278. textureType: textureType
  67279. };
  67280. };
  67281. DDSTools._ToHalfFloat = function (value) {
  67282. if (!DDSTools._FloatView) {
  67283. DDSTools._FloatView = new Float32Array(1);
  67284. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  67285. }
  67286. DDSTools._FloatView[0] = value;
  67287. var x = DDSTools._Int32View[0];
  67288. var bits = (x >> 16) & 0x8000; /* Get the sign */
  67289. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  67290. var e = (x >> 23) & 0xff; /* Using int is faster here */
  67291. /* If zero, or denormal, or exponent underflows too much for a denormal
  67292. * half, return signed zero. */
  67293. if (e < 103) {
  67294. return bits;
  67295. }
  67296. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  67297. if (e > 142) {
  67298. bits |= 0x7c00;
  67299. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  67300. * not Inf, so make sure we set one mantissa bit too. */
  67301. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  67302. return bits;
  67303. }
  67304. /* If exponent underflows but not too much, return a denormal */
  67305. if (e < 113) {
  67306. m |= 0x0800;
  67307. /* Extra rounding may overflow and set mantissa to 0 and exponent
  67308. * to 1, which is OK. */
  67309. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  67310. return bits;
  67311. }
  67312. bits |= ((e - 112) << 10) | (m >> 1);
  67313. bits += m & 1;
  67314. return bits;
  67315. };
  67316. DDSTools._FromHalfFloat = function (value) {
  67317. var s = (value & 0x8000) >> 15;
  67318. var e = (value & 0x7C00) >> 10;
  67319. var f = value & 0x03FF;
  67320. if (e === 0) {
  67321. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  67322. }
  67323. else if (e == 0x1F) {
  67324. return f ? NaN : ((s ? -1 : 1) * Infinity);
  67325. }
  67326. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  67327. };
  67328. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67329. var destArray = new Float32Array(dataLength);
  67330. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67331. var index = 0;
  67332. for (var y = 0; y < height; y++) {
  67333. for (var x = 0; x < width; x++) {
  67334. var srcPos = (x + y * width) * 4;
  67335. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  67336. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  67337. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  67338. if (DDSTools.StoreLODInAlphaChannel) {
  67339. destArray[index + 3] = lod;
  67340. }
  67341. else {
  67342. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  67343. }
  67344. index += 4;
  67345. }
  67346. }
  67347. return destArray;
  67348. };
  67349. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67350. if (DDSTools.StoreLODInAlphaChannel) {
  67351. var destArray = new Uint16Array(dataLength);
  67352. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67353. var index = 0;
  67354. for (var y = 0; y < height; y++) {
  67355. for (var x = 0; x < width; x++) {
  67356. var srcPos = (x + y * width) * 4;
  67357. destArray[index] = srcData[srcPos];
  67358. destArray[index + 1] = srcData[srcPos + 1];
  67359. destArray[index + 2] = srcData[srcPos + 2];
  67360. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  67361. index += 4;
  67362. }
  67363. }
  67364. return destArray;
  67365. }
  67366. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  67367. };
  67368. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67369. if (DDSTools.StoreLODInAlphaChannel) {
  67370. var destArray = new Float32Array(dataLength);
  67371. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67372. var index = 0;
  67373. for (var y = 0; y < height; y++) {
  67374. for (var x = 0; x < width; x++) {
  67375. var srcPos = (x + y * width) * 4;
  67376. destArray[index] = srcData[srcPos];
  67377. destArray[index + 1] = srcData[srcPos + 1];
  67378. destArray[index + 2] = srcData[srcPos + 2];
  67379. destArray[index + 3] = lod;
  67380. index += 4;
  67381. }
  67382. }
  67383. return destArray;
  67384. }
  67385. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  67386. };
  67387. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67388. var destArray = new Uint8Array(dataLength);
  67389. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67390. var index = 0;
  67391. for (var y = 0; y < height; y++) {
  67392. for (var x = 0; x < width; x++) {
  67393. var srcPos = (x + y * width) * 4;
  67394. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67395. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67396. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67397. if (DDSTools.StoreLODInAlphaChannel) {
  67398. destArray[index + 3] = lod;
  67399. }
  67400. else {
  67401. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67402. }
  67403. index += 4;
  67404. }
  67405. }
  67406. return destArray;
  67407. };
  67408. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67409. var destArray = new Uint8Array(dataLength);
  67410. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67411. var index = 0;
  67412. for (var y = 0; y < height; y++) {
  67413. for (var x = 0; x < width; x++) {
  67414. var srcPos = (x + y * width) * 4;
  67415. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  67416. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  67417. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  67418. if (DDSTools.StoreLODInAlphaChannel) {
  67419. destArray[index + 3] = lod;
  67420. }
  67421. else {
  67422. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  67423. }
  67424. index += 4;
  67425. }
  67426. }
  67427. return destArray;
  67428. };
  67429. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67430. var byteArray = new Uint8Array(dataLength);
  67431. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67432. var index = 0;
  67433. for (var y = 0; y < height; y++) {
  67434. for (var x = 0; x < width; x++) {
  67435. var srcPos = (x + y * width) * 4;
  67436. byteArray[index] = srcData[srcPos + 2];
  67437. byteArray[index + 1] = srcData[srcPos + 1];
  67438. byteArray[index + 2] = srcData[srcPos];
  67439. byteArray[index + 3] = srcData[srcPos + 3];
  67440. index += 4;
  67441. }
  67442. }
  67443. return byteArray;
  67444. };
  67445. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67446. var byteArray = new Uint8Array(dataLength);
  67447. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67448. var index = 0;
  67449. for (var y = 0; y < height; y++) {
  67450. for (var x = 0; x < width; x++) {
  67451. var srcPos = (x + y * width) * 3;
  67452. byteArray[index] = srcData[srcPos + 2];
  67453. byteArray[index + 1] = srcData[srcPos + 1];
  67454. byteArray[index + 2] = srcData[srcPos];
  67455. index += 3;
  67456. }
  67457. }
  67458. return byteArray;
  67459. };
  67460. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67461. var byteArray = new Uint8Array(dataLength);
  67462. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67463. var index = 0;
  67464. for (var y = 0; y < height; y++) {
  67465. for (var x = 0; x < width; x++) {
  67466. var srcPos = (x + y * width);
  67467. byteArray[index] = srcData[srcPos];
  67468. index++;
  67469. }
  67470. }
  67471. return byteArray;
  67472. };
  67473. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  67474. if (lodIndex === void 0) { lodIndex = -1; }
  67475. var ext = engine.getCaps().s3tc;
  67476. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  67477. var internalFormat = 0;
  67478. var format = 0;
  67479. var blockBytes = 1;
  67480. if (header[off_magic] != DDS_MAGIC) {
  67481. BABYLON.Tools.Error("Invalid magic number in DDS header");
  67482. return;
  67483. }
  67484. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  67485. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  67486. return;
  67487. }
  67488. if (info.isCompressed && !ext) {
  67489. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  67490. return;
  67491. }
  67492. var bpp = header[off_RGBbpp];
  67493. dataOffset = header[off_size] + 4;
  67494. var computeFormats = false;
  67495. if (info.isFourCC) {
  67496. fourCC = header[off_pfFourCC];
  67497. switch (fourCC) {
  67498. case FOURCC_DXT1:
  67499. blockBytes = 8;
  67500. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  67501. break;
  67502. case FOURCC_DXT3:
  67503. blockBytes = 16;
  67504. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  67505. break;
  67506. case FOURCC_DXT5:
  67507. blockBytes = 16;
  67508. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  67509. break;
  67510. case FOURCC_D3DFMT_R16G16B16A16F:
  67511. computeFormats = true;
  67512. break;
  67513. case FOURCC_D3DFMT_R32G32B32A32F:
  67514. computeFormats = true;
  67515. break;
  67516. case FOURCC_DX10:
  67517. // There is an additionnal header so dataOffset need to be changed
  67518. dataOffset += 5 * 4; // 5 uints
  67519. var supported = false;
  67520. switch (info.dxgiFormat) {
  67521. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  67522. computeFormats = true;
  67523. supported = true;
  67524. break;
  67525. case DXGI_FORMAT_B8G8R8X8_UNORM:
  67526. info.isRGB = true;
  67527. info.isFourCC = false;
  67528. bpp = 32;
  67529. supported = true;
  67530. break;
  67531. }
  67532. if (supported) {
  67533. break;
  67534. }
  67535. default:
  67536. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  67537. return;
  67538. }
  67539. }
  67540. if (computeFormats) {
  67541. format = engine._getWebGLTextureType(info.textureType);
  67542. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67543. }
  67544. mipmapCount = 1;
  67545. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  67546. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67547. }
  67548. for (var face = 0; face < faces; face++) {
  67549. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67550. width = header[off_width];
  67551. height = header[off_height];
  67552. for (mip = 0; mip < mipmapCount; ++mip) {
  67553. if (lodIndex === -1 || lodIndex === mip) {
  67554. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  67555. var i = (lodIndex === -1) ? mip : 0;
  67556. if (!info.isCompressed && info.isFourCC) {
  67557. dataLength = width * height * 4;
  67558. var FloatArray = null;
  67559. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  67560. if (bpp === 128) {
  67561. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67562. }
  67563. else if (bpp === 64) {
  67564. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67565. }
  67566. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67567. format = engine._getWebGLTextureType(info.textureType);
  67568. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67569. }
  67570. else {
  67571. if (bpp === 128) {
  67572. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67573. }
  67574. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  67575. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67576. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67577. format = engine._getWebGLTextureType(info.textureType);
  67578. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67579. }
  67580. else {
  67581. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67582. }
  67583. }
  67584. if (FloatArray) {
  67585. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  67586. }
  67587. }
  67588. else if (info.isRGB) {
  67589. if (bpp === 24) {
  67590. dataLength = width * height * 3;
  67591. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67592. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  67593. }
  67594. else {
  67595. dataLength = width * height * 4;
  67596. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67597. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  67598. }
  67599. }
  67600. else if (info.isLuminance) {
  67601. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  67602. var unpaddedRowSize = width;
  67603. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  67604. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  67605. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67606. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  67607. }
  67608. else {
  67609. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  67610. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  67611. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  67612. }
  67613. }
  67614. dataOffset += width * height * (bpp / 8);
  67615. width *= 0.5;
  67616. height *= 0.5;
  67617. width = Math.max(1.0, width);
  67618. height = Math.max(1.0, height);
  67619. }
  67620. }
  67621. };
  67622. DDSTools.StoreLODInAlphaChannel = false;
  67623. return DDSTools;
  67624. }());
  67625. Internals.DDSTools = DDSTools;
  67626. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67627. })(BABYLON || (BABYLON = {}));
  67628. //# sourceMappingURL=babylon.dds.js.map
  67629. var BABYLON;
  67630. (function (BABYLON) {
  67631. var Internals;
  67632. (function (Internals) {
  67633. /**
  67634. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  67635. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  67636. */
  67637. var KhronosTextureContainer = /** @class */ (function () {
  67638. /**
  67639. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  67640. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  67641. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  67642. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  67643. */
  67644. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  67645. this.arrayBuffer = arrayBuffer;
  67646. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  67647. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  67648. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  67649. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  67650. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  67651. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  67652. BABYLON.Tools.Error("texture missing KTX identifier");
  67653. return;
  67654. }
  67655. // load the reset of the header in native 32 bit int
  67656. var header = new Int32Array(this.arrayBuffer, 12, 13);
  67657. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  67658. var oppositeEndianess = header[0] === 0x01020304;
  67659. // read all the header elements in order they exist in the file, without modification (sans endainness)
  67660. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  67661. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  67662. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  67663. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  67664. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  67665. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  67666. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  67667. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  67668. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  67669. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  67670. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  67671. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  67672. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  67673. if (this.glType !== 0) {
  67674. BABYLON.Tools.Error("only compressed formats currently supported");
  67675. return;
  67676. }
  67677. else {
  67678. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  67679. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  67680. }
  67681. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  67682. BABYLON.Tools.Error("only 2D textures currently supported");
  67683. return;
  67684. }
  67685. if (this.numberOfArrayElements !== 0) {
  67686. BABYLON.Tools.Error("texture arrays not currently supported");
  67687. return;
  67688. }
  67689. if (this.numberOfFaces !== facesExpected) {
  67690. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  67691. return;
  67692. }
  67693. // we now have a completely validated file, so could use existence of loadType as success
  67694. // would need to make this more elaborate & adjust checks above to support more than one load type
  67695. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  67696. }
  67697. // not as fast hardware based, but will probably never need to use
  67698. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  67699. return ((val & 0xFF) << 24)
  67700. | ((val & 0xFF00) << 8)
  67701. | ((val >> 8) & 0xFF00)
  67702. | ((val >> 24) & 0xFF);
  67703. };
  67704. /**
  67705. * It is assumed that the texture has already been created & is currently bound
  67706. */
  67707. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  67708. switch (this.loadType) {
  67709. case KhronosTextureContainer.COMPRESSED_2D:
  67710. this._upload2DCompressedLevels(gl, loadMipmaps);
  67711. break;
  67712. case KhronosTextureContainer.TEX_2D:
  67713. case KhronosTextureContainer.COMPRESSED_3D:
  67714. case KhronosTextureContainer.TEX_3D:
  67715. }
  67716. };
  67717. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  67718. // initialize width & height for level 1
  67719. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  67720. var width = this.pixelWidth;
  67721. var height = this.pixelHeight;
  67722. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  67723. for (var level = 0; level < mipmapCount; level++) {
  67724. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  67725. for (var face = 0; face < this.numberOfFaces; face++) {
  67726. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67727. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  67728. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  67729. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  67730. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  67731. }
  67732. width = Math.max(1.0, width * 0.5);
  67733. height = Math.max(1.0, height * 0.5);
  67734. }
  67735. };
  67736. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  67737. // load types
  67738. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  67739. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  67740. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  67741. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  67742. return KhronosTextureContainer;
  67743. }());
  67744. Internals.KhronosTextureContainer = KhronosTextureContainer;
  67745. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67746. })(BABYLON || (BABYLON = {}));
  67747. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  67748. var BABYLON;
  67749. (function (BABYLON) {
  67750. var Debug;
  67751. (function (Debug) {
  67752. /**
  67753. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  67754. */
  67755. var SkeletonViewer = /** @class */ (function () {
  67756. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  67757. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  67758. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  67759. this.skeleton = skeleton;
  67760. this.mesh = mesh;
  67761. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  67762. this.renderingGroupId = renderingGroupId;
  67763. this.color = BABYLON.Color3.White();
  67764. this._debugLines = new Array();
  67765. this._isEnabled = false;
  67766. this._scene = scene;
  67767. this.update();
  67768. this._renderFunction = this.update.bind(this);
  67769. }
  67770. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  67771. get: function () {
  67772. return this._isEnabled;
  67773. },
  67774. set: function (value) {
  67775. if (this._isEnabled === value) {
  67776. return;
  67777. }
  67778. this._isEnabled = value;
  67779. if (value) {
  67780. this._scene.registerBeforeRender(this._renderFunction);
  67781. }
  67782. else {
  67783. this._scene.unregisterBeforeRender(this._renderFunction);
  67784. }
  67785. },
  67786. enumerable: true,
  67787. configurable: true
  67788. });
  67789. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  67790. if (x === void 0) { x = 0; }
  67791. if (y === void 0) { y = 0; }
  67792. if (z === void 0) { z = 0; }
  67793. var tmat = BABYLON.Tmp.Matrix[0];
  67794. var parentBone = bone.getParent();
  67795. tmat.copyFrom(bone.getLocalMatrix());
  67796. if (x !== 0 || y !== 0 || z !== 0) {
  67797. var tmat2 = BABYLON.Tmp.Matrix[1];
  67798. BABYLON.Matrix.IdentityToRef(tmat2);
  67799. tmat2.m[12] = x;
  67800. tmat2.m[13] = y;
  67801. tmat2.m[14] = z;
  67802. tmat2.multiplyToRef(tmat, tmat);
  67803. }
  67804. if (parentBone) {
  67805. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  67806. }
  67807. tmat.multiplyToRef(meshMat, tmat);
  67808. position.x = tmat.m[12];
  67809. position.y = tmat.m[13];
  67810. position.z = tmat.m[14];
  67811. };
  67812. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  67813. var len = bones.length;
  67814. var meshPos = this.mesh.position;
  67815. for (var i = 0; i < len; i++) {
  67816. var bone = bones[i];
  67817. var points = this._debugLines[i];
  67818. if (!points) {
  67819. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67820. this._debugLines[i] = points;
  67821. }
  67822. this._getBonePosition(points[0], bone, meshMat);
  67823. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  67824. points[0].subtractInPlace(meshPos);
  67825. points[1].subtractInPlace(meshPos);
  67826. }
  67827. };
  67828. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  67829. var len = bones.length;
  67830. var boneNum = 0;
  67831. var meshPos = this.mesh.position;
  67832. for (var i = len - 1; i >= 0; i--) {
  67833. var childBone = bones[i];
  67834. var parentBone = childBone.getParent();
  67835. if (!parentBone) {
  67836. continue;
  67837. }
  67838. var points = this._debugLines[boneNum];
  67839. if (!points) {
  67840. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67841. this._debugLines[boneNum] = points;
  67842. }
  67843. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  67844. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  67845. points[0].subtractInPlace(meshPos);
  67846. points[1].subtractInPlace(meshPos);
  67847. boneNum++;
  67848. }
  67849. };
  67850. SkeletonViewer.prototype.update = function () {
  67851. if (this.autoUpdateBonesMatrices) {
  67852. this.skeleton.computeAbsoluteTransforms();
  67853. }
  67854. if (this.skeleton.bones[0].length === undefined) {
  67855. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67856. }
  67857. else {
  67858. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67859. }
  67860. if (!this._debugMesh) {
  67861. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  67862. this._debugMesh.renderingGroupId = this.renderingGroupId;
  67863. }
  67864. else {
  67865. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  67866. }
  67867. this._debugMesh.position.copyFrom(this.mesh.position);
  67868. this._debugMesh.color = this.color;
  67869. };
  67870. SkeletonViewer.prototype.dispose = function () {
  67871. if (this._debugMesh) {
  67872. this.isEnabled = false;
  67873. this._debugMesh.dispose();
  67874. this._debugMesh = null;
  67875. }
  67876. };
  67877. return SkeletonViewer;
  67878. }());
  67879. Debug.SkeletonViewer = SkeletonViewer;
  67880. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67881. })(BABYLON || (BABYLON = {}));
  67882. //# sourceMappingURL=babylon.skeletonViewer.js.map
  67883. var BABYLON;
  67884. (function (BABYLON) {
  67885. var Debug;
  67886. (function (Debug) {
  67887. var AxesViewer = /** @class */ (function () {
  67888. function AxesViewer(scene, scaleLines) {
  67889. if (scaleLines === void 0) { scaleLines = 1; }
  67890. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67891. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67892. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67893. this.scaleLines = 1;
  67894. this.scaleLines = scaleLines;
  67895. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  67896. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  67897. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  67898. this._xmesh.renderingGroupId = 2;
  67899. this._ymesh.renderingGroupId = 2;
  67900. this._zmesh.renderingGroupId = 2;
  67901. this._xmesh.material.checkReadyOnlyOnce = true;
  67902. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  67903. this._ymesh.material.checkReadyOnlyOnce = true;
  67904. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  67905. this._zmesh.material.checkReadyOnlyOnce = true;
  67906. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  67907. this.scene = scene;
  67908. }
  67909. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  67910. var scaleLines = this.scaleLines;
  67911. if (this._xmesh) {
  67912. this._xmesh.position.copyFrom(position);
  67913. }
  67914. if (this._ymesh) {
  67915. this._ymesh.position.copyFrom(position);
  67916. }
  67917. if (this._zmesh) {
  67918. this._zmesh.position.copyFrom(position);
  67919. }
  67920. var point2 = this._xline[1];
  67921. point2.x = xaxis.x * scaleLines;
  67922. point2.y = xaxis.y * scaleLines;
  67923. point2.z = xaxis.z * scaleLines;
  67924. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  67925. point2 = this._yline[1];
  67926. point2.x = yaxis.x * scaleLines;
  67927. point2.y = yaxis.y * scaleLines;
  67928. point2.z = yaxis.z * scaleLines;
  67929. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  67930. point2 = this._zline[1];
  67931. point2.x = zaxis.x * scaleLines;
  67932. point2.y = zaxis.y * scaleLines;
  67933. point2.z = zaxis.z * scaleLines;
  67934. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  67935. };
  67936. AxesViewer.prototype.dispose = function () {
  67937. if (this._xmesh) {
  67938. this._xmesh.dispose();
  67939. }
  67940. if (this._ymesh) {
  67941. this._ymesh.dispose();
  67942. }
  67943. if (this._zmesh) {
  67944. this._zmesh.dispose();
  67945. }
  67946. this._xmesh = null;
  67947. this._ymesh = null;
  67948. this._zmesh = null;
  67949. this.scene = null;
  67950. };
  67951. return AxesViewer;
  67952. }());
  67953. Debug.AxesViewer = AxesViewer;
  67954. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67955. })(BABYLON || (BABYLON = {}));
  67956. //# sourceMappingURL=babylon.axesViewer.js.map
  67957. var BABYLON;
  67958. (function (BABYLON) {
  67959. var Debug;
  67960. (function (Debug) {
  67961. var BoneAxesViewer = /** @class */ (function (_super) {
  67962. __extends(BoneAxesViewer, _super);
  67963. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  67964. if (scaleLines === void 0) { scaleLines = 1; }
  67965. var _this = _super.call(this, scene, scaleLines) || this;
  67966. _this.pos = BABYLON.Vector3.Zero();
  67967. _this.xaxis = BABYLON.Vector3.Zero();
  67968. _this.yaxis = BABYLON.Vector3.Zero();
  67969. _this.zaxis = BABYLON.Vector3.Zero();
  67970. _this.mesh = mesh;
  67971. _this.bone = bone;
  67972. return _this;
  67973. }
  67974. BoneAxesViewer.prototype.update = function () {
  67975. if (!this.mesh || !this.bone) {
  67976. return;
  67977. }
  67978. var bone = this.bone;
  67979. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  67980. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  67981. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  67982. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  67983. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  67984. };
  67985. BoneAxesViewer.prototype.dispose = function () {
  67986. if (this.mesh) {
  67987. this.mesh = null;
  67988. this.bone = null;
  67989. _super.prototype.dispose.call(this);
  67990. }
  67991. };
  67992. return BoneAxesViewer;
  67993. }(Debug.AxesViewer));
  67994. Debug.BoneAxesViewer = BoneAxesViewer;
  67995. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67996. })(BABYLON || (BABYLON = {}));
  67997. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  67998. var BABYLON;
  67999. (function (BABYLON) {
  68000. var RayHelper = /** @class */ (function () {
  68001. function RayHelper(ray) {
  68002. this.ray = ray;
  68003. }
  68004. RayHelper.CreateAndShow = function (ray, scene, color) {
  68005. var helper = new RayHelper(ray);
  68006. helper.show(scene, color);
  68007. return helper;
  68008. };
  68009. RayHelper.prototype.show = function (scene, color) {
  68010. if (!this._renderFunction && this.ray) {
  68011. var ray = this.ray;
  68012. this._renderFunction = this._render.bind(this);
  68013. this._scene = scene;
  68014. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  68015. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  68016. if (this._renderFunction) {
  68017. this._scene.registerBeforeRender(this._renderFunction);
  68018. }
  68019. }
  68020. if (color && this._renderLine) {
  68021. this._renderLine.color.copyFrom(color);
  68022. }
  68023. };
  68024. RayHelper.prototype.hide = function () {
  68025. if (this._renderFunction && this._scene) {
  68026. this._scene.unregisterBeforeRender(this._renderFunction);
  68027. this._scene = null;
  68028. this._renderFunction = null;
  68029. if (this._renderLine) {
  68030. this._renderLine.dispose();
  68031. this._renderLine = null;
  68032. }
  68033. this._renderPoints = [];
  68034. }
  68035. };
  68036. RayHelper.prototype._render = function () {
  68037. var ray = this.ray;
  68038. if (!ray) {
  68039. return;
  68040. }
  68041. var point = this._renderPoints[1];
  68042. var len = Math.min(ray.length, 1000000);
  68043. point.copyFrom(ray.direction);
  68044. point.scaleInPlace(len);
  68045. point.addInPlace(ray.origin);
  68046. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  68047. };
  68048. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  68049. this._attachedToMesh = mesh;
  68050. var ray = this.ray;
  68051. if (!ray) {
  68052. return;
  68053. }
  68054. if (!ray.direction) {
  68055. ray.direction = BABYLON.Vector3.Zero();
  68056. }
  68057. if (!ray.origin) {
  68058. ray.origin = BABYLON.Vector3.Zero();
  68059. }
  68060. if (length) {
  68061. ray.length = length;
  68062. }
  68063. if (!meshSpaceOrigin) {
  68064. meshSpaceOrigin = BABYLON.Vector3.Zero();
  68065. }
  68066. if (!meshSpaceDirection) {
  68067. // -1 so that this will work with Mesh.lookAt
  68068. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  68069. }
  68070. if (!this._meshSpaceDirection) {
  68071. this._meshSpaceDirection = meshSpaceDirection.clone();
  68072. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  68073. }
  68074. else {
  68075. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  68076. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  68077. }
  68078. if (!this._updateToMeshFunction) {
  68079. this._updateToMeshFunction = this._updateToMesh.bind(this);
  68080. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  68081. }
  68082. this._updateToMesh();
  68083. };
  68084. RayHelper.prototype.detachFromMesh = function () {
  68085. if (this._attachedToMesh) {
  68086. if (this._updateToMeshFunction) {
  68087. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  68088. }
  68089. this._attachedToMesh = null;
  68090. this._updateToMeshFunction = null;
  68091. }
  68092. };
  68093. RayHelper.prototype._updateToMesh = function () {
  68094. var ray = this.ray;
  68095. if (!this._attachedToMesh || !ray) {
  68096. return;
  68097. }
  68098. if (this._attachedToMesh._isDisposed) {
  68099. this.detachFromMesh();
  68100. return;
  68101. }
  68102. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  68103. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  68104. };
  68105. RayHelper.prototype.dispose = function () {
  68106. this.hide();
  68107. this.detachFromMesh();
  68108. this.ray = null;
  68109. };
  68110. return RayHelper;
  68111. }());
  68112. BABYLON.RayHelper = RayHelper;
  68113. })(BABYLON || (BABYLON = {}));
  68114. //# sourceMappingURL=babylon.rayHelper.js.map
  68115. var BABYLON;
  68116. (function (BABYLON) {
  68117. // load the inspector using require, if not present in the global namespace.
  68118. var DebugLayer = /** @class */ (function () {
  68119. function DebugLayer(scene) {
  68120. this._scene = scene;
  68121. // load inspector using require, if it doesn't exist on the global namespace.
  68122. INSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : (typeof require !== 'undefined' ? require('INSPECTOR') : undefined);
  68123. }
  68124. /** Creates the inspector window. */
  68125. DebugLayer.prototype._createInspector = function (config) {
  68126. if (config === void 0) { config = {}; }
  68127. var popup = config.popup || false;
  68128. var initialTab = config.initialTab || 0;
  68129. var parentElement = config.parentElement || null;
  68130. if (!this._inspector) {
  68131. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  68132. } // else nothing to do,; instance is already existing
  68133. };
  68134. DebugLayer.prototype.isVisible = function () {
  68135. if (!this._inspector) {
  68136. return false;
  68137. }
  68138. return true;
  68139. };
  68140. DebugLayer.prototype.hide = function () {
  68141. if (this._inspector) {
  68142. try {
  68143. this._inspector.dispose();
  68144. }
  68145. catch (e) {
  68146. // If the inspector has been removed directly from the inspector tool
  68147. }
  68148. this._inspector = null;
  68149. }
  68150. };
  68151. DebugLayer.prototype.show = function (config) {
  68152. if (config === void 0) { config = {}; }
  68153. if (typeof INSPECTOR == 'undefined') {
  68154. // Load inspector and add it to the DOM
  68155. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  68156. }
  68157. else {
  68158. // Otherwise creates the inspector
  68159. this._createInspector(config);
  68160. }
  68161. };
  68162. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  68163. return DebugLayer;
  68164. }());
  68165. BABYLON.DebugLayer = DebugLayer;
  68166. })(BABYLON || (BABYLON = {}));
  68167. //# sourceMappingURL=babylon.debugLayer.js.map
  68168. var BABYLON;
  68169. (function (BABYLON) {
  68170. var Debug;
  68171. (function (Debug) {
  68172. var PhysicsViewer = /** @class */ (function () {
  68173. function PhysicsViewer(scene) {
  68174. this._impostors = [];
  68175. this._meshes = [];
  68176. this._numMeshes = 0;
  68177. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68178. var physicEngine = this._scene.getPhysicsEngine();
  68179. if (physicEngine) {
  68180. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  68181. }
  68182. }
  68183. PhysicsViewer.prototype._updateDebugMeshes = function () {
  68184. var plugin = this._physicsEnginePlugin;
  68185. for (var i = 0; i < this._numMeshes; i++) {
  68186. var impostor = this._impostors[i];
  68187. if (!impostor) {
  68188. continue;
  68189. }
  68190. if (impostor.isDisposed) {
  68191. this.hideImpostor(this._impostors[i--]);
  68192. }
  68193. else {
  68194. var mesh = this._meshes[i];
  68195. if (mesh && plugin) {
  68196. plugin.syncMeshWithImpostor(mesh, impostor);
  68197. }
  68198. }
  68199. }
  68200. };
  68201. PhysicsViewer.prototype.showImpostor = function (impostor) {
  68202. if (!this._scene) {
  68203. return;
  68204. }
  68205. for (var i = 0; i < this._numMeshes; i++) {
  68206. if (this._impostors[i] == impostor) {
  68207. return;
  68208. }
  68209. }
  68210. var debugMesh = this._getDebugMesh(impostor, this._scene);
  68211. if (debugMesh) {
  68212. this._impostors[this._numMeshes] = impostor;
  68213. this._meshes[this._numMeshes] = debugMesh;
  68214. if (this._numMeshes === 0) {
  68215. this._renderFunction = this._updateDebugMeshes.bind(this);
  68216. this._scene.registerBeforeRender(this._renderFunction);
  68217. }
  68218. this._numMeshes++;
  68219. }
  68220. };
  68221. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  68222. if (!impostor || !this._scene) {
  68223. return;
  68224. }
  68225. var removed = false;
  68226. for (var i = 0; i < this._numMeshes; i++) {
  68227. if (this._impostors[i] == impostor) {
  68228. var mesh = this._meshes[i];
  68229. if (!mesh) {
  68230. continue;
  68231. }
  68232. this._scene.removeMesh(mesh);
  68233. mesh.dispose();
  68234. this._numMeshes--;
  68235. if (this._numMeshes > 0) {
  68236. this._meshes[i] = this._meshes[this._numMeshes];
  68237. this._impostors[i] = this._impostors[this._numMeshes];
  68238. this._meshes[this._numMeshes] = null;
  68239. this._impostors[this._numMeshes] = null;
  68240. }
  68241. else {
  68242. this._meshes[0] = null;
  68243. this._impostors[0] = null;
  68244. }
  68245. removed = true;
  68246. break;
  68247. }
  68248. }
  68249. if (removed && this._numMeshes === 0) {
  68250. this._scene.unregisterBeforeRender(this._renderFunction);
  68251. }
  68252. };
  68253. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  68254. if (!this._debugMaterial) {
  68255. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  68256. this._debugMaterial.wireframe = true;
  68257. }
  68258. return this._debugMaterial;
  68259. };
  68260. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  68261. if (!this._debugBoxMesh) {
  68262. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  68263. this._debugBoxMesh.renderingGroupId = 1;
  68264. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68265. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  68266. scene.removeMesh(this._debugBoxMesh);
  68267. }
  68268. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  68269. };
  68270. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  68271. if (!this._debugSphereMesh) {
  68272. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  68273. this._debugSphereMesh.renderingGroupId = 1;
  68274. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68275. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  68276. scene.removeMesh(this._debugSphereMesh);
  68277. }
  68278. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  68279. };
  68280. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  68281. var mesh = null;
  68282. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  68283. mesh = this._getDebugBoxMesh(scene);
  68284. impostor.getBoxSizeToRef(mesh.scaling);
  68285. }
  68286. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  68287. mesh = this._getDebugSphereMesh(scene);
  68288. var radius = impostor.getRadius();
  68289. mesh.scaling.x = radius * 2;
  68290. mesh.scaling.y = radius * 2;
  68291. mesh.scaling.z = radius * 2;
  68292. }
  68293. return mesh;
  68294. };
  68295. PhysicsViewer.prototype.dispose = function () {
  68296. for (var i = 0; i < this._numMeshes; i++) {
  68297. this.hideImpostor(this._impostors[i]);
  68298. }
  68299. if (this._debugBoxMesh) {
  68300. this._debugBoxMesh.dispose();
  68301. }
  68302. if (this._debugSphereMesh) {
  68303. this._debugSphereMesh.dispose();
  68304. }
  68305. if (this._debugMaterial) {
  68306. this._debugMaterial.dispose();
  68307. }
  68308. this._impostors.length = 0;
  68309. this._scene = null;
  68310. this._physicsEnginePlugin = null;
  68311. };
  68312. return PhysicsViewer;
  68313. }());
  68314. Debug.PhysicsViewer = PhysicsViewer;
  68315. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68316. })(BABYLON || (BABYLON = {}));
  68317. //# sourceMappingURL=babylon.physicsViewer.js.map
  68318. var BABYLON;
  68319. (function (BABYLON) {
  68320. var BoundingBoxRenderer = /** @class */ (function () {
  68321. function BoundingBoxRenderer(scene) {
  68322. this.frontColor = new BABYLON.Color3(1, 1, 1);
  68323. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  68324. this.showBackLines = true;
  68325. this.renderList = new BABYLON.SmartArray(32);
  68326. this._vertexBuffers = {};
  68327. this._scene = scene;
  68328. }
  68329. BoundingBoxRenderer.prototype._prepareRessources = function () {
  68330. if (this._colorShader) {
  68331. return;
  68332. }
  68333. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  68334. attributes: [BABYLON.VertexBuffer.PositionKind],
  68335. uniforms: ["world", "viewProjection", "color"]
  68336. });
  68337. var engine = this._scene.getEngine();
  68338. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  68339. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  68340. this._createIndexBuffer();
  68341. };
  68342. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  68343. var engine = this._scene.getEngine();
  68344. 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]);
  68345. };
  68346. BoundingBoxRenderer.prototype._rebuild = function () {
  68347. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68348. if (vb) {
  68349. vb._rebuild();
  68350. }
  68351. this._createIndexBuffer();
  68352. };
  68353. BoundingBoxRenderer.prototype.reset = function () {
  68354. this.renderList.reset();
  68355. };
  68356. BoundingBoxRenderer.prototype.render = function () {
  68357. if (this.renderList.length === 0) {
  68358. return;
  68359. }
  68360. this._prepareRessources();
  68361. if (!this._colorShader.isReady()) {
  68362. return;
  68363. }
  68364. var engine = this._scene.getEngine();
  68365. engine.setDepthWrite(false);
  68366. this._colorShader._preBind();
  68367. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  68368. var boundingBox = this.renderList.data[boundingBoxIndex];
  68369. var min = boundingBox.minimum;
  68370. var max = boundingBox.maximum;
  68371. var diff = max.subtract(min);
  68372. var median = min.add(diff.scale(0.5));
  68373. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68374. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68375. .multiply(boundingBox.getWorldMatrix());
  68376. // VBOs
  68377. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68378. if (this.showBackLines) {
  68379. // Back
  68380. engine.setDepthFunctionToGreaterOrEqual();
  68381. this._scene.resetCachedMaterial();
  68382. this._colorShader.setColor4("color", this.backColor.toColor4());
  68383. this._colorShader.bind(worldMatrix);
  68384. // Draw order
  68385. engine.draw(false, 0, 24);
  68386. }
  68387. // Front
  68388. engine.setDepthFunctionToLess();
  68389. this._scene.resetCachedMaterial();
  68390. this._colorShader.setColor4("color", this.frontColor.toColor4());
  68391. this._colorShader.bind(worldMatrix);
  68392. // Draw order
  68393. engine.draw(false, 0, 24);
  68394. }
  68395. this._colorShader.unbind();
  68396. engine.setDepthFunctionToLessOrEqual();
  68397. engine.setDepthWrite(true);
  68398. };
  68399. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68400. this._prepareRessources();
  68401. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68402. return;
  68403. }
  68404. var engine = this._scene.getEngine();
  68405. engine.setDepthWrite(false);
  68406. engine.setColorWrite(false);
  68407. this._colorShader._preBind();
  68408. var boundingBox = mesh._boundingInfo.boundingBox;
  68409. var min = boundingBox.minimum;
  68410. var max = boundingBox.maximum;
  68411. var diff = max.subtract(min);
  68412. var median = min.add(diff.scale(0.5));
  68413. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68414. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68415. .multiply(boundingBox.getWorldMatrix());
  68416. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68417. engine.setDepthFunctionToLess();
  68418. this._scene.resetCachedMaterial();
  68419. this._colorShader.bind(worldMatrix);
  68420. engine.draw(false, 0, 24);
  68421. this._colorShader.unbind();
  68422. engine.setDepthFunctionToLessOrEqual();
  68423. engine.setDepthWrite(true);
  68424. engine.setColorWrite(true);
  68425. };
  68426. BoundingBoxRenderer.prototype.dispose = function () {
  68427. if (!this._colorShader) {
  68428. return;
  68429. }
  68430. this.renderList.dispose();
  68431. this._colorShader.dispose();
  68432. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68433. if (buffer) {
  68434. buffer.dispose();
  68435. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68436. }
  68437. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68438. };
  68439. return BoundingBoxRenderer;
  68440. }());
  68441. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  68442. })(BABYLON || (BABYLON = {}));
  68443. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  68444. var BABYLON;
  68445. (function (BABYLON) {
  68446. var MorphTarget = /** @class */ (function () {
  68447. function MorphTarget(name, influence) {
  68448. if (influence === void 0) { influence = 0; }
  68449. this.name = name;
  68450. this.animations = new Array();
  68451. this._positions = null;
  68452. this._normals = null;
  68453. this._tangents = null;
  68454. this.onInfluenceChanged = new BABYLON.Observable();
  68455. this.influence = influence;
  68456. }
  68457. Object.defineProperty(MorphTarget.prototype, "influence", {
  68458. get: function () {
  68459. return this._influence;
  68460. },
  68461. set: function (influence) {
  68462. if (this._influence === influence) {
  68463. return;
  68464. }
  68465. var previous = this._influence;
  68466. this._influence = influence;
  68467. if (this.onInfluenceChanged.hasObservers) {
  68468. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  68469. }
  68470. },
  68471. enumerable: true,
  68472. configurable: true
  68473. });
  68474. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  68475. get: function () {
  68476. return !!this._positions;
  68477. },
  68478. enumerable: true,
  68479. configurable: true
  68480. });
  68481. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  68482. get: function () {
  68483. return !!this._normals;
  68484. },
  68485. enumerable: true,
  68486. configurable: true
  68487. });
  68488. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  68489. get: function () {
  68490. return !!this._tangents;
  68491. },
  68492. enumerable: true,
  68493. configurable: true
  68494. });
  68495. MorphTarget.prototype.setPositions = function (data) {
  68496. this._positions = data;
  68497. };
  68498. MorphTarget.prototype.getPositions = function () {
  68499. return this._positions;
  68500. };
  68501. MorphTarget.prototype.setNormals = function (data) {
  68502. this._normals = data;
  68503. };
  68504. MorphTarget.prototype.getNormals = function () {
  68505. return this._normals;
  68506. };
  68507. MorphTarget.prototype.setTangents = function (data) {
  68508. this._tangents = data;
  68509. };
  68510. MorphTarget.prototype.getTangents = function () {
  68511. return this._tangents;
  68512. };
  68513. /**
  68514. * Serializes the current target into a Serialization object.
  68515. * Returns the serialized object.
  68516. */
  68517. MorphTarget.prototype.serialize = function () {
  68518. var serializationObject = {};
  68519. serializationObject.name = this.name;
  68520. serializationObject.influence = this.influence;
  68521. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  68522. if (this.hasNormals) {
  68523. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  68524. }
  68525. if (this.hasTangents) {
  68526. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  68527. }
  68528. // Animations
  68529. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  68530. return serializationObject;
  68531. };
  68532. // Statics
  68533. MorphTarget.Parse = function (serializationObject) {
  68534. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  68535. result.setPositions(serializationObject.positions);
  68536. if (serializationObject.normals) {
  68537. result.setNormals(serializationObject.normals);
  68538. }
  68539. if (serializationObject.tangents) {
  68540. result.setTangents(serializationObject.tangents);
  68541. }
  68542. // Animations
  68543. if (serializationObject.animations) {
  68544. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  68545. var parsedAnimation = serializationObject.animations[animationIndex];
  68546. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68547. }
  68548. }
  68549. return result;
  68550. };
  68551. MorphTarget.FromMesh = function (mesh, name, influence) {
  68552. if (!name) {
  68553. name = mesh.name;
  68554. }
  68555. var result = new MorphTarget(name, influence);
  68556. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68557. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68558. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  68559. }
  68560. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  68561. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  68562. }
  68563. return result;
  68564. };
  68565. return MorphTarget;
  68566. }());
  68567. BABYLON.MorphTarget = MorphTarget;
  68568. })(BABYLON || (BABYLON = {}));
  68569. //# sourceMappingURL=babylon.morphTarget.js.map
  68570. var BABYLON;
  68571. (function (BABYLON) {
  68572. var MorphTargetManager = /** @class */ (function () {
  68573. function MorphTargetManager(scene) {
  68574. if (scene === void 0) { scene = null; }
  68575. this._targets = new Array();
  68576. this._targetObservable = new Array();
  68577. this._activeTargets = new BABYLON.SmartArray(16);
  68578. this._supportsNormals = false;
  68579. this._supportsTangents = false;
  68580. this._vertexCount = 0;
  68581. this._uniqueId = 0;
  68582. this._tempInfluences = new Array();
  68583. if (!scene) {
  68584. scene = BABYLON.Engine.LastCreatedScene;
  68585. }
  68586. this._scene = scene;
  68587. if (this._scene) {
  68588. this._scene.morphTargetManagers.push(this);
  68589. this._uniqueId = this._scene.getUniqueId();
  68590. }
  68591. }
  68592. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  68593. get: function () {
  68594. return this._uniqueId;
  68595. },
  68596. enumerable: true,
  68597. configurable: true
  68598. });
  68599. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  68600. get: function () {
  68601. return this._vertexCount;
  68602. },
  68603. enumerable: true,
  68604. configurable: true
  68605. });
  68606. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  68607. get: function () {
  68608. return this._supportsNormals;
  68609. },
  68610. enumerable: true,
  68611. configurable: true
  68612. });
  68613. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  68614. get: function () {
  68615. return this._supportsTangents;
  68616. },
  68617. enumerable: true,
  68618. configurable: true
  68619. });
  68620. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  68621. get: function () {
  68622. return this._targets.length;
  68623. },
  68624. enumerable: true,
  68625. configurable: true
  68626. });
  68627. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  68628. get: function () {
  68629. return this._activeTargets.length;
  68630. },
  68631. enumerable: true,
  68632. configurable: true
  68633. });
  68634. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  68635. get: function () {
  68636. return this._influences;
  68637. },
  68638. enumerable: true,
  68639. configurable: true
  68640. });
  68641. MorphTargetManager.prototype.getActiveTarget = function (index) {
  68642. return this._activeTargets.data[index];
  68643. };
  68644. MorphTargetManager.prototype.getTarget = function (index) {
  68645. return this._targets[index];
  68646. };
  68647. MorphTargetManager.prototype.addTarget = function (target) {
  68648. var _this = this;
  68649. this._targets.push(target);
  68650. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  68651. _this._syncActiveTargets(needUpdate);
  68652. }));
  68653. this._syncActiveTargets(true);
  68654. };
  68655. MorphTargetManager.prototype.removeTarget = function (target) {
  68656. var index = this._targets.indexOf(target);
  68657. if (index >= 0) {
  68658. this._targets.splice(index, 1);
  68659. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  68660. this._syncActiveTargets(true);
  68661. }
  68662. };
  68663. /**
  68664. * Serializes the current manager into a Serialization object.
  68665. * Returns the serialized object.
  68666. */
  68667. MorphTargetManager.prototype.serialize = function () {
  68668. var serializationObject = {};
  68669. serializationObject.id = this.uniqueId;
  68670. serializationObject.targets = [];
  68671. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68672. var target = _a[_i];
  68673. serializationObject.targets.push(target.serialize());
  68674. }
  68675. return serializationObject;
  68676. };
  68677. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  68678. var influenceCount = 0;
  68679. this._activeTargets.reset();
  68680. this._supportsNormals = true;
  68681. this._supportsTangents = true;
  68682. this._vertexCount = 0;
  68683. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68684. var target = _a[_i];
  68685. if (target.influence > 0) {
  68686. this._activeTargets.push(target);
  68687. this._tempInfluences[influenceCount++] = target.influence;
  68688. this._supportsNormals = this._supportsNormals && target.hasNormals;
  68689. this._supportsTangents = this._supportsTangents && target.hasTangents;
  68690. var positions = target.getPositions();
  68691. if (!positions) {
  68692. BABYLON.Tools.Error("Invalid target. Target must positions.");
  68693. return;
  68694. }
  68695. var vertexCount = positions.length / 3;
  68696. if (this._vertexCount === 0) {
  68697. this._vertexCount = vertexCount;
  68698. }
  68699. else if (this._vertexCount !== vertexCount) {
  68700. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  68701. return;
  68702. }
  68703. }
  68704. }
  68705. if (!this._influences || this._influences.length !== influenceCount) {
  68706. this._influences = new Float32Array(influenceCount);
  68707. }
  68708. for (var index = 0; index < influenceCount; index++) {
  68709. this._influences[index] = this._tempInfluences[index];
  68710. }
  68711. if (needUpdate && this._scene) {
  68712. // Flag meshes as dirty to resync with the active targets
  68713. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  68714. var mesh = _c[_b];
  68715. if (mesh.morphTargetManager === this) {
  68716. mesh._syncGeometryWithMorphTargetManager();
  68717. }
  68718. }
  68719. }
  68720. };
  68721. // Statics
  68722. MorphTargetManager.Parse = function (serializationObject, scene) {
  68723. var result = new MorphTargetManager(scene);
  68724. result._uniqueId = serializationObject.id;
  68725. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  68726. var targetData = _a[_i];
  68727. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  68728. }
  68729. return result;
  68730. };
  68731. return MorphTargetManager;
  68732. }());
  68733. BABYLON.MorphTargetManager = MorphTargetManager;
  68734. })(BABYLON || (BABYLON = {}));
  68735. //# sourceMappingURL=babylon.morphTargetManager.js.map
  68736. var BABYLON;
  68737. (function (BABYLON) {
  68738. var Octree = /** @class */ (function () {
  68739. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  68740. if (maxDepth === void 0) { maxDepth = 2; }
  68741. this.maxDepth = maxDepth;
  68742. this.dynamicContent = new Array();
  68743. this._maxBlockCapacity = maxBlockCapacity || 64;
  68744. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  68745. this._creationFunc = creationFunc;
  68746. }
  68747. // Methods
  68748. Octree.prototype.update = function (worldMin, worldMax, entries) {
  68749. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  68750. };
  68751. Octree.prototype.addMesh = function (entry) {
  68752. for (var index = 0; index < this.blocks.length; index++) {
  68753. var block = this.blocks[index];
  68754. block.addEntry(entry);
  68755. }
  68756. };
  68757. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  68758. this._selectionContent.reset();
  68759. for (var index = 0; index < this.blocks.length; index++) {
  68760. var block = this.blocks[index];
  68761. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  68762. }
  68763. if (allowDuplicate) {
  68764. this._selectionContent.concat(this.dynamicContent);
  68765. }
  68766. else {
  68767. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68768. }
  68769. return this._selectionContent;
  68770. };
  68771. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  68772. this._selectionContent.reset();
  68773. for (var index = 0; index < this.blocks.length; index++) {
  68774. var block = this.blocks[index];
  68775. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  68776. }
  68777. if (allowDuplicate) {
  68778. this._selectionContent.concat(this.dynamicContent);
  68779. }
  68780. else {
  68781. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68782. }
  68783. return this._selectionContent;
  68784. };
  68785. Octree.prototype.intersectsRay = function (ray) {
  68786. this._selectionContent.reset();
  68787. for (var index = 0; index < this.blocks.length; index++) {
  68788. var block = this.blocks[index];
  68789. block.intersectsRay(ray, this._selectionContent);
  68790. }
  68791. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68792. return this._selectionContent;
  68793. };
  68794. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  68795. target.blocks = new Array();
  68796. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  68797. // Segmenting space
  68798. for (var x = 0; x < 2; x++) {
  68799. for (var y = 0; y < 2; y++) {
  68800. for (var z = 0; z < 2; z++) {
  68801. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  68802. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  68803. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  68804. block.addEntries(entries);
  68805. target.blocks.push(block);
  68806. }
  68807. }
  68808. }
  68809. };
  68810. Octree.CreationFuncForMeshes = function (entry, block) {
  68811. var boundingInfo = entry.getBoundingInfo();
  68812. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68813. block.entries.push(entry);
  68814. }
  68815. };
  68816. Octree.CreationFuncForSubMeshes = function (entry, block) {
  68817. var boundingInfo = entry.getBoundingInfo();
  68818. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68819. block.entries.push(entry);
  68820. }
  68821. };
  68822. return Octree;
  68823. }());
  68824. BABYLON.Octree = Octree;
  68825. })(BABYLON || (BABYLON = {}));
  68826. //# sourceMappingURL=babylon.octree.js.map
  68827. var BABYLON;
  68828. (function (BABYLON) {
  68829. var OctreeBlock = /** @class */ (function () {
  68830. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  68831. this.entries = new Array();
  68832. this._boundingVectors = new Array();
  68833. this._capacity = capacity;
  68834. this._depth = depth;
  68835. this._maxDepth = maxDepth;
  68836. this._creationFunc = creationFunc;
  68837. this._minPoint = minPoint;
  68838. this._maxPoint = maxPoint;
  68839. this._boundingVectors.push(minPoint.clone());
  68840. this._boundingVectors.push(maxPoint.clone());
  68841. this._boundingVectors.push(minPoint.clone());
  68842. this._boundingVectors[2].x = maxPoint.x;
  68843. this._boundingVectors.push(minPoint.clone());
  68844. this._boundingVectors[3].y = maxPoint.y;
  68845. this._boundingVectors.push(minPoint.clone());
  68846. this._boundingVectors[4].z = maxPoint.z;
  68847. this._boundingVectors.push(maxPoint.clone());
  68848. this._boundingVectors[5].z = minPoint.z;
  68849. this._boundingVectors.push(maxPoint.clone());
  68850. this._boundingVectors[6].x = minPoint.x;
  68851. this._boundingVectors.push(maxPoint.clone());
  68852. this._boundingVectors[7].y = minPoint.y;
  68853. }
  68854. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  68855. // Property
  68856. get: function () {
  68857. return this._capacity;
  68858. },
  68859. enumerable: true,
  68860. configurable: true
  68861. });
  68862. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  68863. get: function () {
  68864. return this._minPoint;
  68865. },
  68866. enumerable: true,
  68867. configurable: true
  68868. });
  68869. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  68870. get: function () {
  68871. return this._maxPoint;
  68872. },
  68873. enumerable: true,
  68874. configurable: true
  68875. });
  68876. // Methods
  68877. OctreeBlock.prototype.addEntry = function (entry) {
  68878. if (this.blocks) {
  68879. for (var index = 0; index < this.blocks.length; index++) {
  68880. var block = this.blocks[index];
  68881. block.addEntry(entry);
  68882. }
  68883. return;
  68884. }
  68885. this._creationFunc(entry, this);
  68886. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  68887. this.createInnerBlocks();
  68888. }
  68889. };
  68890. OctreeBlock.prototype.addEntries = function (entries) {
  68891. for (var index = 0; index < entries.length; index++) {
  68892. var mesh = entries[index];
  68893. this.addEntry(mesh);
  68894. }
  68895. };
  68896. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  68897. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  68898. if (this.blocks) {
  68899. for (var index = 0; index < this.blocks.length; index++) {
  68900. var block = this.blocks[index];
  68901. block.select(frustumPlanes, selection, allowDuplicate);
  68902. }
  68903. return;
  68904. }
  68905. if (allowDuplicate) {
  68906. selection.concat(this.entries);
  68907. }
  68908. else {
  68909. selection.concatWithNoDuplicate(this.entries);
  68910. }
  68911. }
  68912. };
  68913. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  68914. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  68915. if (this.blocks) {
  68916. for (var index = 0; index < this.blocks.length; index++) {
  68917. var block = this.blocks[index];
  68918. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  68919. }
  68920. return;
  68921. }
  68922. if (allowDuplicate) {
  68923. selection.concat(this.entries);
  68924. }
  68925. else {
  68926. selection.concatWithNoDuplicate(this.entries);
  68927. }
  68928. }
  68929. };
  68930. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  68931. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  68932. if (this.blocks) {
  68933. for (var index = 0; index < this.blocks.length; index++) {
  68934. var block = this.blocks[index];
  68935. block.intersectsRay(ray, selection);
  68936. }
  68937. return;
  68938. }
  68939. selection.concatWithNoDuplicate(this.entries);
  68940. }
  68941. };
  68942. OctreeBlock.prototype.createInnerBlocks = function () {
  68943. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  68944. };
  68945. return OctreeBlock;
  68946. }());
  68947. BABYLON.OctreeBlock = OctreeBlock;
  68948. })(BABYLON || (BABYLON = {}));
  68949. //# sourceMappingURL=babylon.octreeBlock.js.map
  68950. var BABYLON;
  68951. (function (BABYLON) {
  68952. var SIMDVector3 = /** @class */ (function () {
  68953. function SIMDVector3() {
  68954. }
  68955. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  68956. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  68957. };
  68958. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  68959. var m = transformation.m;
  68960. var m0 = SIMD.Float32x4.load(m, 0);
  68961. var m1 = SIMD.Float32x4.load(m, 4);
  68962. var m2 = SIMD.Float32x4.load(m, 8);
  68963. var m3 = SIMD.Float32x4.load(m, 12);
  68964. 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));
  68965. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  68966. result.x = SIMD.Float32x4.extractLane(r, 0);
  68967. result.y = SIMD.Float32x4.extractLane(r, 1);
  68968. result.z = SIMD.Float32x4.extractLane(r, 2);
  68969. };
  68970. return SIMDVector3;
  68971. }());
  68972. var SIMDMatrix = /** @class */ (function () {
  68973. function SIMDMatrix() {
  68974. }
  68975. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  68976. var tm = this.m;
  68977. var om = other.m;
  68978. var m0 = SIMD.Float32x4.load(om, 0);
  68979. var m1 = SIMD.Float32x4.load(om, 4);
  68980. var m2 = SIMD.Float32x4.load(om, 8);
  68981. var m3 = SIMD.Float32x4.load(om, 12);
  68982. for (var i = 0; i < 16; i += 4) {
  68983. 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)))));
  68984. }
  68985. return this;
  68986. };
  68987. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  68988. var src = this.m;
  68989. var dest = other.m;
  68990. // Load the 4 rows
  68991. var src0 = SIMD.Float32x4.load(src, 0);
  68992. var src1 = SIMD.Float32x4.load(src, 4);
  68993. var src2 = SIMD.Float32x4.load(src, 8);
  68994. var src3 = SIMD.Float32x4.load(src, 12);
  68995. // Transpose the source matrix. Sort of. Not a true transpose operation
  68996. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  68997. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  68998. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  68999. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  69000. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  69001. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  69002. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  69003. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  69004. // This is a true transposition, but it will lead to an incorrect result
  69005. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  69006. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  69007. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  69008. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  69009. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  69010. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  69011. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  69012. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  69013. // ----
  69014. tmp1 = SIMD.Float32x4.mul(row2, row3);
  69015. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69016. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  69017. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  69018. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69019. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  69020. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  69021. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  69022. // ----
  69023. tmp1 = SIMD.Float32x4.mul(row1, row2);
  69024. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69025. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  69026. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  69027. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69028. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  69029. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  69030. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  69031. // ----
  69032. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  69033. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69034. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  69035. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  69036. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  69037. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69038. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  69039. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  69040. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  69041. // ----
  69042. tmp1 = SIMD.Float32x4.mul(row0, row1);
  69043. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69044. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  69045. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  69046. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69047. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  69048. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  69049. // ----
  69050. tmp1 = SIMD.Float32x4.mul(row0, row3);
  69051. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69052. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  69053. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  69054. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69055. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  69056. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  69057. // ----
  69058. tmp1 = SIMD.Float32x4.mul(row0, row2);
  69059. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69060. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  69061. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  69062. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69063. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  69064. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  69065. // Compute determinant
  69066. var det = SIMD.Float32x4.mul(row0, minor0);
  69067. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  69068. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  69069. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  69070. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  69071. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  69072. // These shuffles aren't necessary if the faulty transposition is done
  69073. // up at the top of this function.
  69074. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  69075. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  69076. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  69077. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  69078. // Compute final values by multiplying with 1/det
  69079. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  69080. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  69081. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  69082. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  69083. return this;
  69084. };
  69085. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  69086. var out = result.m;
  69087. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  69088. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  69089. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  69090. // cc.kmVec3Subtract(f, pCenter, pEye);
  69091. var f = SIMD.Float32x4.sub(center, eye);
  69092. // cc.kmVec3Normalize(f, f);
  69093. var tmp = SIMD.Float32x4.mul(f, f);
  69094. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69095. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69096. // cc.kmVec3Assign(up, pUp);
  69097. // cc.kmVec3Normalize(up, up);
  69098. tmp = SIMD.Float32x4.mul(up, up);
  69099. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69100. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69101. // cc.kmVec3Cross(s, f, up);
  69102. 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)));
  69103. // cc.kmVec3Normalize(s, s);
  69104. tmp = SIMD.Float32x4.mul(s, s);
  69105. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69106. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69107. // cc.kmVec3Cross(u, s, f);
  69108. 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)));
  69109. // cc.kmVec3Normalize(s, s);
  69110. tmp = SIMD.Float32x4.mul(s, s);
  69111. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69112. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69113. var zero = SIMD.Float32x4.splat(0.0);
  69114. s = SIMD.Float32x4.neg(s);
  69115. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  69116. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  69117. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  69118. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  69119. 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);
  69120. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  69121. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  69122. 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)))));
  69123. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  69124. 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)))));
  69125. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  69126. 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)))));
  69127. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  69128. 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)))));
  69129. };
  69130. return SIMDMatrix;
  69131. }());
  69132. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  69133. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  69134. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  69135. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  69136. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  69137. var SIMDHelper = /** @class */ (function () {
  69138. function SIMDHelper() {
  69139. }
  69140. Object.defineProperty(SIMDHelper, "IsEnabled", {
  69141. get: function () {
  69142. return SIMDHelper._isEnabled;
  69143. },
  69144. enumerable: true,
  69145. configurable: true
  69146. });
  69147. SIMDHelper.DisableSIMD = function () {
  69148. // Replace functions
  69149. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  69150. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  69151. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  69152. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  69153. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  69154. SIMDHelper._isEnabled = false;
  69155. };
  69156. SIMDHelper.EnableSIMD = function () {
  69157. if (self.SIMD === undefined) {
  69158. return;
  69159. }
  69160. // check if polyfills needed
  69161. if (!self.Math.fround) {
  69162. self.Math.fround = (function (array) { return function (x) {
  69163. return array[0] = x, array[0];
  69164. }; })(new Float32Array(1));
  69165. }
  69166. if (!self.Math.imul) {
  69167. self.Math.imul = function (a, b) {
  69168. var ah = (a >>> 16) & 0xffff;
  69169. var al = a & 0xffff;
  69170. var bh = (b >>> 16) & 0xffff;
  69171. var bl = b & 0xffff;
  69172. // the shift by 0 fixes the sign on the high part
  69173. // the final |0 converts the unsigned value into a signed value
  69174. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  69175. };
  69176. }
  69177. // Replace functions
  69178. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  69179. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  69180. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  69181. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  69182. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  69183. SIMDHelper._isEnabled = true;
  69184. };
  69185. SIMDHelper._isEnabled = false;
  69186. return SIMDHelper;
  69187. }());
  69188. BABYLON.SIMDHelper = SIMDHelper;
  69189. })(BABYLON || (BABYLON = {}));
  69190. //# sourceMappingURL=babylon.math.SIMD.js.map
  69191. var BABYLON;
  69192. (function (BABYLON) {
  69193. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  69194. __extends(VRDistortionCorrectionPostProcess, _super);
  69195. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  69196. var _this = _super.call(this, name, "vrDistortionCorrection", [
  69197. 'LensCenter',
  69198. 'Scale',
  69199. 'ScaleIn',
  69200. 'HmdWarpParam'
  69201. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  69202. _this._isRightEye = isRightEye;
  69203. _this._distortionFactors = vrMetrics.distortionK;
  69204. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  69205. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  69206. _this.adaptScaleToCurrentViewport = true;
  69207. _this.onSizeChangedObservable.add(function () {
  69208. _this.aspectRatio = _this.width * .5 / _this.height;
  69209. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  69210. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  69211. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  69212. });
  69213. _this.onApplyObservable.add(function (effect) {
  69214. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  69215. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  69216. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  69217. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  69218. });
  69219. return _this;
  69220. }
  69221. return VRDistortionCorrectionPostProcess;
  69222. }(BABYLON.PostProcess));
  69223. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  69224. })(BABYLON || (BABYLON = {}));
  69225. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  69226. var BABYLON;
  69227. (function (BABYLON) {
  69228. var AnaglyphPostProcess = /** @class */ (function (_super) {
  69229. __extends(AnaglyphPostProcess, _super);
  69230. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  69231. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  69232. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69233. _this.onApplyObservable.add(function (effect) {
  69234. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  69235. });
  69236. return _this;
  69237. }
  69238. return AnaglyphPostProcess;
  69239. }(BABYLON.PostProcess));
  69240. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  69241. })(BABYLON || (BABYLON = {}));
  69242. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  69243. var BABYLON;
  69244. (function (BABYLON) {
  69245. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  69246. __extends(StereoscopicInterlacePostProcess, _super);
  69247. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  69248. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  69249. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69250. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69251. _this.onSizeChangedObservable.add(function () {
  69252. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69253. });
  69254. _this.onApplyObservable.add(function (effect) {
  69255. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  69256. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  69257. });
  69258. return _this;
  69259. }
  69260. return StereoscopicInterlacePostProcess;
  69261. }(BABYLON.PostProcess));
  69262. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  69263. })(BABYLON || (BABYLON = {}));
  69264. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  69265. var BABYLON;
  69266. (function (BABYLON) {
  69267. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  69268. function FreeCameraDeviceOrientationInput() {
  69269. var _this = this;
  69270. this._screenOrientationAngle = 0;
  69271. this._screenQuaternion = new BABYLON.Quaternion();
  69272. this._alpha = 0;
  69273. this._beta = 0;
  69274. this._gamma = 0;
  69275. this._orientationChanged = function () {
  69276. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  69277. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  69278. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  69279. };
  69280. this._deviceOrientation = function (evt) {
  69281. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  69282. _this._beta = evt.beta !== null ? evt.beta : 0;
  69283. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  69284. };
  69285. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  69286. this._orientationChanged();
  69287. }
  69288. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  69289. get: function () {
  69290. return this._camera;
  69291. },
  69292. set: function (camera) {
  69293. this._camera = camera;
  69294. if (this._camera != null && !this._camera.rotationQuaternion) {
  69295. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  69296. }
  69297. },
  69298. enumerable: true,
  69299. configurable: true
  69300. });
  69301. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69302. window.addEventListener("orientationchange", this._orientationChanged);
  69303. window.addEventListener("deviceorientation", this._deviceOrientation);
  69304. //In certain cases, the attach control is called AFTER orientation was changed,
  69305. //So this is needed.
  69306. this._orientationChanged();
  69307. };
  69308. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  69309. window.removeEventListener("orientationchange", this._orientationChanged);
  69310. window.removeEventListener("deviceorientation", this._deviceOrientation);
  69311. };
  69312. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  69313. //if no device orientation provided, don't update the rotation.
  69314. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  69315. if (!this._alpha)
  69316. return;
  69317. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  69318. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  69319. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  69320. //Mirror on XY Plane
  69321. this._camera.rotationQuaternion.z *= -1;
  69322. this._camera.rotationQuaternion.w *= -1;
  69323. };
  69324. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  69325. return "FreeCameraDeviceOrientationInput";
  69326. };
  69327. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  69328. return "deviceOrientation";
  69329. };
  69330. return FreeCameraDeviceOrientationInput;
  69331. }());
  69332. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  69333. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  69334. })(BABYLON || (BABYLON = {}));
  69335. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  69336. var BABYLON;
  69337. (function (BABYLON) {
  69338. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  69339. function ArcRotateCameraVRDeviceOrientationInput() {
  69340. this.alphaCorrection = 1;
  69341. this.betaCorrection = 1;
  69342. this.gammaCorrection = 1;
  69343. this._alpha = 0;
  69344. this._beta = 0;
  69345. this._gamma = 0;
  69346. this._dirty = false;
  69347. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  69348. }
  69349. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69350. this.camera.attachControl(element, noPreventDefault);
  69351. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  69352. };
  69353. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  69354. if (evt.alpha !== null) {
  69355. this._alpha = +evt.alpha | 0;
  69356. }
  69357. if (evt.beta !== null) {
  69358. this._beta = +evt.beta | 0;
  69359. }
  69360. if (evt.gamma !== null) {
  69361. this._gamma = +evt.gamma | 0;
  69362. }
  69363. this._dirty = true;
  69364. };
  69365. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  69366. if (this._dirty) {
  69367. this._dirty = false;
  69368. if (this._gamma < 0) {
  69369. this._gamma = 180 + this._gamma;
  69370. }
  69371. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  69372. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  69373. }
  69374. };
  69375. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  69376. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  69377. };
  69378. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  69379. return "ArcRotateCameraVRDeviceOrientationInput";
  69380. };
  69381. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  69382. return "VRDeviceOrientation";
  69383. };
  69384. return ArcRotateCameraVRDeviceOrientationInput;
  69385. }());
  69386. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  69387. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  69388. })(BABYLON || (BABYLON = {}));
  69389. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  69390. var BABYLON;
  69391. (function (BABYLON) {
  69392. var VRCameraMetrics = /** @class */ (function () {
  69393. function VRCameraMetrics() {
  69394. this.compensateDistortion = true;
  69395. }
  69396. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  69397. get: function () {
  69398. return this.hResolution / (2 * this.vResolution);
  69399. },
  69400. enumerable: true,
  69401. configurable: true
  69402. });
  69403. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  69404. get: function () {
  69405. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  69406. },
  69407. enumerable: true,
  69408. configurable: true
  69409. });
  69410. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  69411. get: function () {
  69412. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69413. var h = (4 * meters) / this.hScreenSize;
  69414. return BABYLON.Matrix.Translation(h, 0, 0);
  69415. },
  69416. enumerable: true,
  69417. configurable: true
  69418. });
  69419. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  69420. get: function () {
  69421. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69422. var h = (4 * meters) / this.hScreenSize;
  69423. return BABYLON.Matrix.Translation(-h, 0, 0);
  69424. },
  69425. enumerable: true,
  69426. configurable: true
  69427. });
  69428. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  69429. get: function () {
  69430. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  69431. },
  69432. enumerable: true,
  69433. configurable: true
  69434. });
  69435. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  69436. get: function () {
  69437. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  69438. },
  69439. enumerable: true,
  69440. configurable: true
  69441. });
  69442. VRCameraMetrics.GetDefault = function () {
  69443. var result = new VRCameraMetrics();
  69444. result.hResolution = 1280;
  69445. result.vResolution = 800;
  69446. result.hScreenSize = 0.149759993;
  69447. result.vScreenSize = 0.0935999975;
  69448. result.vScreenCenter = 0.0467999987;
  69449. result.eyeToScreenDistance = 0.0410000011;
  69450. result.lensSeparationDistance = 0.0635000020;
  69451. result.interpupillaryDistance = 0.0640000030;
  69452. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  69453. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  69454. result.postProcessScaleFactor = 1.714605507808412;
  69455. result.lensCenterOffset = 0.151976421;
  69456. return result;
  69457. };
  69458. return VRCameraMetrics;
  69459. }());
  69460. BABYLON.VRCameraMetrics = VRCameraMetrics;
  69461. })(BABYLON || (BABYLON = {}));
  69462. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  69463. var BABYLON;
  69464. (function (BABYLON) {
  69465. var WebVRFreeCamera = /** @class */ (function (_super) {
  69466. __extends(WebVRFreeCamera, _super);
  69467. function WebVRFreeCamera(name, position, scene, webVROptions) {
  69468. if (webVROptions === void 0) { webVROptions = {}; }
  69469. var _this = _super.call(this, name, position, scene) || this;
  69470. _this.webVROptions = webVROptions;
  69471. _this._vrDevice = null;
  69472. _this.rawPose = null;
  69473. _this._specsVersion = "1.1";
  69474. _this._attached = false;
  69475. _this._descendants = [];
  69476. _this.devicePosition = BABYLON.Vector3.Zero();
  69477. _this.deviceScaleFactor = 1;
  69478. _this.controllers = [];
  69479. _this.onControllersAttachedObservable = new BABYLON.Observable();
  69480. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  69481. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  69482. _this.minZ = 0.1;
  69483. //legacy support - the compensation boolean was removed.
  69484. if (arguments.length === 5) {
  69485. _this.webVROptions = arguments[4];
  69486. }
  69487. // default webVR options
  69488. if (_this.webVROptions.trackPosition == undefined) {
  69489. _this.webVROptions.trackPosition = true;
  69490. }
  69491. if (_this.webVROptions.controllerMeshes == undefined) {
  69492. _this.webVROptions.controllerMeshes = true;
  69493. }
  69494. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  69495. _this.webVROptions.defaultLightingOnControllers = true;
  69496. }
  69497. _this.rotationQuaternion = new BABYLON.Quaternion();
  69498. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69499. if (_this.webVROptions && _this.webVROptions.positionScale) {
  69500. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  69501. }
  69502. //enable VR
  69503. var engine = _this.getEngine();
  69504. _this._onVREnabled = function (success) { if (success) {
  69505. _this.initControllers();
  69506. } };
  69507. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  69508. engine.initWebVR().add(function (event) {
  69509. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  69510. return;
  69511. }
  69512. _this._vrDevice = event.vrDisplay;
  69513. //reset the rig parameters.
  69514. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  69515. if (_this._attached) {
  69516. _this.getEngine().enableVR();
  69517. }
  69518. });
  69519. if (typeof (VRFrameData) !== "undefined")
  69520. _this._frameData = new VRFrameData();
  69521. /**
  69522. * The idea behind the following lines:
  69523. * objects that have the camera as parent should actually have the rig cameras as a parent.
  69524. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  69525. * the second will not show it correctly.
  69526. *
  69527. * To solve this - each object that has the camera as parent will be added to a protected array.
  69528. * When the rig camera renders, it will take this array and set all of those to be its children.
  69529. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  69530. * Amazing!
  69531. */
  69532. scene.onBeforeCameraRenderObservable.add(function (camera) {
  69533. if (camera.parent === _this && _this.rigParenting) {
  69534. _this._descendants = _this.getDescendants(true, function (n) {
  69535. // don't take the cameras or the controllers!
  69536. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  69537. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  69538. return !isController && !isRigCamera;
  69539. });
  69540. _this._descendants.forEach(function (node) {
  69541. node.parent = camera;
  69542. });
  69543. }
  69544. });
  69545. scene.onAfterCameraRenderObservable.add(function (camera) {
  69546. if (camera.parent === _this && _this.rigParenting) {
  69547. _this._descendants.forEach(function (node) {
  69548. node.parent = _this;
  69549. });
  69550. }
  69551. });
  69552. return _this;
  69553. }
  69554. WebVRFreeCamera.prototype.dispose = function () {
  69555. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  69556. _super.prototype.dispose.call(this);
  69557. };
  69558. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  69559. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  69560. var gp = _a[_i];
  69561. if (gp.hand === name) {
  69562. return gp;
  69563. }
  69564. }
  69565. return null;
  69566. };
  69567. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  69568. get: function () {
  69569. if (!this._leftController) {
  69570. this._leftController = this.getControllerByName("left");
  69571. }
  69572. return this._leftController;
  69573. },
  69574. enumerable: true,
  69575. configurable: true
  69576. });
  69577. ;
  69578. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  69579. get: function () {
  69580. if (!this._rightController) {
  69581. this._rightController = this.getControllerByName("right");
  69582. }
  69583. return this._rightController;
  69584. },
  69585. enumerable: true,
  69586. configurable: true
  69587. });
  69588. ;
  69589. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  69590. if (length === void 0) { length = 100; }
  69591. if (this.leftCamera) {
  69592. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  69593. }
  69594. else {
  69595. return _super.prototype.getForwardRay.call(this, length);
  69596. }
  69597. };
  69598. WebVRFreeCamera.prototype._checkInputs = function () {
  69599. if (this._vrDevice && this._vrDevice.isPresenting) {
  69600. this._vrDevice.getFrameData(this._frameData);
  69601. this.updateFromDevice(this._frameData.pose);
  69602. }
  69603. _super.prototype._checkInputs.call(this);
  69604. };
  69605. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  69606. if (poseData && poseData.orientation) {
  69607. this.rawPose = poseData;
  69608. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  69609. if (this.getScene().useRightHandedSystem) {
  69610. this.deviceRotationQuaternion.z *= -1;
  69611. this.deviceRotationQuaternion.w *= -1;
  69612. }
  69613. if (this.webVROptions.trackPosition && this.rawPose.position) {
  69614. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  69615. if (this.getScene().useRightHandedSystem) {
  69616. this.devicePosition.z *= -1;
  69617. }
  69618. }
  69619. }
  69620. };
  69621. /**
  69622. * WebVR's attach control will start broadcasting frames to the device.
  69623. * Note that in certain browsers (chrome for example) this function must be called
  69624. * within a user-interaction callback. Example:
  69625. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  69626. *
  69627. * @param {HTMLElement} element
  69628. * @param {boolean} [noPreventDefault]
  69629. *
  69630. * @memberOf WebVRFreeCamera
  69631. */
  69632. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  69633. _super.prototype.attachControl.call(this, element, noPreventDefault);
  69634. this._attached = true;
  69635. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  69636. if (this._vrDevice) {
  69637. this.getEngine().enableVR();
  69638. }
  69639. };
  69640. WebVRFreeCamera.prototype.detachControl = function (element) {
  69641. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69642. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69643. _super.prototype.detachControl.call(this, element);
  69644. this._attached = false;
  69645. this.getEngine().disableVR();
  69646. };
  69647. WebVRFreeCamera.prototype.getClassName = function () {
  69648. return "WebVRFreeCamera";
  69649. };
  69650. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  69651. //uses the vrDisplay's "resetPose()".
  69652. //pitch and roll won't be affected.
  69653. this._vrDevice.resetPose();
  69654. };
  69655. WebVRFreeCamera.prototype._updateRigCameras = function () {
  69656. var camLeft = this._rigCameras[0];
  69657. var camRight = this._rigCameras[1];
  69658. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69659. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69660. camLeft.position.copyFrom(this.devicePosition);
  69661. camRight.position.copyFrom(this.devicePosition);
  69662. };
  69663. /**
  69664. * This function is called by the two RIG cameras.
  69665. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  69666. */
  69667. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  69668. var _this = this;
  69669. //WebVR 1.1
  69670. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  69671. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  69672. if (!this.getScene().useRightHandedSystem) {
  69673. [2, 6, 8, 9, 14].forEach(function (num) {
  69674. _this._webvrViewMatrix.m[num] *= -1;
  69675. });
  69676. }
  69677. // update the camera rotation matrix
  69678. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  69679. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  69680. // Computing target and final matrix
  69681. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  69682. var parentCamera = this._cameraRigParams["parentCamera"];
  69683. // should the view matrix be updated with scale and position offset?
  69684. if (parentCamera.deviceScaleFactor !== 1) {
  69685. this._webvrViewMatrix.invert();
  69686. // scale the position, if set
  69687. if (parentCamera.deviceScaleFactor) {
  69688. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  69689. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  69690. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  69691. }
  69692. this._webvrViewMatrix.invert();
  69693. }
  69694. return this._webvrViewMatrix;
  69695. };
  69696. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  69697. var _this = this;
  69698. var parentCamera = this.parent;
  69699. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  69700. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  69701. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  69702. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  69703. //babylon compatible matrix
  69704. if (!this.getScene().useRightHandedSystem) {
  69705. [8, 9, 10, 11].forEach(function (num) {
  69706. _this._projectionMatrix.m[num] *= -1;
  69707. });
  69708. }
  69709. return this._projectionMatrix;
  69710. };
  69711. WebVRFreeCamera.prototype.initControllers = function () {
  69712. var _this = this;
  69713. this.controllers = [];
  69714. var manager = this.getScene().gamepadManager;
  69715. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69716. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69717. var webVrController = gamepad;
  69718. if (webVrController.defaultModel) {
  69719. webVrController.defaultModel.setEnabled(false);
  69720. }
  69721. }
  69722. });
  69723. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69724. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69725. var webVrController_1 = gamepad;
  69726. if (_this.webVROptions.controllerMeshes) {
  69727. if (webVrController_1.defaultModel) {
  69728. webVrController_1.defaultModel.setEnabled(true);
  69729. }
  69730. else {
  69731. // Load the meshes
  69732. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  69733. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  69734. if (_this.webVROptions.defaultLightingOnControllers) {
  69735. if (!_this._lightOnControllers) {
  69736. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  69737. }
  69738. var activateLightOnSubMeshes_1 = function (mesh, light) {
  69739. var children = mesh.getChildren();
  69740. if (children.length !== 0) {
  69741. children.forEach(function (mesh) {
  69742. light.includedOnlyMeshes.push(mesh);
  69743. activateLightOnSubMeshes_1(mesh, light);
  69744. });
  69745. }
  69746. };
  69747. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  69748. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  69749. }
  69750. });
  69751. }
  69752. }
  69753. webVrController_1.attachToPoseControlledCamera(_this);
  69754. // since this is async - sanity check. Is the controller already stored?
  69755. if (_this.controllers.indexOf(webVrController_1) === -1) {
  69756. //add to the controllers array
  69757. _this.controllers.push(webVrController_1);
  69758. //did we find enough controllers? Great! let the developer know.
  69759. if (_this.controllers.length >= 2) {
  69760. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  69761. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  69762. // So we're overriding setting left & right manually to be sure
  69763. var firstViveWandDetected = false;
  69764. for (var i = 0; i < _this.controllers.length; i++) {
  69765. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  69766. if (!firstViveWandDetected) {
  69767. firstViveWandDetected = true;
  69768. _this.controllers[i].hand = "left";
  69769. }
  69770. else {
  69771. _this.controllers[i].hand = "right";
  69772. }
  69773. }
  69774. }
  69775. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  69776. }
  69777. }
  69778. }
  69779. });
  69780. };
  69781. return WebVRFreeCamera;
  69782. }(BABYLON.FreeCamera));
  69783. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  69784. })(BABYLON || (BABYLON = {}));
  69785. //# sourceMappingURL=babylon.webVRCamera.js.map
  69786. var BABYLON;
  69787. (function (BABYLON) {
  69788. // We're mainly based on the logic defined into the FreeCamera code
  69789. var DeviceOrientationCamera = /** @class */ (function (_super) {
  69790. __extends(DeviceOrientationCamera, _super);
  69791. function DeviceOrientationCamera(name, position, scene) {
  69792. var _this = _super.call(this, name, position, scene) || this;
  69793. _this._quaternionCache = new BABYLON.Quaternion();
  69794. _this.inputs.addDeviceOrientation();
  69795. return _this;
  69796. }
  69797. DeviceOrientationCamera.prototype.getClassName = function () {
  69798. return "DeviceOrientationCamera";
  69799. };
  69800. DeviceOrientationCamera.prototype._checkInputs = function () {
  69801. _super.prototype._checkInputs.call(this);
  69802. this._quaternionCache.copyFrom(this.rotationQuaternion);
  69803. if (this._initialQuaternion) {
  69804. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69805. }
  69806. };
  69807. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  69808. var _this = this;
  69809. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  69810. //can only work if this camera has a rotation quaternion already.
  69811. if (!this.rotationQuaternion)
  69812. return;
  69813. if (!this._initialQuaternion) {
  69814. this._initialQuaternion = new BABYLON.Quaternion();
  69815. }
  69816. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  69817. ['x', 'y', 'z'].forEach(function (axisName) {
  69818. if (!axis[axisName]) {
  69819. _this._initialQuaternion[axisName] = 0;
  69820. }
  69821. else {
  69822. _this._initialQuaternion[axisName] *= -1;
  69823. }
  69824. });
  69825. this._initialQuaternion.normalize();
  69826. //force rotation update
  69827. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69828. };
  69829. return DeviceOrientationCamera;
  69830. }(BABYLON.FreeCamera));
  69831. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  69832. })(BABYLON || (BABYLON = {}));
  69833. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  69834. var BABYLON;
  69835. (function (BABYLON) {
  69836. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  69837. __extends(VRDeviceOrientationFreeCamera, _super);
  69838. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69839. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69840. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69841. var _this = _super.call(this, name, position, scene) || this;
  69842. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69843. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69844. return _this;
  69845. }
  69846. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  69847. return "VRDeviceOrientationFreeCamera";
  69848. };
  69849. return VRDeviceOrientationFreeCamera;
  69850. }(BABYLON.DeviceOrientationCamera));
  69851. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  69852. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  69853. __extends(VRDeviceOrientationGamepadCamera, _super);
  69854. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69855. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69856. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69857. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  69858. _this.inputs.addGamepad();
  69859. return _this;
  69860. }
  69861. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  69862. return "VRDeviceOrientationGamepadCamera";
  69863. };
  69864. return VRDeviceOrientationGamepadCamera;
  69865. }(VRDeviceOrientationFreeCamera));
  69866. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  69867. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  69868. __extends(VRDeviceOrientationArcRotateCamera, _super);
  69869. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  69870. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69871. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69872. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69873. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69874. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69875. _this.inputs.addVRDeviceOrientation();
  69876. return _this;
  69877. }
  69878. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  69879. return "VRDeviceOrientationArcRotateCamera";
  69880. };
  69881. return VRDeviceOrientationArcRotateCamera;
  69882. }(BABYLON.ArcRotateCamera));
  69883. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  69884. })(BABYLON || (BABYLON = {}));
  69885. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  69886. var BABYLON;
  69887. (function (BABYLON) {
  69888. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  69889. __extends(AnaglyphFreeCamera, _super);
  69890. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  69891. var _this = _super.call(this, name, position, scene) || this;
  69892. _this.interaxialDistance = interaxialDistance;
  69893. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69894. return _this;
  69895. }
  69896. AnaglyphFreeCamera.prototype.getClassName = function () {
  69897. return "AnaglyphFreeCamera";
  69898. };
  69899. return AnaglyphFreeCamera;
  69900. }(BABYLON.FreeCamera));
  69901. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  69902. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  69903. __extends(AnaglyphArcRotateCamera, _super);
  69904. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  69905. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69906. _this.interaxialDistance = interaxialDistance;
  69907. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69908. return _this;
  69909. }
  69910. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  69911. return "AnaglyphArcRotateCamera";
  69912. };
  69913. return AnaglyphArcRotateCamera;
  69914. }(BABYLON.ArcRotateCamera));
  69915. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  69916. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  69917. __extends(AnaglyphGamepadCamera, _super);
  69918. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  69919. var _this = _super.call(this, name, position, scene) || this;
  69920. _this.interaxialDistance = interaxialDistance;
  69921. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69922. return _this;
  69923. }
  69924. AnaglyphGamepadCamera.prototype.getClassName = function () {
  69925. return "AnaglyphGamepadCamera";
  69926. };
  69927. return AnaglyphGamepadCamera;
  69928. }(BABYLON.GamepadCamera));
  69929. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  69930. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  69931. __extends(AnaglyphUniversalCamera, _super);
  69932. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  69933. var _this = _super.call(this, name, position, scene) || this;
  69934. _this.interaxialDistance = interaxialDistance;
  69935. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69936. return _this;
  69937. }
  69938. AnaglyphUniversalCamera.prototype.getClassName = function () {
  69939. return "AnaglyphUniversalCamera";
  69940. };
  69941. return AnaglyphUniversalCamera;
  69942. }(BABYLON.UniversalCamera));
  69943. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  69944. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  69945. __extends(StereoscopicFreeCamera, _super);
  69946. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69947. var _this = _super.call(this, name, position, scene) || this;
  69948. _this.interaxialDistance = interaxialDistance;
  69949. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69950. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69951. return _this;
  69952. }
  69953. StereoscopicFreeCamera.prototype.getClassName = function () {
  69954. return "StereoscopicFreeCamera";
  69955. };
  69956. return StereoscopicFreeCamera;
  69957. }(BABYLON.FreeCamera));
  69958. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  69959. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  69960. __extends(StereoscopicArcRotateCamera, _super);
  69961. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  69962. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69963. _this.interaxialDistance = interaxialDistance;
  69964. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69965. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69966. return _this;
  69967. }
  69968. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  69969. return "StereoscopicArcRotateCamera";
  69970. };
  69971. return StereoscopicArcRotateCamera;
  69972. }(BABYLON.ArcRotateCamera));
  69973. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  69974. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  69975. __extends(StereoscopicGamepadCamera, _super);
  69976. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69977. var _this = _super.call(this, name, position, scene) || this;
  69978. _this.interaxialDistance = interaxialDistance;
  69979. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69980. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69981. return _this;
  69982. }
  69983. StereoscopicGamepadCamera.prototype.getClassName = function () {
  69984. return "StereoscopicGamepadCamera";
  69985. };
  69986. return StereoscopicGamepadCamera;
  69987. }(BABYLON.GamepadCamera));
  69988. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  69989. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  69990. __extends(StereoscopicUniversalCamera, _super);
  69991. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69992. var _this = _super.call(this, name, position, scene) || this;
  69993. _this.interaxialDistance = interaxialDistance;
  69994. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69995. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69996. return _this;
  69997. }
  69998. StereoscopicUniversalCamera.prototype.getClassName = function () {
  69999. return "StereoscopicUniversalCamera";
  70000. };
  70001. return StereoscopicUniversalCamera;
  70002. }(BABYLON.UniversalCamera));
  70003. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  70004. })(BABYLON || (BABYLON = {}));
  70005. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  70006. var BABYLON;
  70007. (function (BABYLON) {
  70008. var VRExperienceHelper = /** @class */ (function () {
  70009. function VRExperienceHelper(scene, webVROptions) {
  70010. if (webVROptions === void 0) { webVROptions = {}; }
  70011. var _this = this;
  70012. this.webVROptions = webVROptions;
  70013. // Can the system support WebVR, even if a headset isn't plugged in?
  70014. this._webVRsupported = false;
  70015. // If WebVR is supported, is a headset plugged in and are we ready to present?
  70016. this._webVRready = false;
  70017. // Are we waiting for the requestPresent callback to complete?
  70018. this._webVRrequesting = false;
  70019. // Are we presenting to the headset right now?
  70020. this._webVRpresenting = false;
  70021. // Are we presenting in the fullscreen fallback?
  70022. this._fullscreenVRpresenting = false;
  70023. this._scene = scene;
  70024. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  70025. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  70026. }
  70027. else {
  70028. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  70029. if (scene.activeCamera.rotation) {
  70030. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  70031. }
  70032. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  70033. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  70034. }
  70035. this._scene.activeCamera = this._deviceOrientationCamera;
  70036. this._position = this._scene.activeCamera.position;
  70037. this._canvas = scene.getEngine().getRenderingCanvas();
  70038. if (this._canvas) {
  70039. this._scene.activeCamera.attachControl(this._canvas);
  70040. }
  70041. this._btnVR = document.createElement("BUTTON");
  70042. this._btnVR.className = "babylonVRicon";
  70043. this._btnVR.id = "babylonVRiconbtn";
  70044. this._btnVR.title = "Click to switch to VR";
  70045. 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) }";
  70046. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  70047. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  70048. // css += ".babylonVRicon.vrdisplaysupported { }";
  70049. // css += ".babylonVRicon.vrdisplayready { }";
  70050. // css += ".babylonVRicon.vrdisplayrequesting { }";
  70051. var style = document.createElement('style');
  70052. style.appendChild(document.createTextNode(css));
  70053. document.getElementsByTagName('head')[0].appendChild(style);
  70054. if (this._canvas) {
  70055. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70056. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70057. this._btnVR.addEventListener("click", function () {
  70058. _this.enterVR();
  70059. });
  70060. window.addEventListener("resize", function () {
  70061. if (_this._canvas) {
  70062. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  70063. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  70064. }
  70065. if (_this._fullscreenVRpresenting && _this._webVRready) {
  70066. _this.exitVR();
  70067. }
  70068. });
  70069. }
  70070. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70071. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70072. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70073. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70074. document.body.appendChild(this._btnVR);
  70075. // Exiting VR mode using 'ESC' key on desktop
  70076. this._onKeyDown = function (event) {
  70077. if (event.keyCode === 27 && _this.isInVRMode()) {
  70078. _this.exitVR();
  70079. }
  70080. };
  70081. document.addEventListener("keydown", this._onKeyDown);
  70082. // Exiting VR mode double tapping the touch screen
  70083. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  70084. if (_this.isInVRMode()) {
  70085. _this.exitVR();
  70086. if (_this._fullscreenVRpresenting) {
  70087. _this._scene.getEngine().switchFullscreen(true);
  70088. }
  70089. }
  70090. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  70091. // Listen for WebVR display changes
  70092. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  70093. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  70094. this._onVRRequestPresentStart = function () {
  70095. _this._webVRrequesting = true;
  70096. _this.updateButtonVisibility();
  70097. };
  70098. this._onVRRequestPresentComplete = function (success) {
  70099. _this._webVRrequesting = false;
  70100. _this.updateButtonVisibility();
  70101. };
  70102. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  70103. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  70104. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  70105. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70106. // Create the cameras
  70107. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  70108. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  70109. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  70110. this.updateButtonVisibility();
  70111. }
  70112. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  70113. if (this.onControllerMeshLoaded) {
  70114. this.onControllerMeshLoaded(webVRController);
  70115. }
  70116. };
  70117. VRExperienceHelper.prototype._onFullscreenChange = function () {
  70118. if (document.fullscreen !== undefined) {
  70119. this._fullscreenVRpresenting = document.fullscreen;
  70120. }
  70121. else if (document.mozFullScreen !== undefined) {
  70122. this._fullscreenVRpresenting = document.mozFullScreen;
  70123. }
  70124. else if (document.webkitIsFullScreen !== undefined) {
  70125. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  70126. }
  70127. else if (document.msIsFullScreen !== undefined) {
  70128. this._fullscreenVRpresenting = document.msIsFullScreen;
  70129. }
  70130. if (!this._fullscreenVRpresenting && this._canvas) {
  70131. this.exitVR();
  70132. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70133. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70134. }
  70135. };
  70136. VRExperienceHelper.prototype.isInVRMode = function () {
  70137. return this._webVRpresenting || this._fullscreenVRpresenting;
  70138. };
  70139. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  70140. var vrDisplay = this._scene.getEngine().getVRDevice();
  70141. if (vrDisplay) {
  70142. var wasPresenting = this._webVRpresenting;
  70143. // A VR display is connected
  70144. this._webVRpresenting = vrDisplay.isPresenting;
  70145. if (wasPresenting && !this._webVRpresenting)
  70146. this.exitVR();
  70147. }
  70148. else {
  70149. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  70150. }
  70151. this.updateButtonVisibility();
  70152. };
  70153. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  70154. this._webVRsupported = eventArgs.vrSupported;
  70155. this._webVRready = !!eventArgs.vrDisplay;
  70156. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  70157. this.updateButtonVisibility();
  70158. };
  70159. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  70160. if (!this._btnVR) {
  70161. return;
  70162. }
  70163. this._btnVR.className = "babylonVRicon";
  70164. if (this.isInVRMode()) {
  70165. this._btnVR.className += " vrdisplaypresenting";
  70166. }
  70167. else {
  70168. if (this._webVRready)
  70169. this._btnVR.className += " vrdisplayready";
  70170. if (this._webVRsupported)
  70171. this._btnVR.className += " vrdisplaysupported";
  70172. if (this._webVRrequesting)
  70173. this._btnVR.className += " vrdisplayrequesting";
  70174. }
  70175. };
  70176. /**
  70177. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  70178. * Otherwise, will use the fullscreen API.
  70179. */
  70180. VRExperienceHelper.prototype.enterVR = function () {
  70181. if (this.onEnteringVR) {
  70182. this.onEnteringVR();
  70183. }
  70184. if (this._webVRrequesting)
  70185. return;
  70186. // If WebVR is supported and a headset is connected
  70187. if (this._webVRready) {
  70188. if (!this._webVRpresenting) {
  70189. this._webVRCamera.position = this._position;
  70190. this._scene.activeCamera = this._webVRCamera;
  70191. }
  70192. }
  70193. else {
  70194. this._vrDeviceOrientationCamera.position = this._position;
  70195. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  70196. this._scene.getEngine().switchFullscreen(true);
  70197. this.updateButtonVisibility();
  70198. }
  70199. if (this._scene.activeCamera && this._canvas) {
  70200. this._scene.activeCamera.attachControl(this._canvas);
  70201. }
  70202. };
  70203. /**
  70204. * Attempt to exit VR, or fullscreen.
  70205. */
  70206. VRExperienceHelper.prototype.exitVR = function () {
  70207. if (this.onExitingVR) {
  70208. this.onExitingVR();
  70209. }
  70210. if (this._webVRpresenting) {
  70211. this._scene.getEngine().disableVR();
  70212. }
  70213. if (this._scene.activeCamera) {
  70214. this._position = this._scene.activeCamera.position;
  70215. }
  70216. this._deviceOrientationCamera.position = this._position;
  70217. this._scene.activeCamera = this._deviceOrientationCamera;
  70218. if (this._canvas) {
  70219. this._scene.activeCamera.attachControl(this._canvas);
  70220. }
  70221. this.updateButtonVisibility();
  70222. };
  70223. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  70224. get: function () {
  70225. return this._position;
  70226. },
  70227. set: function (value) {
  70228. this._position = value;
  70229. if (this._scene.activeCamera) {
  70230. this._scene.activeCamera.position = value;
  70231. }
  70232. },
  70233. enumerable: true,
  70234. configurable: true
  70235. });
  70236. VRExperienceHelper.prototype.dispose = function () {
  70237. if (this.isInVRMode()) {
  70238. this.exitVR();
  70239. }
  70240. this._deviceOrientationCamera.dispose();
  70241. if (this._webVRCamera) {
  70242. this._webVRCamera.dispose();
  70243. }
  70244. if (this._vrDeviceOrientationCamera) {
  70245. this._vrDeviceOrientationCamera.dispose();
  70246. }
  70247. document.body.removeChild(this._btnVR);
  70248. document.removeEventListener("keydown", this._onKeyDown);
  70249. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70250. };
  70251. VRExperienceHelper.prototype.getClassName = function () {
  70252. return "VRExperienceHelper";
  70253. };
  70254. return VRExperienceHelper;
  70255. }());
  70256. BABYLON.VRExperienceHelper = VRExperienceHelper;
  70257. })(BABYLON || (BABYLON = {}));
  70258. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  70259. // Mainly based on these 2 articles :
  70260. // 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
  70261. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  70262. var BABYLON;
  70263. (function (BABYLON) {
  70264. var JoystickAxis;
  70265. (function (JoystickAxis) {
  70266. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  70267. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  70268. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  70269. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  70270. var VirtualJoystick = /** @class */ (function () {
  70271. function VirtualJoystick(leftJoystick) {
  70272. var _this = this;
  70273. if (leftJoystick) {
  70274. this._leftJoystick = true;
  70275. }
  70276. else {
  70277. this._leftJoystick = false;
  70278. }
  70279. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  70280. VirtualJoystick._globalJoystickIndex++;
  70281. // By default left & right arrow keys are moving the X
  70282. // and up & down keys are moving the Y
  70283. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70284. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70285. this.reverseLeftRight = false;
  70286. this.reverseUpDown = false;
  70287. // collections of pointers
  70288. this._touches = new BABYLON.StringDictionary();
  70289. this.deltaPosition = BABYLON.Vector3.Zero();
  70290. this._joystickSensibility = 25;
  70291. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70292. this._rotationSpeed = 25;
  70293. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  70294. this._rotateOnAxisRelativeToMesh = false;
  70295. this._onResize = function (evt) {
  70296. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70297. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70298. if (VirtualJoystick.vjCanvas) {
  70299. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  70300. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  70301. }
  70302. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  70303. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  70304. };
  70305. // injecting a canvas element on top of the canvas 3D game
  70306. if (!VirtualJoystick.vjCanvas) {
  70307. window.addEventListener("resize", this._onResize, false);
  70308. VirtualJoystick.vjCanvas = document.createElement("canvas");
  70309. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70310. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70311. VirtualJoystick.vjCanvas.width = window.innerWidth;
  70312. VirtualJoystick.vjCanvas.height = window.innerHeight;
  70313. VirtualJoystick.vjCanvas.style.width = "100%";
  70314. VirtualJoystick.vjCanvas.style.height = "100%";
  70315. VirtualJoystick.vjCanvas.style.position = "absolute";
  70316. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  70317. VirtualJoystick.vjCanvas.style.top = "0px";
  70318. VirtualJoystick.vjCanvas.style.left = "0px";
  70319. VirtualJoystick.vjCanvas.style.zIndex = "5";
  70320. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  70321. // Support for jQuery PEP polyfill
  70322. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  70323. var context = VirtualJoystick.vjCanvas.getContext('2d');
  70324. if (!context) {
  70325. throw new Error("Unable to create canvas for virtual joystick");
  70326. }
  70327. VirtualJoystick.vjCanvasContext = context;
  70328. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  70329. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70330. document.body.appendChild(VirtualJoystick.vjCanvas);
  70331. }
  70332. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  70333. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  70334. this.pressed = false;
  70335. // default joystick color
  70336. this._joystickColor = "cyan";
  70337. this._joystickPointerID = -1;
  70338. // current joystick position
  70339. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  70340. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  70341. // origin joystick position
  70342. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  70343. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  70344. this._onPointerDownHandlerRef = function (evt) {
  70345. _this._onPointerDown(evt);
  70346. };
  70347. this._onPointerMoveHandlerRef = function (evt) {
  70348. _this._onPointerMove(evt);
  70349. };
  70350. this._onPointerOutHandlerRef = function (evt) {
  70351. _this._onPointerUp(evt);
  70352. };
  70353. this._onPointerUpHandlerRef = function (evt) {
  70354. _this._onPointerUp(evt);
  70355. };
  70356. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  70357. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  70358. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  70359. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  70360. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  70361. evt.preventDefault(); // Disables system menu
  70362. }, false);
  70363. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70364. }
  70365. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  70366. this._joystickSensibility = newJoystickSensibility;
  70367. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70368. };
  70369. VirtualJoystick.prototype._onPointerDown = function (e) {
  70370. var positionOnScreenCondition;
  70371. e.preventDefault();
  70372. if (this._leftJoystick === true) {
  70373. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  70374. }
  70375. else {
  70376. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  70377. }
  70378. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  70379. // First contact will be dedicated to the virtual joystick
  70380. this._joystickPointerID = e.pointerId;
  70381. this._joystickPointerStartPos.x = e.clientX;
  70382. this._joystickPointerStartPos.y = e.clientY;
  70383. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  70384. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  70385. this._deltaJoystickVector.x = 0;
  70386. this._deltaJoystickVector.y = 0;
  70387. this.pressed = true;
  70388. this._touches.add(e.pointerId.toString(), e);
  70389. }
  70390. else {
  70391. // You can only trigger the action buttons with a joystick declared
  70392. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  70393. this._action();
  70394. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  70395. }
  70396. }
  70397. };
  70398. VirtualJoystick.prototype._onPointerMove = function (e) {
  70399. // If the current pointer is the one associated to the joystick (first touch contact)
  70400. if (this._joystickPointerID == e.pointerId) {
  70401. this._joystickPointerPos.x = e.clientX;
  70402. this._joystickPointerPos.y = e.clientY;
  70403. this._deltaJoystickVector = this._joystickPointerPos.clone();
  70404. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  70405. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  70406. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  70407. switch (this._axisTargetedByLeftAndRight) {
  70408. case JoystickAxis.X:
  70409. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  70410. break;
  70411. case JoystickAxis.Y:
  70412. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  70413. break;
  70414. case JoystickAxis.Z:
  70415. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  70416. break;
  70417. }
  70418. var directionUpDown = this.reverseUpDown ? 1 : -1;
  70419. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  70420. switch (this._axisTargetedByUpAndDown) {
  70421. case JoystickAxis.X:
  70422. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  70423. break;
  70424. case JoystickAxis.Y:
  70425. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  70426. break;
  70427. case JoystickAxis.Z:
  70428. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  70429. break;
  70430. }
  70431. }
  70432. else {
  70433. var data = this._touches.get(e.pointerId.toString());
  70434. if (data) {
  70435. data.x = e.clientX;
  70436. data.y = e.clientY;
  70437. }
  70438. }
  70439. };
  70440. VirtualJoystick.prototype._onPointerUp = function (e) {
  70441. if (this._joystickPointerID == e.pointerId) {
  70442. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  70443. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  70444. this._joystickPointerID = -1;
  70445. this.pressed = false;
  70446. }
  70447. else {
  70448. var touch = this._touches.get(e.pointerId.toString());
  70449. if (touch) {
  70450. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70451. }
  70452. }
  70453. this._deltaJoystickVector.x = 0;
  70454. this._deltaJoystickVector.y = 0;
  70455. this._touches.remove(e.pointerId.toString());
  70456. };
  70457. /**
  70458. * Change the color of the virtual joystick
  70459. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  70460. */
  70461. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  70462. this._joystickColor = newColor;
  70463. };
  70464. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  70465. this._action = action;
  70466. };
  70467. // Define which axis you'd like to control for left & right
  70468. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  70469. switch (axis) {
  70470. case JoystickAxis.X:
  70471. case JoystickAxis.Y:
  70472. case JoystickAxis.Z:
  70473. this._axisTargetedByLeftAndRight = axis;
  70474. break;
  70475. default:
  70476. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70477. break;
  70478. }
  70479. };
  70480. // Define which axis you'd like to control for up & down
  70481. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  70482. switch (axis) {
  70483. case JoystickAxis.X:
  70484. case JoystickAxis.Y:
  70485. case JoystickAxis.Z:
  70486. this._axisTargetedByUpAndDown = axis;
  70487. break;
  70488. default:
  70489. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70490. break;
  70491. }
  70492. };
  70493. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  70494. var _this = this;
  70495. if (this.pressed) {
  70496. this._touches.forEach(function (key, touch) {
  70497. if (touch.pointerId === _this._joystickPointerID) {
  70498. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  70499. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  70500. VirtualJoystick.vjCanvasContext.beginPath();
  70501. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70502. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70503. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  70504. VirtualJoystick.vjCanvasContext.stroke();
  70505. VirtualJoystick.vjCanvasContext.closePath();
  70506. VirtualJoystick.vjCanvasContext.beginPath();
  70507. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70508. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70509. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  70510. VirtualJoystick.vjCanvasContext.stroke();
  70511. VirtualJoystick.vjCanvasContext.closePath();
  70512. VirtualJoystick.vjCanvasContext.beginPath();
  70513. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70514. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  70515. VirtualJoystick.vjCanvasContext.stroke();
  70516. VirtualJoystick.vjCanvasContext.closePath();
  70517. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  70518. }
  70519. else {
  70520. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70521. VirtualJoystick.vjCanvasContext.beginPath();
  70522. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  70523. VirtualJoystick.vjCanvasContext.beginPath();
  70524. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  70525. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70526. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  70527. VirtualJoystick.vjCanvasContext.stroke();
  70528. VirtualJoystick.vjCanvasContext.closePath();
  70529. touch.prevX = touch.x;
  70530. touch.prevY = touch.y;
  70531. }
  70532. ;
  70533. });
  70534. }
  70535. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70536. };
  70537. VirtualJoystick.prototype.releaseCanvas = function () {
  70538. if (VirtualJoystick.vjCanvas) {
  70539. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  70540. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  70541. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  70542. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  70543. window.removeEventListener("resize", this._onResize);
  70544. document.body.removeChild(VirtualJoystick.vjCanvas);
  70545. VirtualJoystick.vjCanvas = null;
  70546. }
  70547. };
  70548. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  70549. VirtualJoystick._globalJoystickIndex = 0;
  70550. return VirtualJoystick;
  70551. }());
  70552. BABYLON.VirtualJoystick = VirtualJoystick;
  70553. })(BABYLON || (BABYLON = {}));
  70554. //# sourceMappingURL=babylon.virtualJoystick.js.map
  70555. var BABYLON;
  70556. (function (BABYLON) {
  70557. // We're mainly based on the logic defined into the FreeCamera code
  70558. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  70559. __extends(VirtualJoysticksCamera, _super);
  70560. function VirtualJoysticksCamera(name, position, scene) {
  70561. var _this = _super.call(this, name, position, scene) || this;
  70562. _this.inputs.addVirtualJoystick();
  70563. return _this;
  70564. }
  70565. VirtualJoysticksCamera.prototype.getClassName = function () {
  70566. return "VirtualJoysticksCamera";
  70567. };
  70568. return VirtualJoysticksCamera;
  70569. }(BABYLON.FreeCamera));
  70570. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  70571. })(BABYLON || (BABYLON = {}));
  70572. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  70573. var BABYLON;
  70574. (function (BABYLON) {
  70575. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  70576. function FreeCameraVirtualJoystickInput() {
  70577. }
  70578. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  70579. return this._leftjoystick;
  70580. };
  70581. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  70582. return this._rightjoystick;
  70583. };
  70584. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  70585. if (this._leftjoystick) {
  70586. var camera = this.camera;
  70587. var speed = camera._computeLocalCameraSpeed() * 50;
  70588. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  70589. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  70590. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  70591. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  70592. if (!this._leftjoystick.pressed) {
  70593. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  70594. }
  70595. if (!this._rightjoystick.pressed) {
  70596. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  70597. }
  70598. }
  70599. };
  70600. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  70601. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  70602. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  70603. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  70604. this._leftjoystick.setJoystickSensibility(0.15);
  70605. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  70606. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  70607. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  70608. this._rightjoystick.reverseUpDown = true;
  70609. this._rightjoystick.setJoystickSensibility(0.05);
  70610. this._rightjoystick.setJoystickColor("yellow");
  70611. };
  70612. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  70613. this._leftjoystick.releaseCanvas();
  70614. this._rightjoystick.releaseCanvas();
  70615. };
  70616. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  70617. return "FreeCameraVirtualJoystickInput";
  70618. };
  70619. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  70620. return "virtualJoystick";
  70621. };
  70622. return FreeCameraVirtualJoystickInput;
  70623. }());
  70624. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  70625. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  70626. })(BABYLON || (BABYLON = {}));
  70627. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  70628. var BABYLON;
  70629. (function (BABYLON) {
  70630. var SimplificationSettings = /** @class */ (function () {
  70631. function SimplificationSettings(quality, distance, optimizeMesh) {
  70632. this.quality = quality;
  70633. this.distance = distance;
  70634. this.optimizeMesh = optimizeMesh;
  70635. }
  70636. return SimplificationSettings;
  70637. }());
  70638. BABYLON.SimplificationSettings = SimplificationSettings;
  70639. var SimplificationQueue = /** @class */ (function () {
  70640. function SimplificationQueue() {
  70641. this.running = false;
  70642. this._simplificationArray = [];
  70643. }
  70644. SimplificationQueue.prototype.addTask = function (task) {
  70645. this._simplificationArray.push(task);
  70646. };
  70647. SimplificationQueue.prototype.executeNext = function () {
  70648. var task = this._simplificationArray.pop();
  70649. if (task) {
  70650. this.running = true;
  70651. this.runSimplification(task);
  70652. }
  70653. else {
  70654. this.running = false;
  70655. }
  70656. };
  70657. SimplificationQueue.prototype.runSimplification = function (task) {
  70658. var _this = this;
  70659. if (task.parallelProcessing) {
  70660. //parallel simplifier
  70661. task.settings.forEach(function (setting) {
  70662. var simplifier = _this.getSimplifier(task);
  70663. simplifier.simplify(setting, function (newMesh) {
  70664. task.mesh.addLODLevel(setting.distance, newMesh);
  70665. newMesh.isVisible = true;
  70666. //check if it is the last
  70667. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  70668. //all done, run the success callback.
  70669. task.successCallback();
  70670. }
  70671. _this.executeNext();
  70672. });
  70673. });
  70674. }
  70675. else {
  70676. //single simplifier.
  70677. var simplifier = this.getSimplifier(task);
  70678. var runDecimation = function (setting, callback) {
  70679. simplifier.simplify(setting, function (newMesh) {
  70680. task.mesh.addLODLevel(setting.distance, newMesh);
  70681. newMesh.isVisible = true;
  70682. //run the next quality level
  70683. callback();
  70684. });
  70685. };
  70686. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  70687. runDecimation(task.settings[loop.index], function () {
  70688. loop.executeNext();
  70689. });
  70690. }, function () {
  70691. //execution ended, run the success callback.
  70692. if (task.successCallback) {
  70693. task.successCallback();
  70694. }
  70695. _this.executeNext();
  70696. });
  70697. }
  70698. };
  70699. SimplificationQueue.prototype.getSimplifier = function (task) {
  70700. switch (task.simplificationType) {
  70701. case SimplificationType.QUADRATIC:
  70702. default:
  70703. return new QuadraticErrorSimplification(task.mesh);
  70704. }
  70705. };
  70706. return SimplificationQueue;
  70707. }());
  70708. BABYLON.SimplificationQueue = SimplificationQueue;
  70709. /**
  70710. * The implemented types of simplification.
  70711. * At the moment only Quadratic Error Decimation is implemented.
  70712. */
  70713. var SimplificationType;
  70714. (function (SimplificationType) {
  70715. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  70716. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  70717. var DecimationTriangle = /** @class */ (function () {
  70718. function DecimationTriangle(vertices) {
  70719. this.vertices = vertices;
  70720. this.error = new Array(4);
  70721. this.deleted = false;
  70722. this.isDirty = false;
  70723. this.deletePending = false;
  70724. this.borderFactor = 0;
  70725. }
  70726. return DecimationTriangle;
  70727. }());
  70728. BABYLON.DecimationTriangle = DecimationTriangle;
  70729. var DecimationVertex = /** @class */ (function () {
  70730. function DecimationVertex(position, id) {
  70731. this.position = position;
  70732. this.id = id;
  70733. this.isBorder = true;
  70734. this.q = new QuadraticMatrix();
  70735. this.triangleCount = 0;
  70736. this.triangleStart = 0;
  70737. this.originalOffsets = [];
  70738. }
  70739. DecimationVertex.prototype.updatePosition = function (newPosition) {
  70740. this.position.copyFrom(newPosition);
  70741. };
  70742. return DecimationVertex;
  70743. }());
  70744. BABYLON.DecimationVertex = DecimationVertex;
  70745. var QuadraticMatrix = /** @class */ (function () {
  70746. function QuadraticMatrix(data) {
  70747. this.data = new Array(10);
  70748. for (var i = 0; i < 10; ++i) {
  70749. if (data && data[i]) {
  70750. this.data[i] = data[i];
  70751. }
  70752. else {
  70753. this.data[i] = 0;
  70754. }
  70755. }
  70756. }
  70757. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  70758. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  70759. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  70760. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  70761. return det;
  70762. };
  70763. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  70764. for (var i = 0; i < 10; ++i) {
  70765. this.data[i] += matrix.data[i];
  70766. }
  70767. };
  70768. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  70769. for (var i = 0; i < 10; ++i) {
  70770. this.data[i] += data[i];
  70771. }
  70772. };
  70773. QuadraticMatrix.prototype.add = function (matrix) {
  70774. var m = new QuadraticMatrix();
  70775. for (var i = 0; i < 10; ++i) {
  70776. m.data[i] = this.data[i] + matrix.data[i];
  70777. }
  70778. return m;
  70779. };
  70780. QuadraticMatrix.FromData = function (a, b, c, d) {
  70781. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  70782. };
  70783. //returning an array to avoid garbage collection
  70784. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  70785. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  70786. };
  70787. return QuadraticMatrix;
  70788. }());
  70789. BABYLON.QuadraticMatrix = QuadraticMatrix;
  70790. var Reference = /** @class */ (function () {
  70791. function Reference(vertexId, triangleId) {
  70792. this.vertexId = vertexId;
  70793. this.triangleId = triangleId;
  70794. }
  70795. return Reference;
  70796. }());
  70797. BABYLON.Reference = Reference;
  70798. /**
  70799. * An implementation of the Quadratic Error simplification algorithm.
  70800. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  70801. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  70802. * @author RaananW
  70803. */
  70804. var QuadraticErrorSimplification = /** @class */ (function () {
  70805. function QuadraticErrorSimplification(_mesh) {
  70806. this._mesh = _mesh;
  70807. this.initialized = false;
  70808. this.syncIterations = 5000;
  70809. this.aggressiveness = 7;
  70810. this.decimationIterations = 100;
  70811. this.boundingBoxEpsilon = BABYLON.Epsilon;
  70812. }
  70813. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  70814. var _this = this;
  70815. this.initDecimatedMesh();
  70816. //iterating through the submeshes array, one after the other.
  70817. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  70818. _this.initWithMesh(loop.index, function () {
  70819. _this.runDecimation(settings, loop.index, function () {
  70820. loop.executeNext();
  70821. });
  70822. }, settings.optimizeMesh);
  70823. }, function () {
  70824. setTimeout(function () {
  70825. successCallback(_this._reconstructedMesh);
  70826. }, 0);
  70827. });
  70828. };
  70829. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  70830. var _this = this;
  70831. var targetCount = ~~(this.triangles.length * settings.quality);
  70832. var deletedTriangles = 0;
  70833. var triangleCount = this.triangles.length;
  70834. var iterationFunction = function (iteration, callback) {
  70835. setTimeout(function () {
  70836. if (iteration % 5 === 0) {
  70837. _this.updateMesh(iteration === 0);
  70838. }
  70839. for (var i = 0; i < _this.triangles.length; ++i) {
  70840. _this.triangles[i].isDirty = false;
  70841. }
  70842. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  70843. var trianglesIterator = function (i) {
  70844. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  70845. var t = _this.triangles[tIdx];
  70846. if (!t)
  70847. return;
  70848. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  70849. return;
  70850. }
  70851. for (var j = 0; j < 3; ++j) {
  70852. if (t.error[j] < threshold) {
  70853. var deleted0 = [];
  70854. var deleted1 = [];
  70855. var v0 = t.vertices[j];
  70856. var v1 = t.vertices[(j + 1) % 3];
  70857. if (v0.isBorder || v1.isBorder)
  70858. continue;
  70859. var p = BABYLON.Vector3.Zero();
  70860. var n = BABYLON.Vector3.Zero();
  70861. var uv = BABYLON.Vector2.Zero();
  70862. var color = new BABYLON.Color4(0, 0, 0, 1);
  70863. _this.calculateError(v0, v1, p, n, uv, color);
  70864. var delTr = new Array();
  70865. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  70866. continue;
  70867. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  70868. continue;
  70869. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  70870. continue;
  70871. var uniqueArray = new Array();
  70872. delTr.forEach(function (deletedT) {
  70873. if (uniqueArray.indexOf(deletedT) === -1) {
  70874. deletedT.deletePending = true;
  70875. uniqueArray.push(deletedT);
  70876. }
  70877. });
  70878. if (uniqueArray.length % 2 !== 0) {
  70879. continue;
  70880. }
  70881. v0.q = v1.q.add(v0.q);
  70882. v0.updatePosition(p);
  70883. var tStart = _this.references.length;
  70884. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  70885. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  70886. var tCount = _this.references.length - tStart;
  70887. if (tCount <= v0.triangleCount) {
  70888. if (tCount) {
  70889. for (var c = 0; c < tCount; c++) {
  70890. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  70891. }
  70892. }
  70893. }
  70894. else {
  70895. v0.triangleStart = tStart;
  70896. }
  70897. v0.triangleCount = tCount;
  70898. break;
  70899. }
  70900. }
  70901. };
  70902. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  70903. }, 0);
  70904. };
  70905. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  70906. if (triangleCount - deletedTriangles <= targetCount)
  70907. loop.breakLoop();
  70908. else {
  70909. iterationFunction(loop.index, function () {
  70910. loop.executeNext();
  70911. });
  70912. }
  70913. }, function () {
  70914. setTimeout(function () {
  70915. //reconstruct this part of the mesh
  70916. _this.reconstructMesh(submeshIndex);
  70917. successCallback();
  70918. }, 0);
  70919. });
  70920. };
  70921. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  70922. var _this = this;
  70923. this.vertices = [];
  70924. this.triangles = [];
  70925. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70926. var indices = this._mesh.getIndices();
  70927. var submesh = this._mesh.subMeshes[submeshIndex];
  70928. var findInVertices = function (positionToSearch) {
  70929. if (optimizeMesh) {
  70930. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  70931. if (_this.vertices[ii].position.equals(positionToSearch)) {
  70932. return _this.vertices[ii];
  70933. }
  70934. }
  70935. }
  70936. return null;
  70937. };
  70938. var vertexReferences = [];
  70939. var vertexInit = function (i) {
  70940. if (!positionData) {
  70941. return;
  70942. }
  70943. var offset = i + submesh.verticesStart;
  70944. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  70945. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  70946. vertex.originalOffsets.push(offset);
  70947. if (vertex.id === _this.vertices.length) {
  70948. _this.vertices.push(vertex);
  70949. }
  70950. vertexReferences.push(vertex.id);
  70951. };
  70952. //var totalVertices = mesh.getTotalVertices();
  70953. var totalVertices = submesh.verticesCount;
  70954. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  70955. var indicesInit = function (i) {
  70956. if (!indices) {
  70957. return;
  70958. }
  70959. var offset = (submesh.indexStart / 3) + i;
  70960. var pos = (offset * 3);
  70961. var i0 = indices[pos + 0];
  70962. var i1 = indices[pos + 1];
  70963. var i2 = indices[pos + 2];
  70964. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  70965. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  70966. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  70967. var triangle = new DecimationTriangle([v0, v1, v2]);
  70968. triangle.originalOffset = pos;
  70969. _this.triangles.push(triangle);
  70970. };
  70971. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  70972. _this.init(callback);
  70973. });
  70974. });
  70975. };
  70976. QuadraticErrorSimplification.prototype.init = function (callback) {
  70977. var _this = this;
  70978. var triangleInit1 = function (i) {
  70979. var t = _this.triangles[i];
  70980. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  70981. for (var j = 0; j < 3; j++) {
  70982. 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))));
  70983. }
  70984. };
  70985. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  70986. var triangleInit2 = function (i) {
  70987. var t = _this.triangles[i];
  70988. for (var j = 0; j < 3; ++j) {
  70989. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  70990. }
  70991. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70992. };
  70993. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  70994. _this.initialized = true;
  70995. callback();
  70996. });
  70997. });
  70998. };
  70999. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  71000. var newTriangles = [];
  71001. var i;
  71002. for (i = 0; i < this.vertices.length; ++i) {
  71003. this.vertices[i].triangleCount = 0;
  71004. }
  71005. var t;
  71006. var j;
  71007. for (i = 0; i < this.triangles.length; ++i) {
  71008. if (!this.triangles[i].deleted) {
  71009. t = this.triangles[i];
  71010. for (j = 0; j < 3; ++j) {
  71011. t.vertices[j].triangleCount = 1;
  71012. }
  71013. newTriangles.push(t);
  71014. }
  71015. }
  71016. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  71017. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  71018. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  71019. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  71020. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  71021. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  71022. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  71023. var vertexCount = 0;
  71024. for (i = 0; i < this.vertices.length; ++i) {
  71025. var vertex = this.vertices[i];
  71026. vertex.id = vertexCount;
  71027. if (vertex.triangleCount) {
  71028. vertex.originalOffsets.forEach(function (originalOffset) {
  71029. if (!normalData) {
  71030. return;
  71031. }
  71032. newPositionData.push(vertex.position.x);
  71033. newPositionData.push(vertex.position.y);
  71034. newPositionData.push(vertex.position.z);
  71035. newNormalData.push(normalData[originalOffset * 3]);
  71036. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  71037. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  71038. if (uvs && uvs.length) {
  71039. newUVsData.push(uvs[(originalOffset * 2)]);
  71040. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  71041. }
  71042. else if (colorsData && colorsData.length) {
  71043. newColorsData.push(colorsData[(originalOffset * 4)]);
  71044. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  71045. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  71046. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  71047. }
  71048. ++vertexCount;
  71049. });
  71050. }
  71051. }
  71052. var startingIndex = this._reconstructedMesh.getTotalIndices();
  71053. var startingVertex = this._reconstructedMesh.getTotalVertices();
  71054. var submeshesArray = this._reconstructedMesh.subMeshes;
  71055. this._reconstructedMesh.subMeshes = [];
  71056. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  71057. var originalIndices = this._mesh.getIndices();
  71058. for (i = 0; i < newTriangles.length; ++i) {
  71059. t = newTriangles[i]; //now get the new referencing point for each vertex
  71060. [0, 1, 2].forEach(function (idx) {
  71061. var id = originalIndices[t.originalOffset + idx];
  71062. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  71063. if (offset < 0)
  71064. offset = 0;
  71065. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  71066. });
  71067. }
  71068. //overwriting the old vertex buffers and indices.
  71069. this._reconstructedMesh.setIndices(newIndicesArray);
  71070. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  71071. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  71072. if (newUVsData.length > 0)
  71073. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  71074. if (newColorsData.length > 0)
  71075. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  71076. //create submesh
  71077. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  71078. if (submeshIndex > 0) {
  71079. this._reconstructedMesh.subMeshes = [];
  71080. submeshesArray.forEach(function (submesh) {
  71081. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  71082. });
  71083. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  71084. }
  71085. };
  71086. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  71087. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  71088. this._reconstructedMesh.material = this._mesh.material;
  71089. this._reconstructedMesh.parent = this._mesh.parent;
  71090. this._reconstructedMesh.isVisible = false;
  71091. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  71092. };
  71093. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  71094. for (var i = 0; i < vertex1.triangleCount; ++i) {
  71095. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  71096. if (t.deleted)
  71097. continue;
  71098. var s = this.references[vertex1.triangleStart + i].vertexId;
  71099. var v1 = t.vertices[(s + 1) % 3];
  71100. var v2 = t.vertices[(s + 2) % 3];
  71101. if ((v1 === vertex2 || v2 === vertex2)) {
  71102. deletedArray[i] = true;
  71103. delTr.push(t);
  71104. continue;
  71105. }
  71106. var d1 = v1.position.subtract(point);
  71107. d1 = d1.normalize();
  71108. var d2 = v2.position.subtract(point);
  71109. d2 = d2.normalize();
  71110. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  71111. return true;
  71112. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  71113. deletedArray[i] = false;
  71114. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  71115. return true;
  71116. }
  71117. return false;
  71118. };
  71119. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  71120. var newDeleted = deletedTriangles;
  71121. for (var i = 0; i < vertex.triangleCount; ++i) {
  71122. var ref = this.references[vertex.triangleStart + i];
  71123. var t = this.triangles[ref.triangleId];
  71124. if (t.deleted)
  71125. continue;
  71126. if (deletedArray[i] && t.deletePending) {
  71127. t.deleted = true;
  71128. newDeleted++;
  71129. continue;
  71130. }
  71131. t.vertices[ref.vertexId] = origVertex;
  71132. t.isDirty = true;
  71133. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  71134. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  71135. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  71136. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  71137. this.references.push(ref);
  71138. }
  71139. return newDeleted;
  71140. };
  71141. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  71142. for (var i = 0; i < this.vertices.length; ++i) {
  71143. var vCount = [];
  71144. var vId = [];
  71145. var v = this.vertices[i];
  71146. var j;
  71147. for (j = 0; j < v.triangleCount; ++j) {
  71148. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  71149. for (var ii = 0; ii < 3; ii++) {
  71150. var ofs = 0;
  71151. var vv = triangle.vertices[ii];
  71152. while (ofs < vCount.length) {
  71153. if (vId[ofs] === vv.id)
  71154. break;
  71155. ++ofs;
  71156. }
  71157. if (ofs === vCount.length) {
  71158. vCount.push(1);
  71159. vId.push(vv.id);
  71160. }
  71161. else {
  71162. vCount[ofs]++;
  71163. }
  71164. }
  71165. }
  71166. for (j = 0; j < vCount.length; ++j) {
  71167. if (vCount[j] === 1) {
  71168. this.vertices[vId[j]].isBorder = true;
  71169. }
  71170. else {
  71171. this.vertices[vId[j]].isBorder = false;
  71172. }
  71173. }
  71174. }
  71175. };
  71176. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  71177. if (identifyBorders === void 0) { identifyBorders = false; }
  71178. var i;
  71179. if (!identifyBorders) {
  71180. var newTrianglesVector = [];
  71181. for (i = 0; i < this.triangles.length; ++i) {
  71182. if (!this.triangles[i].deleted) {
  71183. newTrianglesVector.push(this.triangles[i]);
  71184. }
  71185. }
  71186. this.triangles = newTrianglesVector;
  71187. }
  71188. for (i = 0; i < this.vertices.length; ++i) {
  71189. this.vertices[i].triangleCount = 0;
  71190. this.vertices[i].triangleStart = 0;
  71191. }
  71192. var t;
  71193. var j;
  71194. var v;
  71195. for (i = 0; i < this.triangles.length; ++i) {
  71196. t = this.triangles[i];
  71197. for (j = 0; j < 3; ++j) {
  71198. v = t.vertices[j];
  71199. v.triangleCount++;
  71200. }
  71201. }
  71202. var tStart = 0;
  71203. for (i = 0; i < this.vertices.length; ++i) {
  71204. this.vertices[i].triangleStart = tStart;
  71205. tStart += this.vertices[i].triangleCount;
  71206. this.vertices[i].triangleCount = 0;
  71207. }
  71208. var newReferences = new Array(this.triangles.length * 3);
  71209. for (i = 0; i < this.triangles.length; ++i) {
  71210. t = this.triangles[i];
  71211. for (j = 0; j < 3; ++j) {
  71212. v = t.vertices[j];
  71213. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  71214. v.triangleCount++;
  71215. }
  71216. }
  71217. this.references = newReferences;
  71218. if (identifyBorders) {
  71219. this.identifyBorder();
  71220. }
  71221. };
  71222. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  71223. var x = point.x;
  71224. var y = point.y;
  71225. var z = point.z;
  71226. 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
  71227. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  71228. };
  71229. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  71230. var q = vertex1.q.add(vertex2.q);
  71231. var border = vertex1.isBorder && vertex2.isBorder;
  71232. var error = 0;
  71233. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  71234. if (qDet !== 0 && !border) {
  71235. if (!pointResult) {
  71236. pointResult = BABYLON.Vector3.Zero();
  71237. }
  71238. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  71239. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  71240. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  71241. error = this.vertexError(q, pointResult);
  71242. }
  71243. else {
  71244. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  71245. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  71246. var error1 = this.vertexError(q, vertex1.position);
  71247. var error2 = this.vertexError(q, vertex2.position);
  71248. var error3 = this.vertexError(q, p3);
  71249. error = Math.min(error1, error2, error3);
  71250. if (error === error1) {
  71251. if (pointResult) {
  71252. pointResult.copyFrom(vertex1.position);
  71253. }
  71254. }
  71255. else if (error === error2) {
  71256. if (pointResult) {
  71257. pointResult.copyFrom(vertex2.position);
  71258. }
  71259. }
  71260. else {
  71261. if (pointResult) {
  71262. pointResult.copyFrom(p3);
  71263. }
  71264. }
  71265. }
  71266. return error;
  71267. };
  71268. return QuadraticErrorSimplification;
  71269. }());
  71270. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  71271. })(BABYLON || (BABYLON = {}));
  71272. //# sourceMappingURL=babylon.meshSimplification.js.map
  71273. var BABYLON;
  71274. (function (BABYLON) {
  71275. var Internals;
  71276. (function (Internals) {
  71277. var MeshLODLevel = /** @class */ (function () {
  71278. function MeshLODLevel(distance, mesh) {
  71279. this.distance = distance;
  71280. this.mesh = mesh;
  71281. }
  71282. return MeshLODLevel;
  71283. }());
  71284. Internals.MeshLODLevel = MeshLODLevel;
  71285. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  71286. })(BABYLON || (BABYLON = {}));
  71287. //# sourceMappingURL=babylon.meshLODLevel.js.map
  71288. var BABYLON;
  71289. (function (BABYLON) {
  71290. // Standard optimizations
  71291. var SceneOptimization = /** @class */ (function () {
  71292. function SceneOptimization(priority) {
  71293. if (priority === void 0) { priority = 0; }
  71294. this.priority = priority;
  71295. this.apply = function (scene) {
  71296. return true; // Return true if everything that can be done was applied
  71297. };
  71298. }
  71299. return SceneOptimization;
  71300. }());
  71301. BABYLON.SceneOptimization = SceneOptimization;
  71302. var TextureOptimization = /** @class */ (function (_super) {
  71303. __extends(TextureOptimization, _super);
  71304. function TextureOptimization(priority, maximumSize) {
  71305. if (priority === void 0) { priority = 0; }
  71306. if (maximumSize === void 0) { maximumSize = 1024; }
  71307. var _this = _super.call(this, priority) || this;
  71308. _this.priority = priority;
  71309. _this.maximumSize = maximumSize;
  71310. _this.apply = function (scene) {
  71311. var allDone = true;
  71312. for (var index = 0; index < scene.textures.length; index++) {
  71313. var texture = scene.textures[index];
  71314. if (!texture.canRescale || texture.getContext) {
  71315. continue;
  71316. }
  71317. var currentSize = texture.getSize();
  71318. var maxDimension = Math.max(currentSize.width, currentSize.height);
  71319. if (maxDimension > _this.maximumSize) {
  71320. texture.scale(0.5);
  71321. allDone = false;
  71322. }
  71323. }
  71324. return allDone;
  71325. };
  71326. return _this;
  71327. }
  71328. return TextureOptimization;
  71329. }(SceneOptimization));
  71330. BABYLON.TextureOptimization = TextureOptimization;
  71331. var HardwareScalingOptimization = /** @class */ (function (_super) {
  71332. __extends(HardwareScalingOptimization, _super);
  71333. function HardwareScalingOptimization(priority, maximumScale) {
  71334. if (priority === void 0) { priority = 0; }
  71335. if (maximumScale === void 0) { maximumScale = 2; }
  71336. var _this = _super.call(this, priority) || this;
  71337. _this.priority = priority;
  71338. _this.maximumScale = maximumScale;
  71339. _this._currentScale = 1;
  71340. _this.apply = function (scene) {
  71341. _this._currentScale++;
  71342. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  71343. return _this._currentScale >= _this.maximumScale;
  71344. };
  71345. return _this;
  71346. }
  71347. return HardwareScalingOptimization;
  71348. }(SceneOptimization));
  71349. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  71350. var ShadowsOptimization = /** @class */ (function (_super) {
  71351. __extends(ShadowsOptimization, _super);
  71352. function ShadowsOptimization() {
  71353. var _this = _super !== null && _super.apply(this, arguments) || this;
  71354. _this.apply = function (scene) {
  71355. scene.shadowsEnabled = false;
  71356. return true;
  71357. };
  71358. return _this;
  71359. }
  71360. return ShadowsOptimization;
  71361. }(SceneOptimization));
  71362. BABYLON.ShadowsOptimization = ShadowsOptimization;
  71363. var PostProcessesOptimization = /** @class */ (function (_super) {
  71364. __extends(PostProcessesOptimization, _super);
  71365. function PostProcessesOptimization() {
  71366. var _this = _super !== null && _super.apply(this, arguments) || this;
  71367. _this.apply = function (scene) {
  71368. scene.postProcessesEnabled = false;
  71369. return true;
  71370. };
  71371. return _this;
  71372. }
  71373. return PostProcessesOptimization;
  71374. }(SceneOptimization));
  71375. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  71376. var LensFlaresOptimization = /** @class */ (function (_super) {
  71377. __extends(LensFlaresOptimization, _super);
  71378. function LensFlaresOptimization() {
  71379. var _this = _super !== null && _super.apply(this, arguments) || this;
  71380. _this.apply = function (scene) {
  71381. scene.lensFlaresEnabled = false;
  71382. return true;
  71383. };
  71384. return _this;
  71385. }
  71386. return LensFlaresOptimization;
  71387. }(SceneOptimization));
  71388. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  71389. var ParticlesOptimization = /** @class */ (function (_super) {
  71390. __extends(ParticlesOptimization, _super);
  71391. function ParticlesOptimization() {
  71392. var _this = _super !== null && _super.apply(this, arguments) || this;
  71393. _this.apply = function (scene) {
  71394. scene.particlesEnabled = false;
  71395. return true;
  71396. };
  71397. return _this;
  71398. }
  71399. return ParticlesOptimization;
  71400. }(SceneOptimization));
  71401. BABYLON.ParticlesOptimization = ParticlesOptimization;
  71402. var RenderTargetsOptimization = /** @class */ (function (_super) {
  71403. __extends(RenderTargetsOptimization, _super);
  71404. function RenderTargetsOptimization() {
  71405. var _this = _super !== null && _super.apply(this, arguments) || this;
  71406. _this.apply = function (scene) {
  71407. scene.renderTargetsEnabled = false;
  71408. return true;
  71409. };
  71410. return _this;
  71411. }
  71412. return RenderTargetsOptimization;
  71413. }(SceneOptimization));
  71414. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  71415. var MergeMeshesOptimization = /** @class */ (function (_super) {
  71416. __extends(MergeMeshesOptimization, _super);
  71417. function MergeMeshesOptimization() {
  71418. var _this = _super !== null && _super.apply(this, arguments) || this;
  71419. _this._canBeMerged = function (abstractMesh) {
  71420. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  71421. return false;
  71422. }
  71423. var mesh = abstractMesh;
  71424. if (!mesh.isVisible || !mesh.isEnabled()) {
  71425. return false;
  71426. }
  71427. if (mesh.instances.length > 0) {
  71428. return false;
  71429. }
  71430. if (mesh.skeleton || mesh.hasLODLevels) {
  71431. return false;
  71432. }
  71433. if (mesh.parent) {
  71434. return false;
  71435. }
  71436. return true;
  71437. };
  71438. _this.apply = function (scene, updateSelectionTree) {
  71439. var globalPool = scene.meshes.slice(0);
  71440. var globalLength = globalPool.length;
  71441. for (var index = 0; index < globalLength; index++) {
  71442. var currentPool = new Array();
  71443. var current = globalPool[index];
  71444. // Checks
  71445. if (!_this._canBeMerged(current)) {
  71446. continue;
  71447. }
  71448. currentPool.push(current);
  71449. // Find compatible meshes
  71450. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  71451. var otherMesh = globalPool[subIndex];
  71452. if (!_this._canBeMerged(otherMesh)) {
  71453. continue;
  71454. }
  71455. if (otherMesh.material !== current.material) {
  71456. continue;
  71457. }
  71458. if (otherMesh.checkCollisions !== current.checkCollisions) {
  71459. continue;
  71460. }
  71461. currentPool.push(otherMesh);
  71462. globalLength--;
  71463. globalPool.splice(subIndex, 1);
  71464. subIndex--;
  71465. }
  71466. if (currentPool.length < 2) {
  71467. continue;
  71468. }
  71469. // Merge meshes
  71470. BABYLON.Mesh.MergeMeshes(currentPool);
  71471. }
  71472. if (updateSelectionTree != undefined) {
  71473. if (updateSelectionTree) {
  71474. scene.createOrUpdateSelectionOctree();
  71475. }
  71476. }
  71477. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  71478. scene.createOrUpdateSelectionOctree();
  71479. }
  71480. return true;
  71481. };
  71482. return _this;
  71483. }
  71484. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  71485. get: function () {
  71486. return MergeMeshesOptimization._UpdateSelectionTree;
  71487. },
  71488. set: function (value) {
  71489. MergeMeshesOptimization._UpdateSelectionTree = value;
  71490. },
  71491. enumerable: true,
  71492. configurable: true
  71493. });
  71494. MergeMeshesOptimization._UpdateSelectionTree = false;
  71495. return MergeMeshesOptimization;
  71496. }(SceneOptimization));
  71497. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  71498. // Options
  71499. var SceneOptimizerOptions = /** @class */ (function () {
  71500. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  71501. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  71502. if (trackerDuration === void 0) { trackerDuration = 2000; }
  71503. this.targetFrameRate = targetFrameRate;
  71504. this.trackerDuration = trackerDuration;
  71505. this.optimizations = new Array();
  71506. }
  71507. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  71508. var result = new SceneOptimizerOptions(targetFrameRate);
  71509. var priority = 0;
  71510. result.optimizations.push(new MergeMeshesOptimization(priority));
  71511. result.optimizations.push(new ShadowsOptimization(priority));
  71512. result.optimizations.push(new LensFlaresOptimization(priority));
  71513. // Next priority
  71514. priority++;
  71515. result.optimizations.push(new PostProcessesOptimization(priority));
  71516. result.optimizations.push(new ParticlesOptimization(priority));
  71517. // Next priority
  71518. priority++;
  71519. result.optimizations.push(new TextureOptimization(priority, 1024));
  71520. return result;
  71521. };
  71522. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  71523. var result = new SceneOptimizerOptions(targetFrameRate);
  71524. var priority = 0;
  71525. result.optimizations.push(new MergeMeshesOptimization(priority));
  71526. result.optimizations.push(new ShadowsOptimization(priority));
  71527. result.optimizations.push(new LensFlaresOptimization(priority));
  71528. // Next priority
  71529. priority++;
  71530. result.optimizations.push(new PostProcessesOptimization(priority));
  71531. result.optimizations.push(new ParticlesOptimization(priority));
  71532. // Next priority
  71533. priority++;
  71534. result.optimizations.push(new TextureOptimization(priority, 512));
  71535. // Next priority
  71536. priority++;
  71537. result.optimizations.push(new RenderTargetsOptimization(priority));
  71538. // Next priority
  71539. priority++;
  71540. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  71541. return result;
  71542. };
  71543. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  71544. var result = new SceneOptimizerOptions(targetFrameRate);
  71545. var priority = 0;
  71546. result.optimizations.push(new MergeMeshesOptimization(priority));
  71547. result.optimizations.push(new ShadowsOptimization(priority));
  71548. result.optimizations.push(new LensFlaresOptimization(priority));
  71549. // Next priority
  71550. priority++;
  71551. result.optimizations.push(new PostProcessesOptimization(priority));
  71552. result.optimizations.push(new ParticlesOptimization(priority));
  71553. // Next priority
  71554. priority++;
  71555. result.optimizations.push(new TextureOptimization(priority, 256));
  71556. // Next priority
  71557. priority++;
  71558. result.optimizations.push(new RenderTargetsOptimization(priority));
  71559. // Next priority
  71560. priority++;
  71561. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  71562. return result;
  71563. };
  71564. return SceneOptimizerOptions;
  71565. }());
  71566. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  71567. // Scene optimizer tool
  71568. var SceneOptimizer = /** @class */ (function () {
  71569. function SceneOptimizer() {
  71570. }
  71571. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  71572. // TODO: add an epsilon
  71573. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  71574. if (onSuccess) {
  71575. onSuccess();
  71576. }
  71577. return;
  71578. }
  71579. // Apply current level of optimizations
  71580. var allDone = true;
  71581. var noOptimizationApplied = true;
  71582. for (var index = 0; index < options.optimizations.length; index++) {
  71583. var optimization = options.optimizations[index];
  71584. if (optimization.priority === currentPriorityLevel) {
  71585. noOptimizationApplied = false;
  71586. allDone = allDone && optimization.apply(scene);
  71587. }
  71588. }
  71589. // If no optimization was applied, this is a failure :(
  71590. if (noOptimizationApplied) {
  71591. if (onFailure) {
  71592. onFailure();
  71593. }
  71594. return;
  71595. }
  71596. // If all optimizations were done, move to next level
  71597. if (allDone) {
  71598. currentPriorityLevel++;
  71599. }
  71600. // Let's the system running for a specific amount of time before checking FPS
  71601. scene.executeWhenReady(function () {
  71602. setTimeout(function () {
  71603. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  71604. }, options.trackerDuration);
  71605. });
  71606. };
  71607. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  71608. if (!options) {
  71609. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  71610. }
  71611. // Let's the system running for a specific amount of time before checking FPS
  71612. scene.executeWhenReady(function () {
  71613. setTimeout(function () {
  71614. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  71615. }, options.trackerDuration);
  71616. });
  71617. };
  71618. return SceneOptimizer;
  71619. }());
  71620. BABYLON.SceneOptimizer = SceneOptimizer;
  71621. })(BABYLON || (BABYLON = {}));
  71622. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  71623. var BABYLON;
  71624. (function (BABYLON) {
  71625. var OutlineRenderer = /** @class */ (function () {
  71626. function OutlineRenderer(scene) {
  71627. this.zOffset = 1;
  71628. this._scene = scene;
  71629. }
  71630. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  71631. var _this = this;
  71632. if (useOverlay === void 0) { useOverlay = false; }
  71633. var scene = this._scene;
  71634. var engine = this._scene.getEngine();
  71635. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71636. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  71637. return;
  71638. }
  71639. var mesh = subMesh.getRenderingMesh();
  71640. var material = subMesh.getMaterial();
  71641. if (!material || !scene.activeCamera) {
  71642. return;
  71643. }
  71644. engine.enableEffect(this._effect);
  71645. // Logarithmic depth
  71646. if (material.useLogarithmicDepth) {
  71647. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  71648. }
  71649. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  71650. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  71651. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71652. // Bones
  71653. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71654. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71655. }
  71656. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71657. // Alpha test
  71658. if (material && material.needAlphaTesting()) {
  71659. var alphaTexture = material.getAlphaTestTexture();
  71660. if (alphaTexture) {
  71661. this._effect.setTexture("diffuseSampler", alphaTexture);
  71662. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71663. }
  71664. }
  71665. engine.setZOffset(-this.zOffset);
  71666. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  71667. engine.setZOffset(0);
  71668. };
  71669. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  71670. var defines = [];
  71671. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71672. var mesh = subMesh.getMesh();
  71673. var material = subMesh.getMaterial();
  71674. if (material) {
  71675. // Alpha test
  71676. if (material.needAlphaTesting()) {
  71677. defines.push("#define ALPHATEST");
  71678. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71679. attribs.push(BABYLON.VertexBuffer.UVKind);
  71680. defines.push("#define UV1");
  71681. }
  71682. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71683. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71684. defines.push("#define UV2");
  71685. }
  71686. }
  71687. //Logarithmic depth
  71688. if (material.useLogarithmicDepth) {
  71689. defines.push("#define LOGARITHMICDEPTH");
  71690. }
  71691. }
  71692. // Bones
  71693. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71694. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71695. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71696. if (mesh.numBoneInfluencers > 4) {
  71697. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71698. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71699. }
  71700. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71701. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71702. }
  71703. else {
  71704. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71705. }
  71706. // Instances
  71707. if (useInstances) {
  71708. defines.push("#define INSTANCES");
  71709. attribs.push("world0");
  71710. attribs.push("world1");
  71711. attribs.push("world2");
  71712. attribs.push("world3");
  71713. }
  71714. // Get correct effect
  71715. var join = defines.join("\n");
  71716. if (this._cachedDefines !== join) {
  71717. this._cachedDefines = join;
  71718. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  71719. }
  71720. return this._effect.isReady();
  71721. };
  71722. return OutlineRenderer;
  71723. }());
  71724. BABYLON.OutlineRenderer = OutlineRenderer;
  71725. })(BABYLON || (BABYLON = {}));
  71726. //# sourceMappingURL=babylon.outlineRenderer.js.map
  71727. var BABYLON;
  71728. (function (BABYLON) {
  71729. var FaceAdjacencies = /** @class */ (function () {
  71730. function FaceAdjacencies() {
  71731. this.edges = new Array();
  71732. this.edgesConnectedCount = 0;
  71733. }
  71734. return FaceAdjacencies;
  71735. }());
  71736. var EdgesRenderer = /** @class */ (function () {
  71737. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  71738. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  71739. if (epsilon === void 0) { epsilon = 0.95; }
  71740. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  71741. this.edgesWidthScalerForOrthographic = 1000.0;
  71742. this.edgesWidthScalerForPerspective = 50.0;
  71743. this._linesPositions = new Array();
  71744. this._linesNormals = new Array();
  71745. this._linesIndices = new Array();
  71746. this._buffers = {};
  71747. this._checkVerticesInsteadOfIndices = false;
  71748. this._source = source;
  71749. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  71750. this._epsilon = epsilon;
  71751. this._prepareRessources();
  71752. this._generateEdgesLines();
  71753. }
  71754. EdgesRenderer.prototype._prepareRessources = function () {
  71755. if (this._lineShader) {
  71756. return;
  71757. }
  71758. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  71759. attributes: ["position", "normal"],
  71760. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  71761. });
  71762. this._lineShader.disableDepthWrite = true;
  71763. this._lineShader.backFaceCulling = false;
  71764. };
  71765. EdgesRenderer.prototype._rebuild = function () {
  71766. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71767. if (buffer) {
  71768. buffer._rebuild();
  71769. }
  71770. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71771. if (buffer) {
  71772. buffer._rebuild();
  71773. }
  71774. var scene = this._source.getScene();
  71775. var engine = scene.getEngine();
  71776. this._ib = engine.createIndexBuffer(this._linesIndices);
  71777. };
  71778. EdgesRenderer.prototype.dispose = function () {
  71779. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71780. if (buffer) {
  71781. buffer.dispose();
  71782. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  71783. }
  71784. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71785. if (buffer) {
  71786. buffer.dispose();
  71787. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  71788. }
  71789. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  71790. this._lineShader.dispose();
  71791. };
  71792. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  71793. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  71794. return 0;
  71795. }
  71796. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  71797. return 1;
  71798. }
  71799. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  71800. return 2;
  71801. }
  71802. return -1;
  71803. };
  71804. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  71805. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  71806. return 0;
  71807. }
  71808. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  71809. return 1;
  71810. }
  71811. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  71812. return 2;
  71813. }
  71814. return -1;
  71815. };
  71816. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  71817. var needToCreateLine;
  71818. if (edge === undefined) {
  71819. needToCreateLine = true;
  71820. }
  71821. else {
  71822. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  71823. needToCreateLine = dotProduct < this._epsilon;
  71824. }
  71825. if (needToCreateLine) {
  71826. var offset = this._linesPositions.length / 3;
  71827. var normal = p0.subtract(p1);
  71828. normal.normalize();
  71829. // Positions
  71830. this._linesPositions.push(p0.x);
  71831. this._linesPositions.push(p0.y);
  71832. this._linesPositions.push(p0.z);
  71833. this._linesPositions.push(p0.x);
  71834. this._linesPositions.push(p0.y);
  71835. this._linesPositions.push(p0.z);
  71836. this._linesPositions.push(p1.x);
  71837. this._linesPositions.push(p1.y);
  71838. this._linesPositions.push(p1.z);
  71839. this._linesPositions.push(p1.x);
  71840. this._linesPositions.push(p1.y);
  71841. this._linesPositions.push(p1.z);
  71842. // Normals
  71843. this._linesNormals.push(p1.x);
  71844. this._linesNormals.push(p1.y);
  71845. this._linesNormals.push(p1.z);
  71846. this._linesNormals.push(-1);
  71847. this._linesNormals.push(p1.x);
  71848. this._linesNormals.push(p1.y);
  71849. this._linesNormals.push(p1.z);
  71850. this._linesNormals.push(1);
  71851. this._linesNormals.push(p0.x);
  71852. this._linesNormals.push(p0.y);
  71853. this._linesNormals.push(p0.z);
  71854. this._linesNormals.push(-1);
  71855. this._linesNormals.push(p0.x);
  71856. this._linesNormals.push(p0.y);
  71857. this._linesNormals.push(p0.z);
  71858. this._linesNormals.push(1);
  71859. // Indices
  71860. this._linesIndices.push(offset);
  71861. this._linesIndices.push(offset + 1);
  71862. this._linesIndices.push(offset + 2);
  71863. this._linesIndices.push(offset);
  71864. this._linesIndices.push(offset + 2);
  71865. this._linesIndices.push(offset + 3);
  71866. }
  71867. };
  71868. EdgesRenderer.prototype._generateEdgesLines = function () {
  71869. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71870. var indices = this._source.getIndices();
  71871. if (!indices || !positions) {
  71872. return;
  71873. }
  71874. // First let's find adjacencies
  71875. var adjacencies = new Array();
  71876. var faceNormals = new Array();
  71877. var index;
  71878. var faceAdjacencies;
  71879. // Prepare faces
  71880. for (index = 0; index < indices.length; index += 3) {
  71881. faceAdjacencies = new FaceAdjacencies();
  71882. var p0Index = indices[index];
  71883. var p1Index = indices[index + 1];
  71884. var p2Index = indices[index + 2];
  71885. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  71886. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  71887. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  71888. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  71889. faceNormal.normalize();
  71890. faceNormals.push(faceNormal);
  71891. adjacencies.push(faceAdjacencies);
  71892. }
  71893. // Scan
  71894. for (index = 0; index < adjacencies.length; index++) {
  71895. faceAdjacencies = adjacencies[index];
  71896. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  71897. var otherFaceAdjacencies = adjacencies[otherIndex];
  71898. if (faceAdjacencies.edgesConnectedCount === 3) {
  71899. break;
  71900. }
  71901. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  71902. continue;
  71903. }
  71904. var otherP0 = indices[otherIndex * 3];
  71905. var otherP1 = indices[otherIndex * 3 + 1];
  71906. var otherP2 = indices[otherIndex * 3 + 2];
  71907. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  71908. var otherEdgeIndex = 0;
  71909. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  71910. continue;
  71911. }
  71912. switch (edgeIndex) {
  71913. case 0:
  71914. if (this._checkVerticesInsteadOfIndices) {
  71915. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71916. }
  71917. else {
  71918. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  71919. }
  71920. break;
  71921. case 1:
  71922. if (this._checkVerticesInsteadOfIndices) {
  71923. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71924. }
  71925. else {
  71926. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  71927. }
  71928. break;
  71929. case 2:
  71930. if (this._checkVerticesInsteadOfIndices) {
  71931. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71932. }
  71933. else {
  71934. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  71935. }
  71936. break;
  71937. }
  71938. if (otherEdgeIndex === -1) {
  71939. continue;
  71940. }
  71941. faceAdjacencies.edges[edgeIndex] = otherIndex;
  71942. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  71943. faceAdjacencies.edgesConnectedCount++;
  71944. otherFaceAdjacencies.edgesConnectedCount++;
  71945. if (faceAdjacencies.edgesConnectedCount === 3) {
  71946. break;
  71947. }
  71948. }
  71949. }
  71950. }
  71951. // Create lines
  71952. for (index = 0; index < adjacencies.length; index++) {
  71953. // 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
  71954. var current = adjacencies[index];
  71955. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  71956. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  71957. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  71958. }
  71959. // Merge into a single mesh
  71960. var engine = this._source.getScene().getEngine();
  71961. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  71962. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  71963. this._ib = engine.createIndexBuffer(this._linesIndices);
  71964. this._indicesCount = this._linesIndices.length;
  71965. };
  71966. EdgesRenderer.prototype.render = function () {
  71967. var scene = this._source.getScene();
  71968. if (!this._lineShader.isReady() || !scene.activeCamera) {
  71969. return;
  71970. }
  71971. var engine = scene.getEngine();
  71972. this._lineShader._preBind();
  71973. // VBOs
  71974. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  71975. scene.resetCachedMaterial();
  71976. this._lineShader.setColor4("color", this._source.edgesColor);
  71977. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  71978. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  71979. }
  71980. else {
  71981. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  71982. }
  71983. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  71984. this._lineShader.bind(this._source.getWorldMatrix());
  71985. // Draw order
  71986. engine.draw(true, 0, this._indicesCount);
  71987. this._lineShader.unbind();
  71988. engine.setDepthWrite(true);
  71989. };
  71990. return EdgesRenderer;
  71991. }());
  71992. BABYLON.EdgesRenderer = EdgesRenderer;
  71993. })(BABYLON || (BABYLON = {}));
  71994. //# sourceMappingURL=babylon.edgesRenderer.js.map
  71995. var BABYLON;
  71996. (function (BABYLON) {
  71997. /**
  71998. * Special Glow Blur post process only blurring the alpha channel
  71999. * It enforces keeping the most luminous color in the color channel.
  72000. */
  72001. var GlowBlurPostProcess = /** @class */ (function (_super) {
  72002. __extends(GlowBlurPostProcess, _super);
  72003. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  72004. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72005. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  72006. _this.direction = direction;
  72007. _this.kernel = kernel;
  72008. _this.onApplyObservable.add(function (effect) {
  72009. effect.setFloat2("screenSize", _this.width, _this.height);
  72010. effect.setVector2("direction", _this.direction);
  72011. effect.setFloat("blurWidth", _this.kernel);
  72012. });
  72013. return _this;
  72014. }
  72015. return GlowBlurPostProcess;
  72016. }(BABYLON.PostProcess));
  72017. /**
  72018. * The highlight layer Helps adding a glow effect around a mesh.
  72019. *
  72020. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  72021. * glowy meshes to your scene.
  72022. *
  72023. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  72024. */
  72025. var HighlightLayer = /** @class */ (function () {
  72026. /**
  72027. * Instantiates a new highlight Layer and references it to the scene..
  72028. * @param name The name of the layer
  72029. * @param scene The scene to use the layer in
  72030. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  72031. */
  72032. function HighlightLayer(name, scene, options) {
  72033. this.name = name;
  72034. this._vertexBuffers = {};
  72035. this._mainTextureDesiredSize = { width: 0, height: 0 };
  72036. this._meshes = {};
  72037. this._maxSize = 0;
  72038. this._shouldRender = false;
  72039. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  72040. this._excludedMeshes = {};
  72041. /**
  72042. * Specifies whether or not the inner glow is ACTIVE in the layer.
  72043. */
  72044. this.innerGlow = true;
  72045. /**
  72046. * Specifies whether or not the outer glow is ACTIVE in the layer.
  72047. */
  72048. this.outerGlow = true;
  72049. /**
  72050. * Specifies wether the highlight layer is enabled or not.
  72051. */
  72052. this.isEnabled = true;
  72053. /**
  72054. * An event triggered when the highlight layer has been disposed.
  72055. * @type {BABYLON.Observable}
  72056. */
  72057. this.onDisposeObservable = new BABYLON.Observable();
  72058. /**
  72059. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  72060. * @type {BABYLON.Observable}
  72061. */
  72062. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  72063. /**
  72064. * An event triggered when the highlight layer is being blurred.
  72065. * @type {BABYLON.Observable}
  72066. */
  72067. this.onBeforeBlurObservable = new BABYLON.Observable();
  72068. /**
  72069. * An event triggered when the highlight layer has been blurred.
  72070. * @type {BABYLON.Observable}
  72071. */
  72072. this.onAfterBlurObservable = new BABYLON.Observable();
  72073. /**
  72074. * An event triggered when the glowing blurred texture is being merged in the scene.
  72075. * @type {BABYLON.Observable}
  72076. */
  72077. this.onBeforeComposeObservable = new BABYLON.Observable();
  72078. /**
  72079. * An event triggered when the glowing blurred texture has been merged in the scene.
  72080. * @type {BABYLON.Observable}
  72081. */
  72082. this.onAfterComposeObservable = new BABYLON.Observable();
  72083. /**
  72084. * An event triggered when the highlight layer changes its size.
  72085. * @type {BABYLON.Observable}
  72086. */
  72087. this.onSizeChangedObservable = new BABYLON.Observable();
  72088. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72089. var engine = scene.getEngine();
  72090. this._engine = engine;
  72091. this._maxSize = this._engine.getCaps().maxTextureSize;
  72092. this._scene.highlightLayers.push(this);
  72093. // Warn on stencil.
  72094. if (!this._engine.isStencilEnable) {
  72095. 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 }");
  72096. }
  72097. // Adapt options
  72098. this._options = options || {
  72099. mainTextureRatio: 0.5,
  72100. blurTextureSizeRatio: 0.5,
  72101. blurHorizontalSize: 1.0,
  72102. blurVerticalSize: 1.0,
  72103. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  72104. camera: null
  72105. };
  72106. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  72107. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  72108. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  72109. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  72110. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  72111. // VBO
  72112. var vertices = [];
  72113. vertices.push(1, 1);
  72114. vertices.push(-1, 1);
  72115. vertices.push(-1, -1);
  72116. vertices.push(1, -1);
  72117. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72118. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  72119. this._createIndexBuffer();
  72120. // Effect
  72121. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  72122. // Render target
  72123. this.setMainTextureSize();
  72124. // Create Textures and post processes
  72125. this.createTextureAndPostProcesses();
  72126. }
  72127. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  72128. /**
  72129. * Gets the horizontal size of the blur.
  72130. */
  72131. get: function () {
  72132. return this._horizontalBlurPostprocess.kernel;
  72133. },
  72134. /**
  72135. * Specifies the horizontal size of the blur.
  72136. */
  72137. set: function (value) {
  72138. this._horizontalBlurPostprocess.kernel = value;
  72139. },
  72140. enumerable: true,
  72141. configurable: true
  72142. });
  72143. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  72144. /**
  72145. * Gets the vertical size of the blur.
  72146. */
  72147. get: function () {
  72148. return this._verticalBlurPostprocess.kernel;
  72149. },
  72150. /**
  72151. * Specifies the vertical size of the blur.
  72152. */
  72153. set: function (value) {
  72154. this._verticalBlurPostprocess.kernel = value;
  72155. },
  72156. enumerable: true,
  72157. configurable: true
  72158. });
  72159. Object.defineProperty(HighlightLayer.prototype, "camera", {
  72160. /**
  72161. * Gets the camera attached to the layer.
  72162. */
  72163. get: function () {
  72164. return this._options.camera;
  72165. },
  72166. enumerable: true,
  72167. configurable: true
  72168. });
  72169. HighlightLayer.prototype._createIndexBuffer = function () {
  72170. var engine = this._scene.getEngine();
  72171. // Indices
  72172. var indices = [];
  72173. indices.push(0);
  72174. indices.push(1);
  72175. indices.push(2);
  72176. indices.push(0);
  72177. indices.push(2);
  72178. indices.push(3);
  72179. this._indexBuffer = engine.createIndexBuffer(indices);
  72180. };
  72181. HighlightLayer.prototype._rebuild = function () {
  72182. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72183. if (vb) {
  72184. vb._rebuild();
  72185. }
  72186. this._createIndexBuffer();
  72187. };
  72188. /**
  72189. * Creates the render target textures and post processes used in the highlight layer.
  72190. */
  72191. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  72192. var _this = this;
  72193. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  72194. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  72195. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  72196. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  72197. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  72198. width: this._mainTextureDesiredSize.width,
  72199. height: this._mainTextureDesiredSize.height
  72200. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72201. this._mainTexture.activeCamera = this._options.camera;
  72202. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72203. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72204. this._mainTexture.anisotropicFilteringLevel = 1;
  72205. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72206. this._mainTexture.renderParticles = false;
  72207. this._mainTexture.renderList = null;
  72208. this._mainTexture.ignoreCameraViewport = true;
  72209. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  72210. width: blurTextureWidth,
  72211. height: blurTextureHeight
  72212. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72213. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72214. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72215. this._blurTexture.anisotropicFilteringLevel = 16;
  72216. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72217. this._blurTexture.renderParticles = false;
  72218. this._blurTexture.ignoreCameraViewport = true;
  72219. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72220. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  72221. effect.setTexture("textureSampler", _this._mainTexture);
  72222. });
  72223. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  72224. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72225. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72226. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72227. });
  72228. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72229. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72230. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72231. });
  72232. }
  72233. else {
  72234. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72235. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72236. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72237. });
  72238. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72239. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72240. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72241. });
  72242. }
  72243. this._mainTexture.onAfterUnbindObservable.add(function () {
  72244. _this.onBeforeBlurObservable.notifyObservers(_this);
  72245. var internalTexture = _this._blurTexture.getInternalTexture();
  72246. if (internalTexture) {
  72247. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  72248. }
  72249. _this.onAfterBlurObservable.notifyObservers(_this);
  72250. });
  72251. // Custom render function
  72252. var renderSubMesh = function (subMesh) {
  72253. if (!_this._meshes) {
  72254. return;
  72255. }
  72256. var material = subMesh.getMaterial();
  72257. var mesh = subMesh.getRenderingMesh();
  72258. var scene = _this._scene;
  72259. var engine = scene.getEngine();
  72260. if (!material) {
  72261. return;
  72262. }
  72263. // Culling
  72264. engine.setState(material.backFaceCulling);
  72265. // Managing instances
  72266. var batch = mesh._getInstancesRenderList(subMesh._id);
  72267. if (batch.mustReturn) {
  72268. return;
  72269. }
  72270. // Excluded Mesh
  72271. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72272. return;
  72273. }
  72274. ;
  72275. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72276. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  72277. var emissiveTexture = null;
  72278. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  72279. emissiveTexture = material.emissiveTexture;
  72280. }
  72281. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  72282. engine.enableEffect(_this._glowMapGenerationEffect);
  72283. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  72284. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  72285. if (highlightLayerMesh) {
  72286. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  72287. }
  72288. else {
  72289. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  72290. }
  72291. // Alpha test
  72292. if (material && material.needAlphaTesting()) {
  72293. var alphaTexture = material.getAlphaTestTexture();
  72294. if (alphaTexture) {
  72295. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  72296. var textureMatrix = alphaTexture.getTextureMatrix();
  72297. if (textureMatrix) {
  72298. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  72299. }
  72300. }
  72301. }
  72302. // Glow emissive only
  72303. if (emissiveTexture) {
  72304. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  72305. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  72306. }
  72307. // Bones
  72308. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72309. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72310. }
  72311. // Draw
  72312. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  72313. }
  72314. else {
  72315. // Need to reset refresh rate of the shadowMap
  72316. _this._mainTexture.resetRefreshCounter();
  72317. }
  72318. };
  72319. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72320. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  72321. var index;
  72322. var engine = _this._scene.getEngine();
  72323. if (depthOnlySubMeshes.length) {
  72324. engine.setColorWrite(false);
  72325. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72326. renderSubMesh(depthOnlySubMeshes.data[index]);
  72327. }
  72328. engine.setColorWrite(true);
  72329. }
  72330. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72331. renderSubMesh(opaqueSubMeshes.data[index]);
  72332. }
  72333. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72334. renderSubMesh(alphaTestSubMeshes.data[index]);
  72335. }
  72336. for (index = 0; index < transparentSubMeshes.length; index++) {
  72337. renderSubMesh(transparentSubMeshes.data[index]);
  72338. }
  72339. };
  72340. this._mainTexture.onClearObservable.add(function (engine) {
  72341. engine.clear(HighlightLayer.neutralColor, true, true, true);
  72342. });
  72343. };
  72344. /**
  72345. * Checks for the readiness of the element composing the layer.
  72346. * @param subMesh the mesh to check for
  72347. * @param useInstances specify wether or not to use instances to render the mesh
  72348. * @param emissiveTexture the associated emissive texture used to generate the glow
  72349. * @return true if ready otherwise, false
  72350. */
  72351. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  72352. var material = subMesh.getMaterial();
  72353. if (!material) {
  72354. return false;
  72355. }
  72356. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  72357. return false;
  72358. }
  72359. var defines = [];
  72360. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72361. var mesh = subMesh.getMesh();
  72362. var uv1 = false;
  72363. var uv2 = false;
  72364. // Alpha test
  72365. if (material && material.needAlphaTesting()) {
  72366. var alphaTexture = material.getAlphaTestTexture();
  72367. if (alphaTexture) {
  72368. defines.push("#define ALPHATEST");
  72369. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72370. alphaTexture.coordinatesIndex === 1) {
  72371. defines.push("#define DIFFUSEUV2");
  72372. uv2 = true;
  72373. }
  72374. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72375. defines.push("#define DIFFUSEUV1");
  72376. uv1 = true;
  72377. }
  72378. }
  72379. }
  72380. // Emissive
  72381. if (emissiveTexture) {
  72382. defines.push("#define EMISSIVE");
  72383. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72384. emissiveTexture.coordinatesIndex === 1) {
  72385. defines.push("#define EMISSIVEUV2");
  72386. uv2 = true;
  72387. }
  72388. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72389. defines.push("#define EMISSIVEUV1");
  72390. uv1 = true;
  72391. }
  72392. }
  72393. if (uv1) {
  72394. attribs.push(BABYLON.VertexBuffer.UVKind);
  72395. defines.push("#define UV1");
  72396. }
  72397. if (uv2) {
  72398. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72399. defines.push("#define UV2");
  72400. }
  72401. // Bones
  72402. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72403. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72404. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72405. if (mesh.numBoneInfluencers > 4) {
  72406. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72407. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72408. }
  72409. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72410. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72411. }
  72412. else {
  72413. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72414. }
  72415. // Instances
  72416. if (useInstances) {
  72417. defines.push("#define INSTANCES");
  72418. attribs.push("world0");
  72419. attribs.push("world1");
  72420. attribs.push("world2");
  72421. attribs.push("world3");
  72422. }
  72423. // Get correct effect
  72424. var join = defines.join("\n");
  72425. if (this._cachedDefines !== join) {
  72426. this._cachedDefines = join;
  72427. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  72428. }
  72429. return this._glowMapGenerationEffect.isReady();
  72430. };
  72431. /**
  72432. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  72433. */
  72434. HighlightLayer.prototype.render = function () {
  72435. var currentEffect = this._glowMapMergeEffect;
  72436. // Check
  72437. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  72438. return;
  72439. var engine = this._scene.getEngine();
  72440. this.onBeforeComposeObservable.notifyObservers(this);
  72441. // Render
  72442. engine.enableEffect(currentEffect);
  72443. engine.setState(false);
  72444. // Cache
  72445. var previousStencilBuffer = engine.getStencilBuffer();
  72446. var previousStencilFunction = engine.getStencilFunction();
  72447. var previousStencilMask = engine.getStencilMask();
  72448. var previousStencilOperationPass = engine.getStencilOperationPass();
  72449. var previousStencilOperationFail = engine.getStencilOperationFail();
  72450. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  72451. var previousAlphaMode = engine.getAlphaMode();
  72452. // Texture
  72453. currentEffect.setTexture("textureSampler", this._blurTexture);
  72454. // VBOs
  72455. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72456. // Stencil operations
  72457. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  72458. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  72459. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  72460. // Draw order
  72461. engine.setAlphaMode(this._options.alphaBlendingMode);
  72462. engine.setStencilMask(0x00);
  72463. engine.setStencilBuffer(true);
  72464. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  72465. if (this.outerGlow) {
  72466. currentEffect.setFloat("offset", 0);
  72467. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  72468. engine.draw(true, 0, 6);
  72469. }
  72470. if (this.innerGlow) {
  72471. currentEffect.setFloat("offset", 1);
  72472. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  72473. engine.draw(true, 0, 6);
  72474. }
  72475. // Restore Cache
  72476. engine.setStencilFunction(previousStencilFunction);
  72477. engine.setStencilMask(previousStencilMask);
  72478. engine.setAlphaMode(previousAlphaMode);
  72479. engine.setStencilBuffer(previousStencilBuffer);
  72480. engine.setStencilOperationPass(previousStencilOperationPass);
  72481. engine.setStencilOperationFail(previousStencilOperationFail);
  72482. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  72483. engine._stencilState.reset();
  72484. this.onAfterComposeObservable.notifyObservers(this);
  72485. // Handle size changes.
  72486. var size = this._mainTexture.getSize();
  72487. this.setMainTextureSize();
  72488. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  72489. // Recreate RTT and post processes on size change.
  72490. this.onSizeChangedObservable.notifyObservers(this);
  72491. this.disposeTextureAndPostProcesses();
  72492. this.createTextureAndPostProcesses();
  72493. }
  72494. };
  72495. /**
  72496. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  72497. * @param mesh The mesh to exclude from the highlight layer
  72498. */
  72499. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  72500. if (!this._excludedMeshes) {
  72501. return;
  72502. }
  72503. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72504. if (!meshExcluded) {
  72505. this._excludedMeshes[mesh.uniqueId] = {
  72506. mesh: mesh,
  72507. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  72508. mesh.getEngine().setStencilBuffer(false);
  72509. }),
  72510. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  72511. mesh.getEngine().setStencilBuffer(true);
  72512. }),
  72513. };
  72514. }
  72515. };
  72516. /**
  72517. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  72518. * @param mesh The mesh to highlight
  72519. */
  72520. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  72521. if (!this._excludedMeshes) {
  72522. return;
  72523. }
  72524. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72525. if (meshExcluded) {
  72526. if (meshExcluded.beforeRender) {
  72527. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  72528. }
  72529. if (meshExcluded.afterRender) {
  72530. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  72531. }
  72532. }
  72533. this._excludedMeshes[mesh.uniqueId] = null;
  72534. };
  72535. /**
  72536. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  72537. * @param mesh The mesh to highlight
  72538. * @param color The color of the highlight
  72539. * @param glowEmissiveOnly Extract the glow from the emissive texture
  72540. */
  72541. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  72542. var _this = this;
  72543. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  72544. if (!this._meshes) {
  72545. return;
  72546. }
  72547. var meshHighlight = this._meshes[mesh.uniqueId];
  72548. if (meshHighlight) {
  72549. meshHighlight.color = color;
  72550. }
  72551. else {
  72552. this._meshes[mesh.uniqueId] = {
  72553. mesh: mesh,
  72554. color: color,
  72555. // Lambda required for capture due to Observable this context
  72556. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  72557. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72558. _this.defaultStencilReference(mesh);
  72559. }
  72560. else {
  72561. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  72562. }
  72563. }),
  72564. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  72565. glowEmissiveOnly: glowEmissiveOnly
  72566. };
  72567. }
  72568. this._shouldRender = true;
  72569. };
  72570. /**
  72571. * Remove a mesh from the highlight layer in order to make it stop glowing.
  72572. * @param mesh The mesh to highlight
  72573. */
  72574. HighlightLayer.prototype.removeMesh = function (mesh) {
  72575. if (!this._meshes) {
  72576. return;
  72577. }
  72578. var meshHighlight = this._meshes[mesh.uniqueId];
  72579. if (meshHighlight) {
  72580. if (meshHighlight.observerHighlight) {
  72581. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72582. }
  72583. if (meshHighlight.observerDefault) {
  72584. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72585. }
  72586. }
  72587. this._meshes[mesh.uniqueId] = null;
  72588. this._shouldRender = false;
  72589. for (var meshHighlightToCheck in this._meshes) {
  72590. if (meshHighlightToCheck) {
  72591. this._shouldRender = true;
  72592. break;
  72593. }
  72594. }
  72595. };
  72596. /**
  72597. * Returns true if the layer contains information to display, otherwise false.
  72598. */
  72599. HighlightLayer.prototype.shouldRender = function () {
  72600. return this.isEnabled && this._shouldRender;
  72601. };
  72602. /**
  72603. * Sets the main texture desired size which is the closest power of two
  72604. * of the engine canvas size.
  72605. */
  72606. HighlightLayer.prototype.setMainTextureSize = function () {
  72607. if (this._options.mainTextureFixedSize) {
  72608. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  72609. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  72610. }
  72611. else {
  72612. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  72613. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  72614. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  72615. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  72616. }
  72617. };
  72618. /**
  72619. * Force the stencil to the normal expected value for none glowing parts
  72620. */
  72621. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  72622. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  72623. };
  72624. /**
  72625. * Dispose only the render target textures and post process.
  72626. */
  72627. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  72628. this._blurTexture.dispose();
  72629. this._mainTexture.dispose();
  72630. this._downSamplePostprocess.dispose();
  72631. this._horizontalBlurPostprocess.dispose();
  72632. this._verticalBlurPostprocess.dispose();
  72633. };
  72634. /**
  72635. * Dispose the highlight layer and free resources.
  72636. */
  72637. HighlightLayer.prototype.dispose = function () {
  72638. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72639. if (vertexBuffer) {
  72640. vertexBuffer.dispose();
  72641. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72642. }
  72643. if (this._indexBuffer) {
  72644. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72645. this._indexBuffer = null;
  72646. }
  72647. // Clean textures and post processes
  72648. this.disposeTextureAndPostProcesses();
  72649. if (this._meshes) {
  72650. // Clean mesh references
  72651. for (var id in this._meshes) {
  72652. var meshHighlight = this._meshes[id];
  72653. if (meshHighlight && meshHighlight.mesh) {
  72654. if (meshHighlight.observerHighlight) {
  72655. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72656. }
  72657. if (meshHighlight.observerDefault) {
  72658. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72659. }
  72660. }
  72661. }
  72662. this._meshes = null;
  72663. }
  72664. if (this._excludedMeshes) {
  72665. for (var id in this._excludedMeshes) {
  72666. var meshHighlight = this._excludedMeshes[id];
  72667. if (meshHighlight) {
  72668. if (meshHighlight.beforeRender) {
  72669. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  72670. }
  72671. if (meshHighlight.afterRender) {
  72672. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  72673. }
  72674. }
  72675. }
  72676. this._excludedMeshes = null;
  72677. }
  72678. // Remove from scene
  72679. var index = this._scene.highlightLayers.indexOf(this, 0);
  72680. if (index > -1) {
  72681. this._scene.highlightLayers.splice(index, 1);
  72682. }
  72683. // Callback
  72684. this.onDisposeObservable.notifyObservers(this);
  72685. this.onDisposeObservable.clear();
  72686. this.onBeforeRenderMainTextureObservable.clear();
  72687. this.onBeforeBlurObservable.clear();
  72688. this.onBeforeComposeObservable.clear();
  72689. this.onAfterComposeObservable.clear();
  72690. this.onSizeChangedObservable.clear();
  72691. };
  72692. /**
  72693. * The neutral color used during the preparation of the glow effect.
  72694. * This is black by default as the blend operation is a blend operation.
  72695. */
  72696. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  72697. /**
  72698. * Stencil value used for glowing meshes.
  72699. */
  72700. HighlightLayer.glowingMeshStencilReference = 0x02;
  72701. /**
  72702. * Stencil value used for the other meshes in the scene.
  72703. */
  72704. HighlightLayer.normalMeshStencilReference = 0x01;
  72705. return HighlightLayer;
  72706. }());
  72707. BABYLON.HighlightLayer = HighlightLayer;
  72708. })(BABYLON || (BABYLON = {}));
  72709. //# sourceMappingURL=babylon.highlightlayer.js.map
  72710. var BABYLON;
  72711. (function (BABYLON) {
  72712. var AssetTaskState;
  72713. (function (AssetTaskState) {
  72714. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  72715. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  72716. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  72717. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  72718. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  72719. var AbstractAssetTask = /** @class */ (function () {
  72720. function AbstractAssetTask(name) {
  72721. this.name = name;
  72722. this.isCompleted = false;
  72723. this.taskState = AssetTaskState.INIT;
  72724. }
  72725. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72726. var _this = this;
  72727. this.taskState = AssetTaskState.RUNNING;
  72728. this.runTask(scene, function () {
  72729. _this.onDoneCallback(onSuccess, onError);
  72730. }, function (msg, exception) {
  72731. _this.onErrorCallback(onError, msg, exception);
  72732. });
  72733. };
  72734. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72735. throw new Error("runTask is not implemented");
  72736. };
  72737. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  72738. this.taskState = AssetTaskState.ERROR;
  72739. this.errorObject = {
  72740. message: message,
  72741. exception: exception
  72742. };
  72743. if (this.onError) {
  72744. this.onError(this, message, exception);
  72745. }
  72746. onError();
  72747. };
  72748. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  72749. try {
  72750. this.taskState = AssetTaskState.DONE;
  72751. this.isCompleted = true;
  72752. if (this.onSuccess) {
  72753. this.onSuccess(this);
  72754. }
  72755. onSuccess();
  72756. }
  72757. catch (e) {
  72758. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  72759. }
  72760. };
  72761. return AbstractAssetTask;
  72762. }());
  72763. BABYLON.AbstractAssetTask = AbstractAssetTask;
  72764. var AssetsProgressEvent = /** @class */ (function () {
  72765. function AssetsProgressEvent(remainingCount, totalCount, task) {
  72766. this.remainingCount = remainingCount;
  72767. this.totalCount = totalCount;
  72768. this.task = task;
  72769. }
  72770. return AssetsProgressEvent;
  72771. }());
  72772. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  72773. var MeshAssetTask = /** @class */ (function (_super) {
  72774. __extends(MeshAssetTask, _super);
  72775. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  72776. var _this = _super.call(this, name) || this;
  72777. _this.name = name;
  72778. _this.meshesNames = meshesNames;
  72779. _this.rootUrl = rootUrl;
  72780. _this.sceneFilename = sceneFilename;
  72781. return _this;
  72782. }
  72783. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72784. var _this = this;
  72785. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  72786. _this.loadedMeshes = meshes;
  72787. _this.loadedParticleSystems = particleSystems;
  72788. _this.loadedSkeletons = skeletons;
  72789. onSuccess();
  72790. }, null, function (scene, message, exception) {
  72791. onError(message, exception);
  72792. });
  72793. };
  72794. return MeshAssetTask;
  72795. }(AbstractAssetTask));
  72796. BABYLON.MeshAssetTask = MeshAssetTask;
  72797. var TextFileAssetTask = /** @class */ (function (_super) {
  72798. __extends(TextFileAssetTask, _super);
  72799. function TextFileAssetTask(name, url) {
  72800. var _this = _super.call(this, name) || this;
  72801. _this.name = name;
  72802. _this.url = url;
  72803. return _this;
  72804. }
  72805. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72806. var _this = this;
  72807. BABYLON.Tools.LoadFile(this.url, function (data) {
  72808. _this.text = data;
  72809. onSuccess();
  72810. }, undefined, scene.database, false, function (request, exception) {
  72811. if (request) {
  72812. onError(request.status + " " + request.statusText, exception);
  72813. }
  72814. });
  72815. };
  72816. return TextFileAssetTask;
  72817. }(AbstractAssetTask));
  72818. BABYLON.TextFileAssetTask = TextFileAssetTask;
  72819. var BinaryFileAssetTask = /** @class */ (function (_super) {
  72820. __extends(BinaryFileAssetTask, _super);
  72821. function BinaryFileAssetTask(name, url) {
  72822. var _this = _super.call(this, name) || this;
  72823. _this.name = name;
  72824. _this.url = url;
  72825. return _this;
  72826. }
  72827. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72828. var _this = this;
  72829. BABYLON.Tools.LoadFile(this.url, function (data) {
  72830. _this.data = data;
  72831. onSuccess();
  72832. }, undefined, scene.database, true, function (request, exception) {
  72833. if (request) {
  72834. onError(request.status + " " + request.statusText, exception);
  72835. }
  72836. });
  72837. };
  72838. return BinaryFileAssetTask;
  72839. }(AbstractAssetTask));
  72840. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  72841. var ImageAssetTask = /** @class */ (function (_super) {
  72842. __extends(ImageAssetTask, _super);
  72843. function ImageAssetTask(name, url) {
  72844. var _this = _super.call(this, name) || this;
  72845. _this.name = name;
  72846. _this.url = url;
  72847. return _this;
  72848. }
  72849. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72850. var _this = this;
  72851. var img = new Image();
  72852. BABYLON.Tools.SetCorsBehavior(this.url, img);
  72853. img.onload = function () {
  72854. _this.image = img;
  72855. onSuccess();
  72856. };
  72857. img.onerror = function (err) {
  72858. onError("Error loading image", err);
  72859. };
  72860. img.src = this.url;
  72861. };
  72862. return ImageAssetTask;
  72863. }(AbstractAssetTask));
  72864. BABYLON.ImageAssetTask = ImageAssetTask;
  72865. var TextureAssetTask = /** @class */ (function (_super) {
  72866. __extends(TextureAssetTask, _super);
  72867. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  72868. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72869. var _this = _super.call(this, name) || this;
  72870. _this.name = name;
  72871. _this.url = url;
  72872. _this.noMipmap = noMipmap;
  72873. _this.invertY = invertY;
  72874. _this.samplingMode = samplingMode;
  72875. return _this;
  72876. }
  72877. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72878. var onload = function () {
  72879. onSuccess();
  72880. };
  72881. var onerror = function (msg, exception) {
  72882. onError(msg, exception);
  72883. };
  72884. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  72885. };
  72886. return TextureAssetTask;
  72887. }(AbstractAssetTask));
  72888. BABYLON.TextureAssetTask = TextureAssetTask;
  72889. var CubeTextureAssetTask = /** @class */ (function (_super) {
  72890. __extends(CubeTextureAssetTask, _super);
  72891. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  72892. var _this = _super.call(this, name) || this;
  72893. _this.name = name;
  72894. _this.url = url;
  72895. _this.extensions = extensions;
  72896. _this.noMipmap = noMipmap;
  72897. _this.files = files;
  72898. return _this;
  72899. }
  72900. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72901. var onload = function () {
  72902. onSuccess();
  72903. };
  72904. var onerror = function (msg, exception) {
  72905. onError(msg, exception);
  72906. };
  72907. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  72908. };
  72909. return CubeTextureAssetTask;
  72910. }(AbstractAssetTask));
  72911. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  72912. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  72913. __extends(HDRCubeTextureAssetTask, _super);
  72914. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72915. if (noMipmap === void 0) { noMipmap = false; }
  72916. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72917. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72918. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72919. var _this = _super.call(this, name) || this;
  72920. _this.name = name;
  72921. _this.url = url;
  72922. _this.size = size;
  72923. _this.noMipmap = noMipmap;
  72924. _this.generateHarmonics = generateHarmonics;
  72925. _this.useInGammaSpace = useInGammaSpace;
  72926. _this.usePMREMGenerator = usePMREMGenerator;
  72927. return _this;
  72928. }
  72929. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72930. var onload = function () {
  72931. onSuccess();
  72932. };
  72933. var onerror = function (message, exception) {
  72934. onError(message, exception);
  72935. };
  72936. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  72937. };
  72938. return HDRCubeTextureAssetTask;
  72939. }(AbstractAssetTask));
  72940. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  72941. var AssetsManager = /** @class */ (function () {
  72942. function AssetsManager(scene) {
  72943. this.tasks = new Array();
  72944. this.waitingTasksCount = 0;
  72945. //Observables
  72946. this.onTaskSuccessObservable = new BABYLON.Observable();
  72947. this.onTaskErrorObservable = new BABYLON.Observable();
  72948. this.onTasksDoneObservable = new BABYLON.Observable();
  72949. this.onProgressObservable = new BABYLON.Observable();
  72950. this.useDefaultLoadingScreen = true;
  72951. this._scene = scene;
  72952. }
  72953. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  72954. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  72955. this.tasks.push(task);
  72956. return task;
  72957. };
  72958. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  72959. var task = new TextFileAssetTask(taskName, url);
  72960. this.tasks.push(task);
  72961. return task;
  72962. };
  72963. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  72964. var task = new BinaryFileAssetTask(taskName, url);
  72965. this.tasks.push(task);
  72966. return task;
  72967. };
  72968. AssetsManager.prototype.addImageTask = function (taskName, url) {
  72969. var task = new ImageAssetTask(taskName, url);
  72970. this.tasks.push(task);
  72971. return task;
  72972. };
  72973. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  72974. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72975. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  72976. this.tasks.push(task);
  72977. return task;
  72978. };
  72979. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  72980. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  72981. this.tasks.push(task);
  72982. return task;
  72983. };
  72984. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72985. if (noMipmap === void 0) { noMipmap = false; }
  72986. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72987. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72988. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72989. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  72990. this.tasks.push(task);
  72991. return task;
  72992. };
  72993. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  72994. this.waitingTasksCount--;
  72995. try {
  72996. if (this.onProgress) {
  72997. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  72998. }
  72999. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  73000. }
  73001. catch (e) {
  73002. BABYLON.Tools.Error("Error running progress callbacks.");
  73003. console.log(e);
  73004. }
  73005. if (this.waitingTasksCount === 0) {
  73006. try {
  73007. if (this.onFinish) {
  73008. this.onFinish(this.tasks);
  73009. }
  73010. this.onTasksDoneObservable.notifyObservers(this.tasks);
  73011. }
  73012. catch (e) {
  73013. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  73014. console.log(e);
  73015. }
  73016. this._scene.getEngine().hideLoadingUI();
  73017. }
  73018. };
  73019. AssetsManager.prototype._runTask = function (task) {
  73020. var _this = this;
  73021. var done = function () {
  73022. try {
  73023. if (_this.onTaskSuccess) {
  73024. _this.onTaskSuccess(task);
  73025. }
  73026. _this.onTaskSuccessObservable.notifyObservers(task);
  73027. _this._decreaseWaitingTasksCount(task);
  73028. }
  73029. catch (e) {
  73030. error("Error executing task success callbacks", e);
  73031. }
  73032. };
  73033. var error = function (message, exception) {
  73034. task.errorObject = task.errorObject || {
  73035. message: message,
  73036. exception: exception
  73037. };
  73038. if (_this.onTaskError) {
  73039. _this.onTaskError(task);
  73040. }
  73041. _this.onTaskErrorObservable.notifyObservers(task);
  73042. _this._decreaseWaitingTasksCount(task);
  73043. };
  73044. task.run(this._scene, done, error);
  73045. };
  73046. AssetsManager.prototype.reset = function () {
  73047. this.tasks = new Array();
  73048. return this;
  73049. };
  73050. AssetsManager.prototype.load = function () {
  73051. this.waitingTasksCount = this.tasks.length;
  73052. if (this.waitingTasksCount === 0) {
  73053. if (this.onFinish) {
  73054. this.onFinish(this.tasks);
  73055. }
  73056. this.onTasksDoneObservable.notifyObservers(this.tasks);
  73057. return this;
  73058. }
  73059. if (this.useDefaultLoadingScreen) {
  73060. this._scene.getEngine().displayLoadingUI();
  73061. }
  73062. for (var index = 0; index < this.tasks.length; index++) {
  73063. var task = this.tasks[index];
  73064. this._runTask(task);
  73065. }
  73066. return this;
  73067. };
  73068. return AssetsManager;
  73069. }());
  73070. BABYLON.AssetsManager = AssetsManager;
  73071. })(BABYLON || (BABYLON = {}));
  73072. //# sourceMappingURL=babylon.assetsManager.js.map
  73073. var BABYLON;
  73074. (function (BABYLON) {
  73075. var serializedGeometries = [];
  73076. var serializeGeometry = function (geometry, serializationGeometries) {
  73077. if (serializedGeometries[geometry.id]) {
  73078. return;
  73079. }
  73080. if (geometry.doNotSerialize) {
  73081. return;
  73082. }
  73083. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  73084. serializationGeometries.boxes.push(geometry.serialize());
  73085. }
  73086. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  73087. serializationGeometries.spheres.push(geometry.serialize());
  73088. }
  73089. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  73090. serializationGeometries.cylinders.push(geometry.serialize());
  73091. }
  73092. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  73093. serializationGeometries.toruses.push(geometry.serialize());
  73094. }
  73095. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  73096. serializationGeometries.grounds.push(geometry.serialize());
  73097. }
  73098. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  73099. serializationGeometries.planes.push(geometry.serialize());
  73100. }
  73101. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  73102. serializationGeometries.torusKnots.push(geometry.serialize());
  73103. }
  73104. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  73105. throw new Error("Unknown primitive type");
  73106. }
  73107. else {
  73108. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  73109. }
  73110. serializedGeometries[geometry.id] = true;
  73111. };
  73112. var serializeMesh = function (mesh, serializationScene) {
  73113. var serializationObject = {};
  73114. // Geometry
  73115. var geometry = mesh._geometry;
  73116. if (geometry) {
  73117. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  73118. // 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
  73119. serializeGeometry(geometry, serializationScene.geometries);
  73120. }
  73121. }
  73122. // Custom
  73123. if (mesh.serialize) {
  73124. mesh.serialize(serializationObject);
  73125. }
  73126. return serializationObject;
  73127. };
  73128. var finalizeSingleMesh = function (mesh, serializationObject) {
  73129. //only works if the mesh is already loaded
  73130. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73131. //serialize material
  73132. if (mesh.material) {
  73133. if (mesh.material instanceof BABYLON.StandardMaterial) {
  73134. serializationObject.materials = serializationObject.materials || [];
  73135. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  73136. serializationObject.materials.push(mesh.material.serialize());
  73137. }
  73138. }
  73139. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  73140. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  73141. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  73142. serializationObject.multiMaterials.push(mesh.material.serialize());
  73143. }
  73144. }
  73145. }
  73146. //serialize geometry
  73147. var geometry = mesh._geometry;
  73148. if (geometry) {
  73149. if (!serializationObject.geometries) {
  73150. serializationObject.geometries = {};
  73151. serializationObject.geometries.boxes = [];
  73152. serializationObject.geometries.spheres = [];
  73153. serializationObject.geometries.cylinders = [];
  73154. serializationObject.geometries.toruses = [];
  73155. serializationObject.geometries.grounds = [];
  73156. serializationObject.geometries.planes = [];
  73157. serializationObject.geometries.torusKnots = [];
  73158. serializationObject.geometries.vertexData = [];
  73159. }
  73160. serializeGeometry(geometry, serializationObject.geometries);
  73161. }
  73162. // Skeletons
  73163. if (mesh.skeleton) {
  73164. serializationObject.skeletons = serializationObject.skeletons || [];
  73165. serializationObject.skeletons.push(mesh.skeleton.serialize());
  73166. }
  73167. //serialize the actual mesh
  73168. serializationObject.meshes = serializationObject.meshes || [];
  73169. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73170. }
  73171. };
  73172. var SceneSerializer = /** @class */ (function () {
  73173. function SceneSerializer() {
  73174. }
  73175. SceneSerializer.ClearCache = function () {
  73176. serializedGeometries = [];
  73177. };
  73178. SceneSerializer.Serialize = function (scene) {
  73179. var serializationObject = {};
  73180. SceneSerializer.ClearCache();
  73181. // Scene
  73182. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  73183. serializationObject.autoClear = scene.autoClear;
  73184. serializationObject.clearColor = scene.clearColor.asArray();
  73185. serializationObject.ambientColor = scene.ambientColor.asArray();
  73186. serializationObject.gravity = scene.gravity.asArray();
  73187. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  73188. serializationObject.workerCollisions = scene.workerCollisions;
  73189. // Fog
  73190. if (scene.fogMode && scene.fogMode !== 0) {
  73191. serializationObject.fogMode = scene.fogMode;
  73192. serializationObject.fogColor = scene.fogColor.asArray();
  73193. serializationObject.fogStart = scene.fogStart;
  73194. serializationObject.fogEnd = scene.fogEnd;
  73195. serializationObject.fogDensity = scene.fogDensity;
  73196. }
  73197. //Physics
  73198. if (scene.isPhysicsEnabled()) {
  73199. var physicEngine = scene.getPhysicsEngine();
  73200. if (physicEngine) {
  73201. serializationObject.physicsEnabled = true;
  73202. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  73203. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  73204. }
  73205. }
  73206. // Metadata
  73207. if (scene.metadata) {
  73208. serializationObject.metadata = scene.metadata;
  73209. }
  73210. // Morph targets
  73211. serializationObject.morphTargetManagers = [];
  73212. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  73213. var abstractMesh = _a[_i];
  73214. var manager = abstractMesh.morphTargetManager;
  73215. if (manager) {
  73216. serializationObject.morphTargetManagers.push(manager.serialize());
  73217. }
  73218. }
  73219. // Lights
  73220. serializationObject.lights = [];
  73221. var index;
  73222. var light;
  73223. for (index = 0; index < scene.lights.length; index++) {
  73224. light = scene.lights[index];
  73225. if (!light.doNotSerialize) {
  73226. serializationObject.lights.push(light.serialize());
  73227. }
  73228. }
  73229. // Cameras
  73230. serializationObject.cameras = [];
  73231. for (index = 0; index < scene.cameras.length; index++) {
  73232. var camera = scene.cameras[index];
  73233. if (!camera.doNotSerialize) {
  73234. serializationObject.cameras.push(camera.serialize());
  73235. }
  73236. }
  73237. if (scene.activeCamera) {
  73238. serializationObject.activeCameraID = scene.activeCamera.id;
  73239. }
  73240. // Animations
  73241. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  73242. // Materials
  73243. serializationObject.materials = [];
  73244. serializationObject.multiMaterials = [];
  73245. var material;
  73246. for (index = 0; index < scene.materials.length; index++) {
  73247. material = scene.materials[index];
  73248. if (!material.doNotSerialize) {
  73249. serializationObject.materials.push(material.serialize());
  73250. }
  73251. }
  73252. // MultiMaterials
  73253. serializationObject.multiMaterials = [];
  73254. for (index = 0; index < scene.multiMaterials.length; index++) {
  73255. var multiMaterial = scene.multiMaterials[index];
  73256. serializationObject.multiMaterials.push(multiMaterial.serialize());
  73257. }
  73258. // Skeletons
  73259. serializationObject.skeletons = [];
  73260. for (index = 0; index < scene.skeletons.length; index++) {
  73261. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  73262. }
  73263. // Geometries
  73264. serializationObject.geometries = {};
  73265. serializationObject.geometries.boxes = [];
  73266. serializationObject.geometries.spheres = [];
  73267. serializationObject.geometries.cylinders = [];
  73268. serializationObject.geometries.toruses = [];
  73269. serializationObject.geometries.grounds = [];
  73270. serializationObject.geometries.planes = [];
  73271. serializationObject.geometries.torusKnots = [];
  73272. serializationObject.geometries.vertexData = [];
  73273. serializedGeometries = [];
  73274. var geometries = scene.getGeometries();
  73275. for (index = 0; index < geometries.length; index++) {
  73276. var geometry = geometries[index];
  73277. if (geometry.isReady()) {
  73278. serializeGeometry(geometry, serializationObject.geometries);
  73279. }
  73280. }
  73281. // Meshes
  73282. serializationObject.meshes = [];
  73283. for (index = 0; index < scene.meshes.length; index++) {
  73284. var abstractMesh = scene.meshes[index];
  73285. if (abstractMesh instanceof BABYLON.Mesh) {
  73286. var mesh = abstractMesh;
  73287. if (!mesh.doNotSerialize) {
  73288. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73289. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73290. }
  73291. }
  73292. }
  73293. }
  73294. // Particles Systems
  73295. serializationObject.particleSystems = [];
  73296. for (index = 0; index < scene.particleSystems.length; index++) {
  73297. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  73298. }
  73299. // Lens flares
  73300. serializationObject.lensFlareSystems = [];
  73301. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  73302. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  73303. }
  73304. // Shadows
  73305. serializationObject.shadowGenerators = [];
  73306. for (index = 0; index < scene.lights.length; index++) {
  73307. light = scene.lights[index];
  73308. var shadowGenerator = light.getShadowGenerator();
  73309. if (shadowGenerator) {
  73310. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73311. }
  73312. }
  73313. // Action Manager
  73314. if (scene.actionManager) {
  73315. serializationObject.actions = scene.actionManager.serialize("scene");
  73316. }
  73317. // Audio
  73318. serializationObject.sounds = [];
  73319. for (index = 0; index < scene.soundTracks.length; index++) {
  73320. var soundtrack = scene.soundTracks[index];
  73321. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  73322. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  73323. }
  73324. }
  73325. return serializationObject;
  73326. };
  73327. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  73328. if (withParents === void 0) { withParents = false; }
  73329. if (withChildren === void 0) { withChildren = false; }
  73330. var serializationObject = {};
  73331. SceneSerializer.ClearCache();
  73332. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  73333. if (withParents || withChildren) {
  73334. //deliberate for loop! not for each, appended should be processed as well.
  73335. for (var i = 0; i < toSerialize.length; ++i) {
  73336. if (withChildren) {
  73337. toSerialize[i].getDescendants().forEach(function (node) {
  73338. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  73339. toSerialize.push(node);
  73340. }
  73341. });
  73342. }
  73343. //make sure the array doesn't contain the object already
  73344. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  73345. toSerialize.push(toSerialize[i].parent);
  73346. }
  73347. }
  73348. }
  73349. toSerialize.forEach(function (mesh) {
  73350. finalizeSingleMesh(mesh, serializationObject);
  73351. });
  73352. return serializationObject;
  73353. };
  73354. return SceneSerializer;
  73355. }());
  73356. BABYLON.SceneSerializer = SceneSerializer;
  73357. })(BABYLON || (BABYLON = {}));
  73358. //# sourceMappingURL=babylon.sceneSerializer.js.map
  73359. var BABYLON;
  73360. (function (BABYLON) {
  73361. var ReflectionProbe = /** @class */ (function () {
  73362. function ReflectionProbe(name, size, scene, generateMipMaps) {
  73363. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73364. var _this = this;
  73365. this.name = name;
  73366. this._viewMatrix = BABYLON.Matrix.Identity();
  73367. this._target = BABYLON.Vector3.Zero();
  73368. this._add = BABYLON.Vector3.Zero();
  73369. this.invertYAxis = false;
  73370. this.position = BABYLON.Vector3.Zero();
  73371. this._scene = scene;
  73372. this._scene.reflectionProbes.push(this);
  73373. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  73374. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  73375. switch (faceIndex) {
  73376. case 0:
  73377. _this._add.copyFromFloats(1, 0, 0);
  73378. break;
  73379. case 1:
  73380. _this._add.copyFromFloats(-1, 0, 0);
  73381. break;
  73382. case 2:
  73383. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  73384. break;
  73385. case 3:
  73386. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  73387. break;
  73388. case 4:
  73389. _this._add.copyFromFloats(0, 0, 1);
  73390. break;
  73391. case 5:
  73392. _this._add.copyFromFloats(0, 0, -1);
  73393. break;
  73394. }
  73395. if (_this._attachedMesh) {
  73396. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  73397. }
  73398. _this.position.addToRef(_this._add, _this._target);
  73399. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  73400. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  73401. scene._forcedViewPosition = _this.position;
  73402. });
  73403. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  73404. scene._forcedViewPosition = null;
  73405. scene.updateTransformMatrix(true);
  73406. });
  73407. if (scene.activeCamera) {
  73408. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73409. }
  73410. }
  73411. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  73412. get: function () {
  73413. return this._renderTargetTexture.samples;
  73414. },
  73415. set: function (value) {
  73416. this._renderTargetTexture.samples = value;
  73417. },
  73418. enumerable: true,
  73419. configurable: true
  73420. });
  73421. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  73422. get: function () {
  73423. return this._renderTargetTexture.refreshRate;
  73424. },
  73425. set: function (value) {
  73426. this._renderTargetTexture.refreshRate = value;
  73427. },
  73428. enumerable: true,
  73429. configurable: true
  73430. });
  73431. ReflectionProbe.prototype.getScene = function () {
  73432. return this._scene;
  73433. };
  73434. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  73435. get: function () {
  73436. return this._renderTargetTexture;
  73437. },
  73438. enumerable: true,
  73439. configurable: true
  73440. });
  73441. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  73442. get: function () {
  73443. return this._renderTargetTexture.renderList;
  73444. },
  73445. enumerable: true,
  73446. configurable: true
  73447. });
  73448. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  73449. this._attachedMesh = mesh;
  73450. };
  73451. /**
  73452. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73453. *
  73454. * @param renderingGroupId The rendering group id corresponding to its index
  73455. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73456. */
  73457. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73458. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73459. };
  73460. ReflectionProbe.prototype.dispose = function () {
  73461. var index = this._scene.reflectionProbes.indexOf(this);
  73462. if (index !== -1) {
  73463. // Remove from the scene if found
  73464. this._scene.reflectionProbes.splice(index, 1);
  73465. }
  73466. if (this._renderTargetTexture) {
  73467. this._renderTargetTexture.dispose();
  73468. this._renderTargetTexture = null;
  73469. }
  73470. };
  73471. return ReflectionProbe;
  73472. }());
  73473. BABYLON.ReflectionProbe = ReflectionProbe;
  73474. })(BABYLON || (BABYLON = {}));
  73475. //# sourceMappingURL=babylon.reflectionProbe.js.map
  73476. var BABYLON;
  73477. (function (BABYLON) {
  73478. var Layer = /** @class */ (function () {
  73479. function Layer(name, imgUrl, scene, isBackground, color) {
  73480. this.name = name;
  73481. this.scale = new BABYLON.Vector2(1, 1);
  73482. this.offset = new BABYLON.Vector2(0, 0);
  73483. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  73484. this.layerMask = 0x0FFFFFFF;
  73485. this._vertexBuffers = {};
  73486. // Events
  73487. /**
  73488. * An event triggered when the layer is disposed.
  73489. * @type {BABYLON.Observable}
  73490. */
  73491. this.onDisposeObservable = new BABYLON.Observable();
  73492. /**
  73493. * An event triggered before rendering the scene
  73494. * @type {BABYLON.Observable}
  73495. */
  73496. this.onBeforeRenderObservable = new BABYLON.Observable();
  73497. /**
  73498. * An event triggered after rendering the scene
  73499. * @type {BABYLON.Observable}
  73500. */
  73501. this.onAfterRenderObservable = new BABYLON.Observable();
  73502. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  73503. this.isBackground = isBackground === undefined ? true : isBackground;
  73504. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  73505. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  73506. this._scene.layers.push(this);
  73507. var engine = this._scene.getEngine();
  73508. // VBO
  73509. var vertices = [];
  73510. vertices.push(1, 1);
  73511. vertices.push(-1, 1);
  73512. vertices.push(-1, -1);
  73513. vertices.push(1, -1);
  73514. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73515. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73516. this._createIndexBuffer();
  73517. // Effects
  73518. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  73519. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  73520. }
  73521. Object.defineProperty(Layer.prototype, "onDispose", {
  73522. set: function (callback) {
  73523. if (this._onDisposeObserver) {
  73524. this.onDisposeObservable.remove(this._onDisposeObserver);
  73525. }
  73526. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  73527. },
  73528. enumerable: true,
  73529. configurable: true
  73530. });
  73531. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  73532. set: function (callback) {
  73533. if (this._onBeforeRenderObserver) {
  73534. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73535. }
  73536. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73537. },
  73538. enumerable: true,
  73539. configurable: true
  73540. });
  73541. Object.defineProperty(Layer.prototype, "onAfterRender", {
  73542. set: function (callback) {
  73543. if (this._onAfterRenderObserver) {
  73544. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73545. }
  73546. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73547. },
  73548. enumerable: true,
  73549. configurable: true
  73550. });
  73551. Layer.prototype._createIndexBuffer = function () {
  73552. var engine = this._scene.getEngine();
  73553. // Indices
  73554. var indices = [];
  73555. indices.push(0);
  73556. indices.push(1);
  73557. indices.push(2);
  73558. indices.push(0);
  73559. indices.push(2);
  73560. indices.push(3);
  73561. this._indexBuffer = engine.createIndexBuffer(indices);
  73562. };
  73563. Layer.prototype._rebuild = function () {
  73564. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73565. if (vb) {
  73566. vb._rebuild();
  73567. }
  73568. this._createIndexBuffer();
  73569. };
  73570. Layer.prototype.render = function () {
  73571. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  73572. // Check
  73573. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  73574. return;
  73575. var engine = this._scene.getEngine();
  73576. this.onBeforeRenderObservable.notifyObservers(this);
  73577. // Render
  73578. engine.enableEffect(currentEffect);
  73579. engine.setState(false);
  73580. // Texture
  73581. currentEffect.setTexture("textureSampler", this.texture);
  73582. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  73583. // Color
  73584. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  73585. // Scale / offset
  73586. currentEffect.setVector2("offset", this.offset);
  73587. currentEffect.setVector2("scale", this.scale);
  73588. // VBOs
  73589. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73590. // Draw order
  73591. if (!this.alphaTest) {
  73592. engine.setAlphaMode(this.alphaBlendingMode);
  73593. engine.draw(true, 0, 6);
  73594. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73595. }
  73596. else {
  73597. engine.draw(true, 0, 6);
  73598. }
  73599. this.onAfterRenderObservable.notifyObservers(this);
  73600. };
  73601. Layer.prototype.dispose = function () {
  73602. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73603. if (vertexBuffer) {
  73604. vertexBuffer.dispose();
  73605. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73606. }
  73607. if (this._indexBuffer) {
  73608. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73609. this._indexBuffer = null;
  73610. }
  73611. if (this.texture) {
  73612. this.texture.dispose();
  73613. this.texture = null;
  73614. }
  73615. // Remove from scene
  73616. var index = this._scene.layers.indexOf(this);
  73617. this._scene.layers.splice(index, 1);
  73618. // Callback
  73619. this.onDisposeObservable.notifyObservers(this);
  73620. this.onDisposeObservable.clear();
  73621. this.onAfterRenderObservable.clear();
  73622. this.onBeforeRenderObservable.clear();
  73623. };
  73624. return Layer;
  73625. }());
  73626. BABYLON.Layer = Layer;
  73627. })(BABYLON || (BABYLON = {}));
  73628. //# sourceMappingURL=babylon.layer.js.map
  73629. var BABYLON;
  73630. (function (BABYLON) {
  73631. var TextureTools = /** @class */ (function () {
  73632. function TextureTools() {
  73633. }
  73634. /**
  73635. * Uses the GPU to create a copy texture rescaled at a given size
  73636. * @param texture Texture to copy from
  73637. * @param width Desired width
  73638. * @param height Desired height
  73639. * @return Generated texture
  73640. */
  73641. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  73642. if (useBilinearMode === void 0) { useBilinearMode = true; }
  73643. var scene = texture.getScene();
  73644. var engine = scene.getEngine();
  73645. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  73646. rtt.wrapU = texture.wrapU;
  73647. rtt.wrapV = texture.wrapV;
  73648. rtt.uOffset = texture.uOffset;
  73649. rtt.vOffset = texture.vOffset;
  73650. rtt.uScale = texture.uScale;
  73651. rtt.vScale = texture.vScale;
  73652. rtt.uAng = texture.uAng;
  73653. rtt.vAng = texture.vAng;
  73654. rtt.wAng = texture.wAng;
  73655. rtt.coordinatesIndex = texture.coordinatesIndex;
  73656. rtt.level = texture.level;
  73657. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  73658. rtt._texture.isReady = false;
  73659. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73660. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73661. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73662. passPostProcess.getEffect().executeWhenCompiled(function () {
  73663. passPostProcess.onApply = function (effect) {
  73664. effect.setTexture("textureSampler", texture);
  73665. };
  73666. var internalTexture = rtt.getInternalTexture();
  73667. if (internalTexture) {
  73668. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  73669. engine.unBindFramebuffer(internalTexture);
  73670. rtt.disposeFramebufferObjects();
  73671. passPostProcess.dispose();
  73672. internalTexture.isReady = true;
  73673. }
  73674. });
  73675. return rtt;
  73676. };
  73677. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  73678. if (!scene._environmentBRDFTexture) {
  73679. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73680. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73681. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73682. scene._environmentBRDFTexture = texture;
  73683. }
  73684. return scene._environmentBRDFTexture;
  73685. };
  73686. 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=";
  73687. return TextureTools;
  73688. }());
  73689. BABYLON.TextureTools = TextureTools;
  73690. })(BABYLON || (BABYLON = {}));
  73691. //# sourceMappingURL=babylon.textureTools.js.map
  73692. var BABYLON;
  73693. (function (BABYLON) {
  73694. var FramingBehavior = /** @class */ (function () {
  73695. function FramingBehavior() {
  73696. this._mode = FramingBehavior.FitFrustumSidesMode;
  73697. this._radiusScale = 1.0;
  73698. this._positionScale = 0.5;
  73699. this._defaultElevation = 0.3;
  73700. this._elevationReturnTime = 1500;
  73701. this._elevationReturnWaitTime = 1000;
  73702. this._zoomStopsAnimation = false;
  73703. this._framingTime = 1500;
  73704. this._isPointerDown = false;
  73705. this._lastInteractionTime = -Infinity;
  73706. // Framing control
  73707. this._animatables = new Array();
  73708. this._betaIsAnimating = false;
  73709. }
  73710. Object.defineProperty(FramingBehavior.prototype, "name", {
  73711. get: function () {
  73712. return "Framing";
  73713. },
  73714. enumerable: true,
  73715. configurable: true
  73716. });
  73717. Object.defineProperty(FramingBehavior.prototype, "mode", {
  73718. /**
  73719. * Gets current mode used by the behavior.
  73720. */
  73721. get: function () {
  73722. return this._mode;
  73723. },
  73724. /**
  73725. * Sets the current mode used by the behavior
  73726. */
  73727. set: function (mode) {
  73728. this._mode = mode;
  73729. },
  73730. enumerable: true,
  73731. configurable: true
  73732. });
  73733. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  73734. /**
  73735. * Gets the scale applied to the radius
  73736. */
  73737. get: function () {
  73738. return this._radiusScale;
  73739. },
  73740. /**
  73741. * Sets the scale applied to the radius (1 by default)
  73742. */
  73743. set: function (radius) {
  73744. this._radiusScale = radius;
  73745. },
  73746. enumerable: true,
  73747. configurable: true
  73748. });
  73749. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  73750. /**
  73751. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73752. */
  73753. get: function () {
  73754. return this._positionScale;
  73755. },
  73756. /**
  73757. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73758. */
  73759. set: function (scale) {
  73760. this._positionScale = scale;
  73761. },
  73762. enumerable: true,
  73763. configurable: true
  73764. });
  73765. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  73766. /**
  73767. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73768. * behaviour is triggered, in radians.
  73769. */
  73770. get: function () {
  73771. return this._defaultElevation;
  73772. },
  73773. /**
  73774. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73775. * behaviour is triggered, in radians.
  73776. */
  73777. set: function (elevation) {
  73778. this._defaultElevation = elevation;
  73779. },
  73780. enumerable: true,
  73781. configurable: true
  73782. });
  73783. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  73784. /**
  73785. * Gets the time (in milliseconds) taken to return to the default beta position.
  73786. * Negative value indicates camera should not return to default.
  73787. */
  73788. get: function () {
  73789. return this._elevationReturnTime;
  73790. },
  73791. /**
  73792. * Sets the time (in milliseconds) taken to return to the default beta position.
  73793. * Negative value indicates camera should not return to default.
  73794. */
  73795. set: function (speed) {
  73796. this._elevationReturnTime = speed;
  73797. },
  73798. enumerable: true,
  73799. configurable: true
  73800. });
  73801. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  73802. /**
  73803. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73804. */
  73805. get: function () {
  73806. return this._elevationReturnWaitTime;
  73807. },
  73808. /**
  73809. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73810. */
  73811. set: function (time) {
  73812. this._elevationReturnWaitTime = time;
  73813. },
  73814. enumerable: true,
  73815. configurable: true
  73816. });
  73817. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  73818. /**
  73819. * Gets the flag that indicates if user zooming should stop animation.
  73820. */
  73821. get: function () {
  73822. return this._zoomStopsAnimation;
  73823. },
  73824. /**
  73825. * Sets the flag that indicates if user zooming should stop animation.
  73826. */
  73827. set: function (flag) {
  73828. this._zoomStopsAnimation = flag;
  73829. },
  73830. enumerable: true,
  73831. configurable: true
  73832. });
  73833. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  73834. /**
  73835. * Gets the transition time when framing the mesh, in milliseconds
  73836. */
  73837. get: function () {
  73838. return this._framingTime;
  73839. },
  73840. /**
  73841. * Sets the transition time when framing the mesh, in milliseconds
  73842. */
  73843. set: function (time) {
  73844. this._framingTime = time;
  73845. },
  73846. enumerable: true,
  73847. configurable: true
  73848. });
  73849. FramingBehavior.prototype.init = function () {
  73850. // Do notihng
  73851. };
  73852. FramingBehavior.prototype.attach = function (camera) {
  73853. var _this = this;
  73854. this._attachedCamera = camera;
  73855. var scene = this._attachedCamera.getScene();
  73856. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  73857. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73858. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73859. _this._isPointerDown = true;
  73860. return;
  73861. }
  73862. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73863. _this._isPointerDown = false;
  73864. }
  73865. });
  73866. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73867. if (mesh) {
  73868. _this.zoomOnMesh(mesh);
  73869. }
  73870. });
  73871. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73872. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73873. _this._applyUserInteraction();
  73874. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  73875. // back to the default position after a given timeout
  73876. _this._maintainCameraAboveGround();
  73877. });
  73878. };
  73879. FramingBehavior.prototype.detach = function () {
  73880. if (!this._attachedCamera) {
  73881. return;
  73882. }
  73883. var scene = this._attachedCamera.getScene();
  73884. if (this._onPrePointerObservableObserver) {
  73885. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73886. }
  73887. if (this._onAfterCheckInputsObserver) {
  73888. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73889. }
  73890. if (this._onMeshTargetChangedObserver) {
  73891. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73892. }
  73893. this._attachedCamera = null;
  73894. };
  73895. /**
  73896. * Targets the given mesh and updates zoom level accordingly.
  73897. * @param mesh The mesh to target.
  73898. * @param radius Optional. If a cached radius position already exists, overrides default.
  73899. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73900. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73901. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73902. */
  73903. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  73904. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73905. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73906. mesh.computeWorldMatrix(true);
  73907. var boundingBox = mesh.getBoundingInfo().boundingBox;
  73908. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  73909. };
  73910. /**
  73911. * Targets the given mesh and updates zoom level accordingly.
  73912. * @param mesh The mesh to target.
  73913. * @param radius Optional. If a cached radius position already exists, overrides default.
  73914. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73915. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73916. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73917. */
  73918. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  73919. var _this = this;
  73920. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73921. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73922. var zoomTarget;
  73923. if (!this._attachedCamera) {
  73924. return;
  73925. }
  73926. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  73927. var bottom = minimumWorld.y;
  73928. var top = maximumWorld.y;
  73929. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  73930. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  73931. if (focusOnOriginXZ) {
  73932. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  73933. }
  73934. else {
  73935. var centerWorld = minimumWorld.add(radiusWorld);
  73936. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  73937. }
  73938. if (!this._vectorTransition) {
  73939. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  73940. }
  73941. this._betaIsAnimating = true;
  73942. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  73943. if (animatable) {
  73944. this._animatables.push(animatable);
  73945. }
  73946. // sets the radius and lower radius bounds
  73947. // Small delta ensures camera is not always at lower zoom limit.
  73948. var radius = 0;
  73949. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  73950. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73951. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  73952. radius = position;
  73953. }
  73954. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73955. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73956. if (this._attachedCamera.lowerRadiusLimit === null) {
  73957. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  73958. }
  73959. }
  73960. // Set sensibilities
  73961. var extend = maximumWorld.subtract(minimumWorld).length();
  73962. this._attachedCamera.panningSensibility = 5000 / extend;
  73963. this._attachedCamera.wheelPrecision = 100 / radius;
  73964. // transition to new radius
  73965. if (!this._radiusTransition) {
  73966. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73967. }
  73968. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  73969. if (onAnimationEnd) {
  73970. onAnimationEnd();
  73971. }
  73972. if (_this._attachedCamera) {
  73973. _this._attachedCamera.storeState();
  73974. }
  73975. });
  73976. if (animatable) {
  73977. this._animatables.push(animatable);
  73978. }
  73979. };
  73980. /**
  73981. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  73982. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  73983. * frustum width.
  73984. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  73985. * to fully enclose the mesh in the viewing frustum.
  73986. */
  73987. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  73988. var size = maximumWorld.subtract(minimumWorld);
  73989. var boxVectorGlobalDiagonal = size.length();
  73990. var frustumSlope = this._getFrustumSlope();
  73991. // Formula for setting distance
  73992. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  73993. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  73994. // Horizon distance
  73995. var radius = radiusWithoutFraming * this._radiusScale;
  73996. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  73997. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  73998. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  73999. var camera = this._attachedCamera;
  74000. if (!camera) {
  74001. return 0;
  74002. }
  74003. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  74004. // Don't exceed the requested limit
  74005. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  74006. }
  74007. // Don't exceed the upper radius limit
  74008. if (camera.upperRadiusLimit) {
  74009. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  74010. }
  74011. return distance;
  74012. };
  74013. /**
  74014. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  74015. * is automatically returned to its default position (expected to be above ground plane).
  74016. */
  74017. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  74018. var _this = this;
  74019. if (this._elevationReturnTime < 0) {
  74020. return;
  74021. }
  74022. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  74023. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  74024. var limitBeta = Math.PI * 0.5;
  74025. // Bring the camera back up if below the ground plane
  74026. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  74027. this._betaIsAnimating = true;
  74028. //Transition to new position
  74029. this.stopAllAnimations();
  74030. if (!this._betaTransition) {
  74031. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  74032. }
  74033. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  74034. _this._clearAnimationLocks();
  74035. _this.stopAllAnimations();
  74036. });
  74037. if (animatabe) {
  74038. this._animatables.push(animatabe);
  74039. }
  74040. }
  74041. };
  74042. /**
  74043. * Returns the frustum slope based on the canvas ratio and camera FOV
  74044. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  74045. */
  74046. FramingBehavior.prototype._getFrustumSlope = function () {
  74047. // Calculate the viewport ratio
  74048. // Aspect Ratio is Height/Width.
  74049. var camera = this._attachedCamera;
  74050. if (!camera) {
  74051. return BABYLON.Vector2.Zero();
  74052. }
  74053. var engine = camera.getScene().getEngine();
  74054. var aspectRatio = engine.getAspectRatio(camera);
  74055. // Camera FOV is the vertical field of view (top-bottom) in radians.
  74056. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  74057. var frustumSlopeY = Math.tan(camera.fov / 2);
  74058. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  74059. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  74060. // along the forward vector.
  74061. var frustumSlopeX = frustumSlopeY * aspectRatio;
  74062. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  74063. };
  74064. /**
  74065. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  74066. */
  74067. FramingBehavior.prototype._clearAnimationLocks = function () {
  74068. this._betaIsAnimating = false;
  74069. };
  74070. /**
  74071. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74072. */
  74073. FramingBehavior.prototype._applyUserInteraction = function () {
  74074. if (this.isUserIsMoving) {
  74075. this._lastInteractionTime = BABYLON.Tools.Now;
  74076. this.stopAllAnimations();
  74077. this._clearAnimationLocks();
  74078. }
  74079. };
  74080. /**
  74081. * Stops and removes all animations that have been applied to the camera
  74082. */
  74083. FramingBehavior.prototype.stopAllAnimations = function () {
  74084. if (this._attachedCamera) {
  74085. this._attachedCamera.animations = [];
  74086. }
  74087. while (this._animatables.length) {
  74088. if (this._animatables[0]) {
  74089. this._animatables[0].onAnimationEnd = null;
  74090. this._animatables[0].stop();
  74091. }
  74092. this._animatables.shift();
  74093. }
  74094. };
  74095. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  74096. /**
  74097. * Gets a value indicating if the user is moving the camera
  74098. */
  74099. get: function () {
  74100. if (!this._attachedCamera) {
  74101. return false;
  74102. }
  74103. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74104. this._attachedCamera.inertialBetaOffset !== 0 ||
  74105. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74106. this._attachedCamera.inertialPanningX !== 0 ||
  74107. this._attachedCamera.inertialPanningY !== 0 ||
  74108. this._isPointerDown;
  74109. },
  74110. enumerable: true,
  74111. configurable: true
  74112. });
  74113. /**
  74114. * The easing function used by animations
  74115. */
  74116. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  74117. /**
  74118. * The easing mode used by animations
  74119. */
  74120. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  74121. // Statics
  74122. /**
  74123. * The camera can move all the way towards the mesh.
  74124. */
  74125. FramingBehavior.IgnoreBoundsSizeMode = 0;
  74126. /**
  74127. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  74128. */
  74129. FramingBehavior.FitFrustumSidesMode = 1;
  74130. return FramingBehavior;
  74131. }());
  74132. BABYLON.FramingBehavior = FramingBehavior;
  74133. })(BABYLON || (BABYLON = {}));
  74134. //# sourceMappingURL=babylon.framingBehavior.js.map
  74135. var BABYLON;
  74136. (function (BABYLON) {
  74137. /**
  74138. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  74139. */
  74140. var BouncingBehavior = /** @class */ (function () {
  74141. function BouncingBehavior() {
  74142. /**
  74143. * The duration of the animation, in milliseconds
  74144. */
  74145. this.transitionDuration = 450;
  74146. /**
  74147. * Length of the distance animated by the transition when lower radius is reached
  74148. */
  74149. this.lowerRadiusTransitionRange = 2;
  74150. /**
  74151. * Length of the distance animated by the transition when upper radius is reached
  74152. */
  74153. this.upperRadiusTransitionRange = -2;
  74154. this._autoTransitionRange = false;
  74155. // Animations
  74156. this._radiusIsAnimating = false;
  74157. this._radiusBounceTransition = null;
  74158. this._animatables = new Array();
  74159. }
  74160. Object.defineProperty(BouncingBehavior.prototype, "name", {
  74161. get: function () {
  74162. return "Bouncing";
  74163. },
  74164. enumerable: true,
  74165. configurable: true
  74166. });
  74167. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  74168. /**
  74169. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  74170. */
  74171. get: function () {
  74172. return this._autoTransitionRange;
  74173. },
  74174. /**
  74175. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  74176. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  74177. */
  74178. set: function (value) {
  74179. var _this = this;
  74180. if (this._autoTransitionRange === value) {
  74181. return;
  74182. }
  74183. this._autoTransitionRange = value;
  74184. var camera = this._attachedCamera;
  74185. if (!camera) {
  74186. return;
  74187. }
  74188. if (value) {
  74189. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  74190. if (!mesh) {
  74191. return;
  74192. }
  74193. mesh.computeWorldMatrix(true);
  74194. var diagonal = mesh.getBoundingInfo().diagonalLength;
  74195. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  74196. _this.upperRadiusTransitionRange = diagonal * 0.05;
  74197. });
  74198. }
  74199. else if (this._onMeshTargetChangedObserver) {
  74200. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74201. }
  74202. },
  74203. enumerable: true,
  74204. configurable: true
  74205. });
  74206. BouncingBehavior.prototype.init = function () {
  74207. // Do notihng
  74208. };
  74209. BouncingBehavior.prototype.attach = function (camera) {
  74210. var _this = this;
  74211. this._attachedCamera = camera;
  74212. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74213. if (!_this._attachedCamera) {
  74214. return;
  74215. }
  74216. // Add the bounce animation to the lower radius limit
  74217. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  74218. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  74219. }
  74220. // Add the bounce animation to the upper radius limit
  74221. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  74222. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  74223. }
  74224. });
  74225. };
  74226. BouncingBehavior.prototype.detach = function () {
  74227. if (!this._attachedCamera) {
  74228. return;
  74229. }
  74230. if (this._onAfterCheckInputsObserver) {
  74231. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74232. }
  74233. if (this._onMeshTargetChangedObserver) {
  74234. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74235. }
  74236. this._attachedCamera = null;
  74237. };
  74238. /**
  74239. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  74240. * @param radiusLimit The limit to check against.
  74241. * @return Bool to indicate if at limit.
  74242. */
  74243. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  74244. if (!this._attachedCamera) {
  74245. return false;
  74246. }
  74247. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  74248. return true;
  74249. }
  74250. return false;
  74251. };
  74252. /**
  74253. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  74254. * @param radiusDelta The delta by which to animate to. Can be negative.
  74255. */
  74256. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  74257. var _this = this;
  74258. if (!this._attachedCamera) {
  74259. return;
  74260. }
  74261. if (!this._radiusBounceTransition) {
  74262. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  74263. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  74264. }
  74265. // Prevent zoom until bounce has completed
  74266. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  74267. this._attachedCamera.wheelPrecision = Infinity;
  74268. this._attachedCamera.inertialRadiusOffset = 0;
  74269. // Animate to the radius limit
  74270. this.stopAllAnimations();
  74271. this._radiusIsAnimating = true;
  74272. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  74273. if (animatable) {
  74274. this._animatables.push(animatable);
  74275. }
  74276. };
  74277. /**
  74278. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  74279. */
  74280. BouncingBehavior.prototype._clearAnimationLocks = function () {
  74281. this._radiusIsAnimating = false;
  74282. if (this._attachedCamera) {
  74283. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  74284. }
  74285. };
  74286. /**
  74287. * Stops and removes all animations that have been applied to the camera
  74288. */
  74289. BouncingBehavior.prototype.stopAllAnimations = function () {
  74290. if (this._attachedCamera) {
  74291. this._attachedCamera.animations = [];
  74292. }
  74293. while (this._animatables.length) {
  74294. this._animatables[0].onAnimationEnd = null;
  74295. this._animatables[0].stop();
  74296. this._animatables.shift();
  74297. }
  74298. };
  74299. /**
  74300. * The easing function used by animations
  74301. */
  74302. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  74303. /**
  74304. * The easing mode used by animations
  74305. */
  74306. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  74307. return BouncingBehavior;
  74308. }());
  74309. BABYLON.BouncingBehavior = BouncingBehavior;
  74310. })(BABYLON || (BABYLON = {}));
  74311. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  74312. var BABYLON;
  74313. (function (BABYLON) {
  74314. var AutoRotationBehavior = /** @class */ (function () {
  74315. function AutoRotationBehavior() {
  74316. this._zoomStopsAnimation = false;
  74317. this._idleRotationSpeed = 0.05;
  74318. this._idleRotationWaitTime = 2000;
  74319. this._idleRotationSpinupTime = 2000;
  74320. this._isPointerDown = false;
  74321. this._lastFrameTime = null;
  74322. this._lastInteractionTime = -Infinity;
  74323. this._cameraRotationSpeed = 0;
  74324. this._lastFrameRadius = 0;
  74325. }
  74326. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  74327. get: function () {
  74328. return "AutoRotation";
  74329. },
  74330. enumerable: true,
  74331. configurable: true
  74332. });
  74333. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  74334. /**
  74335. * Gets the flag that indicates if user zooming should stop animation.
  74336. */
  74337. get: function () {
  74338. return this._zoomStopsAnimation;
  74339. },
  74340. /**
  74341. * Sets the flag that indicates if user zooming should stop animation.
  74342. */
  74343. set: function (flag) {
  74344. this._zoomStopsAnimation = flag;
  74345. },
  74346. enumerable: true,
  74347. configurable: true
  74348. });
  74349. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  74350. /**
  74351. * Gets the default speed at which the camera rotates around the model.
  74352. */
  74353. get: function () {
  74354. return this._idleRotationSpeed;
  74355. },
  74356. /**
  74357. * Sets the default speed at which the camera rotates around the model.
  74358. */
  74359. set: function (speed) {
  74360. this._idleRotationSpeed = speed;
  74361. },
  74362. enumerable: true,
  74363. configurable: true
  74364. });
  74365. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  74366. /**
  74367. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  74368. */
  74369. get: function () {
  74370. return this._idleRotationWaitTime;
  74371. },
  74372. /**
  74373. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  74374. */
  74375. set: function (time) {
  74376. this._idleRotationWaitTime = time;
  74377. },
  74378. enumerable: true,
  74379. configurable: true
  74380. });
  74381. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  74382. /**
  74383. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74384. */
  74385. get: function () {
  74386. return this._idleRotationSpinupTime;
  74387. },
  74388. /**
  74389. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74390. */
  74391. set: function (time) {
  74392. this._idleRotationSpinupTime = time;
  74393. },
  74394. enumerable: true,
  74395. configurable: true
  74396. });
  74397. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  74398. /**
  74399. * Gets a value indicating if the camera is currently rotating because of this behavior
  74400. */
  74401. get: function () {
  74402. return Math.abs(this._cameraRotationSpeed) > 0;
  74403. },
  74404. enumerable: true,
  74405. configurable: true
  74406. });
  74407. AutoRotationBehavior.prototype.init = function () {
  74408. // Do notihng
  74409. };
  74410. AutoRotationBehavior.prototype.attach = function (camera) {
  74411. var _this = this;
  74412. this._attachedCamera = camera;
  74413. var scene = this._attachedCamera.getScene();
  74414. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74415. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74416. _this._isPointerDown = true;
  74417. return;
  74418. }
  74419. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74420. _this._isPointerDown = false;
  74421. }
  74422. });
  74423. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74424. var now = BABYLON.Tools.Now;
  74425. var dt = 0;
  74426. if (_this._lastFrameTime != null) {
  74427. dt = now - _this._lastFrameTime;
  74428. }
  74429. _this._lastFrameTime = now;
  74430. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74431. _this._applyUserInteraction();
  74432. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  74433. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  74434. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  74435. // Step camera rotation by rotation speed
  74436. if (_this._attachedCamera) {
  74437. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  74438. }
  74439. });
  74440. };
  74441. AutoRotationBehavior.prototype.detach = function () {
  74442. if (!this._attachedCamera) {
  74443. return;
  74444. }
  74445. var scene = this._attachedCamera.getScene();
  74446. if (this._onPrePointerObservableObserver) {
  74447. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74448. }
  74449. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74450. this._attachedCamera = null;
  74451. };
  74452. /**
  74453. * Returns true if user is scrolling.
  74454. * @return true if user is scrolling.
  74455. */
  74456. AutoRotationBehavior.prototype._userIsZooming = function () {
  74457. if (!this._attachedCamera) {
  74458. return false;
  74459. }
  74460. return this._attachedCamera.inertialRadiusOffset !== 0;
  74461. };
  74462. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  74463. if (!this._attachedCamera) {
  74464. return false;
  74465. }
  74466. var zoomHasHitLimit = false;
  74467. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  74468. zoomHasHitLimit = true;
  74469. }
  74470. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  74471. this._lastFrameRadius = this._attachedCamera.radius;
  74472. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  74473. };
  74474. /**
  74475. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74476. */
  74477. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  74478. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  74479. this._lastInteractionTime = BABYLON.Tools.Now;
  74480. }
  74481. };
  74482. // Tools
  74483. AutoRotationBehavior.prototype._userIsMoving = function () {
  74484. if (!this._attachedCamera) {
  74485. return false;
  74486. }
  74487. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74488. this._attachedCamera.inertialBetaOffset !== 0 ||
  74489. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74490. this._attachedCamera.inertialPanningX !== 0 ||
  74491. this._attachedCamera.inertialPanningY !== 0 ||
  74492. this._isPointerDown;
  74493. };
  74494. return AutoRotationBehavior;
  74495. }());
  74496. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  74497. })(BABYLON || (BABYLON = {}));
  74498. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  74499. var BABYLON;
  74500. (function (BABYLON) {
  74501. /**
  74502. * This class can be used to get instrumentation data from a Babylon engine
  74503. */
  74504. var EngineInstrumentation = /** @class */ (function () {
  74505. function EngineInstrumentation(engine) {
  74506. this.engine = engine;
  74507. this._captureGPUFrameTime = false;
  74508. this._gpuFrameTime = new BABYLON.PerfCounter();
  74509. this._captureShaderCompilationTime = false;
  74510. this._shaderCompilationTime = new BABYLON.PerfCounter();
  74511. // Observers
  74512. this._onBeginFrameObserver = null;
  74513. this._onEndFrameObserver = null;
  74514. this._onBeforeShaderCompilationObserver = null;
  74515. this._onAfterShaderCompilationObserver = null;
  74516. }
  74517. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  74518. // Properties
  74519. /**
  74520. * Gets the perf counter used for GPU frame time
  74521. */
  74522. get: function () {
  74523. return this._gpuFrameTime;
  74524. },
  74525. enumerable: true,
  74526. configurable: true
  74527. });
  74528. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  74529. /**
  74530. * Gets the GPU frame time capture status
  74531. */
  74532. get: function () {
  74533. return this._captureGPUFrameTime;
  74534. },
  74535. /**
  74536. * Enable or disable the GPU frame time capture
  74537. */
  74538. set: function (value) {
  74539. var _this = this;
  74540. if (value === this._captureGPUFrameTime) {
  74541. return;
  74542. }
  74543. this._captureGPUFrameTime = value;
  74544. if (value) {
  74545. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  74546. if (!_this._gpuFrameTimeToken) {
  74547. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  74548. }
  74549. });
  74550. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  74551. if (!_this._gpuFrameTimeToken) {
  74552. return;
  74553. }
  74554. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  74555. if (time > -1) {
  74556. _this._gpuFrameTimeToken = null;
  74557. _this._gpuFrameTime.fetchNewFrame();
  74558. _this._gpuFrameTime.addCount(time, true);
  74559. }
  74560. });
  74561. }
  74562. else {
  74563. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74564. this._onBeginFrameObserver = null;
  74565. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74566. this._onEndFrameObserver = null;
  74567. }
  74568. },
  74569. enumerable: true,
  74570. configurable: true
  74571. });
  74572. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  74573. /**
  74574. * Gets the perf counter used for shader compilation time
  74575. */
  74576. get: function () {
  74577. return this._shaderCompilationTime;
  74578. },
  74579. enumerable: true,
  74580. configurable: true
  74581. });
  74582. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  74583. /**
  74584. * Gets the shader compilation time capture status
  74585. */
  74586. get: function () {
  74587. return this._captureShaderCompilationTime;
  74588. },
  74589. /**
  74590. * Enable or disable the shader compilation time capture
  74591. */
  74592. set: function (value) {
  74593. var _this = this;
  74594. if (value === this._captureShaderCompilationTime) {
  74595. return;
  74596. }
  74597. this._captureShaderCompilationTime = value;
  74598. if (value) {
  74599. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  74600. _this._shaderCompilationTime.fetchNewFrame();
  74601. _this._shaderCompilationTime.beginMonitoring();
  74602. });
  74603. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  74604. _this._shaderCompilationTime.endMonitoring();
  74605. });
  74606. }
  74607. else {
  74608. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74609. this._onBeforeShaderCompilationObserver = null;
  74610. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74611. this._onAfterShaderCompilationObserver = null;
  74612. }
  74613. },
  74614. enumerable: true,
  74615. configurable: true
  74616. });
  74617. EngineInstrumentation.prototype.dispose = function () {
  74618. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74619. this._onBeginFrameObserver = null;
  74620. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74621. this._onEndFrameObserver = null;
  74622. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74623. this._onBeforeShaderCompilationObserver = null;
  74624. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74625. this._onAfterShaderCompilationObserver = null;
  74626. this.engine = null;
  74627. };
  74628. return EngineInstrumentation;
  74629. }());
  74630. BABYLON.EngineInstrumentation = EngineInstrumentation;
  74631. })(BABYLON || (BABYLON = {}));
  74632. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  74633. var BABYLON;
  74634. (function (BABYLON) {
  74635. /**
  74636. * This class can be used to get instrumentation data from a Babylon engine
  74637. */
  74638. var SceneInstrumentation = /** @class */ (function () {
  74639. function SceneInstrumentation(scene) {
  74640. var _this = this;
  74641. this.scene = scene;
  74642. this._captureActiveMeshesEvaluationTime = false;
  74643. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  74644. this._captureRenderTargetsRenderTime = false;
  74645. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  74646. this._captureFrameTime = false;
  74647. this._frameTime = new BABYLON.PerfCounter();
  74648. this._captureRenderTime = false;
  74649. this._renderTime = new BABYLON.PerfCounter();
  74650. this._captureInterFrameTime = false;
  74651. this._interFrameTime = new BABYLON.PerfCounter();
  74652. this._captureParticlesRenderTime = false;
  74653. this._particlesRenderTime = new BABYLON.PerfCounter();
  74654. this._captureSpritesRenderTime = false;
  74655. this._spritesRenderTime = new BABYLON.PerfCounter();
  74656. this._capturePhysicsTime = false;
  74657. this._physicsTime = new BABYLON.PerfCounter();
  74658. this._captureAnimationsTime = false;
  74659. this._animationsTime = new BABYLON.PerfCounter();
  74660. // Observers
  74661. this._onBeforeActiveMeshesEvaluationObserver = null;
  74662. this._onAfterActiveMeshesEvaluationObserver = null;
  74663. this._onBeforeRenderTargetsRenderObserver = null;
  74664. this._onAfterRenderTargetsRenderObserver = null;
  74665. this._onAfterRenderObserver = null;
  74666. this._onBeforeDrawPhaseObserver = null;
  74667. this._onAfterDrawPhaseObserver = null;
  74668. this._onBeforeAnimationsObserver = null;
  74669. this._onBeforeParticlesRenderingObserver = null;
  74670. this._onAfterParticlesRenderingObserver = null;
  74671. this._onBeforeSpritesRenderingObserver = null;
  74672. this._onAfterSpritesRenderingObserver = null;
  74673. this._onBeforePhysicsObserver = null;
  74674. this._onAfterPhysicsObserver = null;
  74675. this._onAfterAnimationsObserver = null;
  74676. // Before render
  74677. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  74678. if (_this._captureActiveMeshesEvaluationTime) {
  74679. _this._activeMeshesEvaluationTime.fetchNewFrame();
  74680. }
  74681. if (_this._captureRenderTargetsRenderTime) {
  74682. _this._renderTargetsRenderTime.fetchNewFrame();
  74683. }
  74684. if (_this._captureFrameTime) {
  74685. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  74686. _this._frameTime.beginMonitoring();
  74687. }
  74688. if (_this._captureInterFrameTime) {
  74689. _this._interFrameTime.endMonitoring();
  74690. }
  74691. if (_this._captureParticlesRenderTime) {
  74692. _this._particlesRenderTime.fetchNewFrame();
  74693. }
  74694. if (_this._captureSpritesRenderTime) {
  74695. _this._spritesRenderTime.fetchNewFrame();
  74696. }
  74697. if (_this._captureAnimationsTime) {
  74698. _this._animationsTime.beginMonitoring();
  74699. }
  74700. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  74701. });
  74702. // After render
  74703. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  74704. if (_this._captureFrameTime) {
  74705. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  74706. _this._frameTime.endMonitoring();
  74707. }
  74708. if (_this._captureRenderTime) {
  74709. _this._renderTime.endMonitoring(false);
  74710. }
  74711. if (_this._captureInterFrameTime) {
  74712. _this._interFrameTime.beginMonitoring();
  74713. }
  74714. });
  74715. }
  74716. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  74717. // Properties
  74718. /**
  74719. * Gets the perf counter used for active meshes evaluation time
  74720. */
  74721. get: function () {
  74722. return this._activeMeshesEvaluationTime;
  74723. },
  74724. enumerable: true,
  74725. configurable: true
  74726. });
  74727. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  74728. /**
  74729. * Gets the active meshes evaluation time capture status
  74730. */
  74731. get: function () {
  74732. return this._captureActiveMeshesEvaluationTime;
  74733. },
  74734. /**
  74735. * Enable or disable the active meshes evaluation time capture
  74736. */
  74737. set: function (value) {
  74738. var _this = this;
  74739. if (value === this._captureActiveMeshesEvaluationTime) {
  74740. return;
  74741. }
  74742. this._captureActiveMeshesEvaluationTime = value;
  74743. if (value) {
  74744. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  74745. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  74746. _this._activeMeshesEvaluationTime.beginMonitoring();
  74747. });
  74748. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  74749. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  74750. _this._activeMeshesEvaluationTime.endMonitoring();
  74751. });
  74752. }
  74753. else {
  74754. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74755. this._onBeforeActiveMeshesEvaluationObserver = null;
  74756. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74757. this._onAfterActiveMeshesEvaluationObserver = null;
  74758. }
  74759. },
  74760. enumerable: true,
  74761. configurable: true
  74762. });
  74763. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  74764. /**
  74765. * Gets the perf counter used for render targets render time
  74766. */
  74767. get: function () {
  74768. return this._renderTargetsRenderTime;
  74769. },
  74770. enumerable: true,
  74771. configurable: true
  74772. });
  74773. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  74774. /**
  74775. * Gets the render targets render time capture status
  74776. */
  74777. get: function () {
  74778. return this._captureRenderTargetsRenderTime;
  74779. },
  74780. /**
  74781. * Enable or disable the render targets render time capture
  74782. */
  74783. set: function (value) {
  74784. var _this = this;
  74785. if (value === this._captureRenderTargetsRenderTime) {
  74786. return;
  74787. }
  74788. this._captureRenderTargetsRenderTime = value;
  74789. if (value) {
  74790. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  74791. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  74792. _this._renderTargetsRenderTime.beginMonitoring();
  74793. });
  74794. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  74795. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  74796. _this._renderTargetsRenderTime.endMonitoring(false);
  74797. });
  74798. }
  74799. else {
  74800. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74801. this._onBeforeRenderTargetsRenderObserver = null;
  74802. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74803. this._onAfterRenderTargetsRenderObserver = null;
  74804. }
  74805. },
  74806. enumerable: true,
  74807. configurable: true
  74808. });
  74809. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  74810. /**
  74811. * Gets the perf counter used for particles render time
  74812. */
  74813. get: function () {
  74814. return this._particlesRenderTime;
  74815. },
  74816. enumerable: true,
  74817. configurable: true
  74818. });
  74819. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  74820. /**
  74821. * Gets the particles render time capture status
  74822. */
  74823. get: function () {
  74824. return this._captureParticlesRenderTime;
  74825. },
  74826. /**
  74827. * Enable or disable the particles render time capture
  74828. */
  74829. set: function (value) {
  74830. var _this = this;
  74831. if (value === this._captureParticlesRenderTime) {
  74832. return;
  74833. }
  74834. this._captureParticlesRenderTime = value;
  74835. if (value) {
  74836. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  74837. BABYLON.Tools.StartPerformanceCounter("Particles");
  74838. _this._particlesRenderTime.beginMonitoring();
  74839. });
  74840. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  74841. BABYLON.Tools.EndPerformanceCounter("Particles");
  74842. _this._particlesRenderTime.endMonitoring(false);
  74843. });
  74844. }
  74845. else {
  74846. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  74847. this._onBeforeParticlesRenderingObserver = null;
  74848. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  74849. this._onAfterParticlesRenderingObserver = null;
  74850. }
  74851. },
  74852. enumerable: true,
  74853. configurable: true
  74854. });
  74855. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  74856. /**
  74857. * Gets the perf counter used for sprites render time
  74858. */
  74859. get: function () {
  74860. return this._spritesRenderTime;
  74861. },
  74862. enumerable: true,
  74863. configurable: true
  74864. });
  74865. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  74866. /**
  74867. * Gets the sprites render time capture status
  74868. */
  74869. get: function () {
  74870. return this._captureSpritesRenderTime;
  74871. },
  74872. /**
  74873. * Enable or disable the sprites render time capture
  74874. */
  74875. set: function (value) {
  74876. var _this = this;
  74877. if (value === this._captureSpritesRenderTime) {
  74878. return;
  74879. }
  74880. this._captureSpritesRenderTime = value;
  74881. if (value) {
  74882. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  74883. BABYLON.Tools.StartPerformanceCounter("Sprites");
  74884. _this._spritesRenderTime.beginMonitoring();
  74885. });
  74886. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  74887. BABYLON.Tools.EndPerformanceCounter("Sprites");
  74888. _this._spritesRenderTime.endMonitoring(false);
  74889. });
  74890. }
  74891. else {
  74892. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  74893. this._onBeforeSpritesRenderingObserver = null;
  74894. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  74895. this._onAfterSpritesRenderingObserver = null;
  74896. }
  74897. },
  74898. enumerable: true,
  74899. configurable: true
  74900. });
  74901. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  74902. /**
  74903. * Gets the perf counter used for physics time
  74904. */
  74905. get: function () {
  74906. return this._physicsTime;
  74907. },
  74908. enumerable: true,
  74909. configurable: true
  74910. });
  74911. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  74912. /**
  74913. * Gets the physics time capture status
  74914. */
  74915. get: function () {
  74916. return this._capturePhysicsTime;
  74917. },
  74918. /**
  74919. * Enable or disable the physics time capture
  74920. */
  74921. set: function (value) {
  74922. var _this = this;
  74923. if (value === this._capturePhysicsTime) {
  74924. return;
  74925. }
  74926. this._capturePhysicsTime = value;
  74927. if (value) {
  74928. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  74929. BABYLON.Tools.StartPerformanceCounter("Physics");
  74930. _this._physicsTime.beginMonitoring();
  74931. });
  74932. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  74933. BABYLON.Tools.EndPerformanceCounter("Physics");
  74934. _this._physicsTime.endMonitoring();
  74935. });
  74936. }
  74937. else {
  74938. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  74939. this._onBeforePhysicsObserver = null;
  74940. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  74941. this._onAfterPhysicsObserver = null;
  74942. }
  74943. },
  74944. enumerable: true,
  74945. configurable: true
  74946. });
  74947. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  74948. /**
  74949. * Gets the perf counter used for animations time
  74950. */
  74951. get: function () {
  74952. return this._animationsTime;
  74953. },
  74954. enumerable: true,
  74955. configurable: true
  74956. });
  74957. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  74958. /**
  74959. * Gets the animations time capture status
  74960. */
  74961. get: function () {
  74962. return this._captureAnimationsTime;
  74963. },
  74964. /**
  74965. * Enable or disable the animations time capture
  74966. */
  74967. set: function (value) {
  74968. var _this = this;
  74969. if (value === this._captureAnimationsTime) {
  74970. return;
  74971. }
  74972. this._captureAnimationsTime = value;
  74973. if (value) {
  74974. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  74975. _this._animationsTime.endMonitoring();
  74976. });
  74977. }
  74978. else {
  74979. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  74980. this._onAfterAnimationsObserver = null;
  74981. }
  74982. },
  74983. enumerable: true,
  74984. configurable: true
  74985. });
  74986. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  74987. /**
  74988. * Gets the perf counter used for frame time capture
  74989. */
  74990. get: function () {
  74991. return this._frameTime;
  74992. },
  74993. enumerable: true,
  74994. configurable: true
  74995. });
  74996. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  74997. /**
  74998. * Gets the frame time capture status
  74999. */
  75000. get: function () {
  75001. return this._captureFrameTime;
  75002. },
  75003. /**
  75004. * Enable or disable the frame time capture
  75005. */
  75006. set: function (value) {
  75007. this._captureFrameTime = value;
  75008. },
  75009. enumerable: true,
  75010. configurable: true
  75011. });
  75012. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  75013. /**
  75014. * Gets the perf counter used for inter-frames time capture
  75015. */
  75016. get: function () {
  75017. return this._interFrameTime;
  75018. },
  75019. enumerable: true,
  75020. configurable: true
  75021. });
  75022. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  75023. /**
  75024. * Gets the inter-frames time capture status
  75025. */
  75026. get: function () {
  75027. return this._captureInterFrameTime;
  75028. },
  75029. /**
  75030. * Enable or disable the inter-frames time capture
  75031. */
  75032. set: function (value) {
  75033. this._captureInterFrameTime = value;
  75034. },
  75035. enumerable: true,
  75036. configurable: true
  75037. });
  75038. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  75039. /**
  75040. * Gets the perf counter used for render time capture
  75041. */
  75042. get: function () {
  75043. return this._renderTime;
  75044. },
  75045. enumerable: true,
  75046. configurable: true
  75047. });
  75048. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  75049. /**
  75050. * Gets the render time capture status
  75051. */
  75052. get: function () {
  75053. return this._captureRenderTime;
  75054. },
  75055. /**
  75056. * Enable or disable the render time capture
  75057. */
  75058. set: function (value) {
  75059. var _this = this;
  75060. if (value === this._captureRenderTime) {
  75061. return;
  75062. }
  75063. this._captureRenderTime = value;
  75064. if (value) {
  75065. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  75066. _this._renderTime.beginMonitoring();
  75067. BABYLON.Tools.StartPerformanceCounter("Main render");
  75068. });
  75069. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  75070. _this._renderTime.endMonitoring(false);
  75071. BABYLON.Tools.EndPerformanceCounter("Main render");
  75072. });
  75073. }
  75074. else {
  75075. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  75076. this._onBeforeDrawPhaseObserver = null;
  75077. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  75078. this._onAfterDrawPhaseObserver = null;
  75079. }
  75080. },
  75081. enumerable: true,
  75082. configurable: true
  75083. });
  75084. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  75085. /**
  75086. * Gets the perf counter used for frame time capture
  75087. */
  75088. get: function () {
  75089. return this.scene.getEngine()._drawCalls;
  75090. },
  75091. enumerable: true,
  75092. configurable: true
  75093. });
  75094. SceneInstrumentation.prototype.dispose = function () {
  75095. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75096. this._onAfterRenderObserver = null;
  75097. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  75098. this._onBeforeActiveMeshesEvaluationObserver = null;
  75099. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  75100. this._onAfterActiveMeshesEvaluationObserver = null;
  75101. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  75102. this._onBeforeRenderTargetsRenderObserver = null;
  75103. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  75104. this._onAfterRenderTargetsRenderObserver = null;
  75105. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  75106. this._onBeforeAnimationsObserver = null;
  75107. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  75108. this._onBeforeParticlesRenderingObserver = null;
  75109. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  75110. this._onAfterParticlesRenderingObserver = null;
  75111. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  75112. this._onBeforeSpritesRenderingObserver = null;
  75113. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  75114. this._onAfterSpritesRenderingObserver = null;
  75115. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  75116. this._onBeforeDrawPhaseObserver = null;
  75117. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  75118. this._onAfterDrawPhaseObserver = null;
  75119. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  75120. this._onBeforePhysicsObserver = null;
  75121. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  75122. this._onAfterPhysicsObserver = null;
  75123. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  75124. this._onAfterAnimationsObserver = null;
  75125. this.scene = null;
  75126. };
  75127. return SceneInstrumentation;
  75128. }());
  75129. BABYLON.SceneInstrumentation = SceneInstrumentation;
  75130. })(BABYLON || (BABYLON = {}));
  75131. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  75132. var BABYLON;
  75133. (function (BABYLON) {
  75134. var _TimeToken = /** @class */ (function () {
  75135. function _TimeToken() {
  75136. this._timeElapsedQueryEnded = false;
  75137. }
  75138. return _TimeToken;
  75139. }());
  75140. BABYLON._TimeToken = _TimeToken;
  75141. })(BABYLON || (BABYLON = {}));
  75142. //# sourceMappingURL=babylon.timeToken.js.map
  75143. var BABYLON;
  75144. (function (BABYLON) {
  75145. /**
  75146. * Background material defines definition.
  75147. */
  75148. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  75149. __extends(BackgroundMaterialDefines, _super);
  75150. /**
  75151. * Constructor of the defines.
  75152. */
  75153. function BackgroundMaterialDefines() {
  75154. var _this = _super.call(this) || this;
  75155. /**
  75156. * True if the diffuse texture is in use.
  75157. */
  75158. _this.DIFFUSE = false;
  75159. /**
  75160. * The direct UV channel to use.
  75161. */
  75162. _this.DIFFUSEDIRECTUV = 0;
  75163. /**
  75164. * True if the diffuse texture is in gamma space.
  75165. */
  75166. _this.GAMMADIFFUSE = false;
  75167. /**
  75168. * True if the diffuse texture has opacity in the alpha channel.
  75169. */
  75170. _this.DIFFUSEHASALPHA = false;
  75171. /**
  75172. * True if you want the material to fade to transparent at grazing angle.
  75173. */
  75174. _this.OPACITYFRESNEL = false;
  75175. /**
  75176. * True if an extra blur needs to be added in the reflection.
  75177. */
  75178. _this.REFLECTIONBLUR = false;
  75179. /**
  75180. * True if you want the material to fade to reflection at grazing angle.
  75181. */
  75182. _this.REFLECTIONFRESNEL = false;
  75183. /**
  75184. * True if you want the material to falloff as far as you move away from the scene center.
  75185. */
  75186. _this.REFLECTIONFALLOFF = false;
  75187. /**
  75188. * False if the current Webgl implementation does not support the texture lod extension.
  75189. */
  75190. _this.TEXTURELODSUPPORT = false;
  75191. /**
  75192. * True to ensure the data are premultiplied.
  75193. */
  75194. _this.PREMULTIPLYALPHA = false;
  75195. /**
  75196. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  75197. */
  75198. _this.USERGBCOLOR = false;
  75199. // Image Processing Configuration.
  75200. _this.IMAGEPROCESSING = false;
  75201. _this.VIGNETTE = false;
  75202. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  75203. _this.VIGNETTEBLENDMODEOPAQUE = false;
  75204. _this.TONEMAPPING = false;
  75205. _this.CONTRAST = false;
  75206. _this.COLORCURVES = false;
  75207. _this.COLORGRADING = false;
  75208. _this.COLORGRADING3D = false;
  75209. _this.SAMPLER3DGREENDEPTH = false;
  75210. _this.SAMPLER3DBGRMAP = false;
  75211. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  75212. _this.EXPOSURE = false;
  75213. // Reflection.
  75214. _this.REFLECTION = false;
  75215. _this.REFLECTIONMAP_3D = false;
  75216. _this.REFLECTIONMAP_SPHERICAL = false;
  75217. _this.REFLECTIONMAP_PLANAR = false;
  75218. _this.REFLECTIONMAP_CUBIC = false;
  75219. _this.REFLECTIONMAP_PROJECTION = false;
  75220. _this.REFLECTIONMAP_SKYBOX = false;
  75221. _this.REFLECTIONMAP_EXPLICIT = false;
  75222. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75223. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75224. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75225. _this.INVERTCUBICMAP = false;
  75226. _this.REFLECTIONMAP_OPPOSITEZ = false;
  75227. _this.LODINREFLECTIONALPHA = false;
  75228. _this.GAMMAREFLECTION = false;
  75229. // Default BJS.
  75230. _this.MAINUV1 = false;
  75231. _this.MAINUV2 = false;
  75232. _this.UV1 = false;
  75233. _this.UV2 = false;
  75234. _this.CLIPPLANE = false;
  75235. _this.POINTSIZE = false;
  75236. _this.FOG = false;
  75237. _this.NORMAL = false;
  75238. _this.NUM_BONE_INFLUENCERS = 0;
  75239. _this.BonesPerMesh = 0;
  75240. _this.INSTANCES = false;
  75241. _this.SHADOWFLOAT = false;
  75242. _this.rebuild();
  75243. return _this;
  75244. }
  75245. return BackgroundMaterialDefines;
  75246. }(BABYLON.MaterialDefines));
  75247. /**
  75248. * Background material used to create an efficient environement around your scene.
  75249. */
  75250. var BackgroundMaterial = /** @class */ (function (_super) {
  75251. __extends(BackgroundMaterial, _super);
  75252. /**
  75253. * constructor
  75254. * @param name The name of the material
  75255. * @param scene The scene to add the material to
  75256. */
  75257. function BackgroundMaterial(name, scene) {
  75258. var _this = _super.call(this, name, scene) || this;
  75259. _this.primaryColor = BABYLON.Color3.White();
  75260. _this.primaryLevel = 1;
  75261. _this.secondaryColor = BABYLON.Color3.Gray();
  75262. _this.secondaryLevel = 1;
  75263. _this.tertiaryColor = BABYLON.Color3.Black();
  75264. _this.tertiaryLevel = 1;
  75265. _this.reflectionTexture = null;
  75266. _this.reflectionBlur = 0;
  75267. _this.diffuseTexture = null;
  75268. /**
  75269. * Specify the list of lights casting shadow on the material.
  75270. * All scene shadow lights will be included if null.
  75271. */
  75272. _this._shadowLights = null;
  75273. _this.shadowLights = null;
  75274. _this.shadowBlurScale = 1;
  75275. _this.shadowLevel = 0;
  75276. _this.sceneCenter = BABYLON.Vector3.Zero();
  75277. _this.opacityFresnel = true;
  75278. _this.reflectionFresnel = false;
  75279. _this.reflectionFalloffDistance = 0.0;
  75280. _this.reflectionAmount = 1.0;
  75281. _this.reflectionReflectance0 = 0.05;
  75282. _this.reflectionReflectance90 = 0.5;
  75283. _this.useRGBColor = true;
  75284. /**
  75285. * Number of Simultaneous lights allowed on the material.
  75286. */
  75287. _this._maxSimultaneousLights = 4;
  75288. _this.maxSimultaneousLights = 4;
  75289. /**
  75290. * Keep track of the image processing observer to allow dispose and replace.
  75291. */
  75292. _this._imageProcessingObserver = null;
  75293. // Temp values kept as cache in the material.
  75294. _this._renderTargets = new BABYLON.SmartArray(16);
  75295. _this._reflectionControls = BABYLON.Vector4.Zero();
  75296. // Setup the default processing configuration to the scene.
  75297. _this._attachImageProcessingConfiguration(null);
  75298. _this.getRenderTargetTextures = function () {
  75299. _this._renderTargets.reset();
  75300. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  75301. _this._renderTargets.push(_this._diffuseTexture);
  75302. }
  75303. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  75304. _this._renderTargets.push(_this._reflectionTexture);
  75305. }
  75306. return _this._renderTargets;
  75307. };
  75308. return _this;
  75309. }
  75310. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  75311. /**
  75312. * Sets the reflection reflectance fresnel values according to the default standard
  75313. * empirically know to work well :-)
  75314. */
  75315. set: function (value) {
  75316. var reflectionWeight = value;
  75317. if (reflectionWeight < 0.5) {
  75318. reflectionWeight = reflectionWeight * 2.0;
  75319. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  75320. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  75321. }
  75322. else {
  75323. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  75324. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  75325. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  75326. }
  75327. },
  75328. enumerable: true,
  75329. configurable: true
  75330. });
  75331. /**
  75332. * Attaches a new image processing configuration to the PBR Material.
  75333. * @param configuration (if null the scene configuration will be use)
  75334. */
  75335. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  75336. var _this = this;
  75337. if (configuration === this._imageProcessingConfiguration) {
  75338. return;
  75339. }
  75340. // Detaches observer.
  75341. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75342. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75343. }
  75344. // Pick the scene configuration if needed.
  75345. if (!configuration) {
  75346. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  75347. }
  75348. else {
  75349. this._imageProcessingConfiguration = configuration;
  75350. }
  75351. // Attaches observer.
  75352. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75353. _this._markAllSubMeshesAsImageProcessingDirty();
  75354. });
  75355. };
  75356. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  75357. /**
  75358. * Gets the image processing configuration used either in this material.
  75359. */
  75360. get: function () {
  75361. return this._imageProcessingConfiguration;
  75362. },
  75363. /**
  75364. * Sets the Default image processing configuration used either in the this material.
  75365. *
  75366. * If sets to null, the scene one is in use.
  75367. */
  75368. set: function (value) {
  75369. this._attachImageProcessingConfiguration(value);
  75370. // Ensure the effect will be rebuilt.
  75371. this._markAllSubMeshesAsTexturesDirty();
  75372. },
  75373. enumerable: true,
  75374. configurable: true
  75375. });
  75376. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  75377. /**
  75378. * Gets wether the color curves effect is enabled.
  75379. */
  75380. get: function () {
  75381. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75382. },
  75383. /**
  75384. * Sets wether the color curves effect is enabled.
  75385. */
  75386. set: function (value) {
  75387. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75388. },
  75389. enumerable: true,
  75390. configurable: true
  75391. });
  75392. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  75393. /**
  75394. * Gets wether the color grading effect is enabled.
  75395. */
  75396. get: function () {
  75397. return this.imageProcessingConfiguration.colorGradingEnabled;
  75398. },
  75399. /**
  75400. * Gets wether the color grading effect is enabled.
  75401. */
  75402. set: function (value) {
  75403. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75404. },
  75405. enumerable: true,
  75406. configurable: true
  75407. });
  75408. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  75409. /**
  75410. * Gets wether tonemapping is enabled or not.
  75411. */
  75412. get: function () {
  75413. return this._imageProcessingConfiguration.toneMappingEnabled;
  75414. },
  75415. /**
  75416. * Sets wether tonemapping is enabled or not
  75417. */
  75418. set: function (value) {
  75419. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75420. },
  75421. enumerable: true,
  75422. configurable: true
  75423. });
  75424. ;
  75425. ;
  75426. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  75427. /**
  75428. * The camera exposure used on this material.
  75429. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  75430. * This corresponds to a photographic exposure.
  75431. */
  75432. get: function () {
  75433. return this._imageProcessingConfiguration.exposure;
  75434. },
  75435. /**
  75436. * The camera exposure used on this material.
  75437. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  75438. * This corresponds to a photographic exposure.
  75439. */
  75440. set: function (value) {
  75441. this._imageProcessingConfiguration.exposure = value;
  75442. },
  75443. enumerable: true,
  75444. configurable: true
  75445. });
  75446. ;
  75447. ;
  75448. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  75449. /**
  75450. * Gets The camera contrast used on this material.
  75451. */
  75452. get: function () {
  75453. return this._imageProcessingConfiguration.contrast;
  75454. },
  75455. /**
  75456. * Sets The camera contrast used on this material.
  75457. */
  75458. set: function (value) {
  75459. this._imageProcessingConfiguration.contrast = value;
  75460. },
  75461. enumerable: true,
  75462. configurable: true
  75463. });
  75464. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  75465. /**
  75466. * Gets the Color Grading 2D Lookup Texture.
  75467. */
  75468. get: function () {
  75469. return this._imageProcessingConfiguration.colorGradingTexture;
  75470. },
  75471. /**
  75472. * Sets the Color Grading 2D Lookup Texture.
  75473. */
  75474. set: function (value) {
  75475. this.imageProcessingConfiguration.colorGradingTexture = value;
  75476. },
  75477. enumerable: true,
  75478. configurable: true
  75479. });
  75480. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  75481. /**
  75482. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  75483. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  75484. * 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;
  75485. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  75486. */
  75487. get: function () {
  75488. return this.imageProcessingConfiguration.colorCurves;
  75489. },
  75490. /**
  75491. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  75492. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  75493. * 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;
  75494. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  75495. */
  75496. set: function (value) {
  75497. this.imageProcessingConfiguration.colorCurves = value;
  75498. },
  75499. enumerable: true,
  75500. configurable: true
  75501. });
  75502. /**
  75503. * The entire material has been created in order to prevent overdraw.
  75504. * @returns false
  75505. */
  75506. BackgroundMaterial.prototype.needAlphaTesting = function () {
  75507. return false;
  75508. };
  75509. /**
  75510. * The entire material has been created in order to prevent overdraw.
  75511. * @returns true if blending is enable
  75512. */
  75513. BackgroundMaterial.prototype.needAlphaBlending = function () {
  75514. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  75515. };
  75516. /**
  75517. * Checks wether the material is ready to be rendered for a given mesh.
  75518. * @param mesh The mesh to render
  75519. * @param subMesh The submesh to check against
  75520. * @param useInstances Specify wether or not the material is used with instances
  75521. */
  75522. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75523. var _this = this;
  75524. if (useInstances === void 0) { useInstances = false; }
  75525. if (subMesh.effect && this.isFrozen) {
  75526. if (this._wasPreviouslyReady) {
  75527. return true;
  75528. }
  75529. }
  75530. if (!subMesh._materialDefines) {
  75531. subMesh._materialDefines = new BackgroundMaterialDefines();
  75532. }
  75533. var scene = this.getScene();
  75534. var defines = subMesh._materialDefines;
  75535. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  75536. if (defines._renderId === scene.getRenderId()) {
  75537. return true;
  75538. }
  75539. }
  75540. var engine = scene.getEngine();
  75541. // Lights
  75542. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  75543. defines._needNormals = true;
  75544. // Textures
  75545. if (defines._areTexturesDirty) {
  75546. defines._needUVs = false;
  75547. if (scene.texturesEnabled) {
  75548. if (scene.getEngine().getCaps().textureLOD) {
  75549. defines.TEXTURELODSUPPORT = true;
  75550. }
  75551. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75552. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  75553. return false;
  75554. }
  75555. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  75556. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  75557. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  75558. defines.OPACITYFRESNEL = this._opacityFresnel;
  75559. }
  75560. else {
  75561. defines.DIFFUSE = false;
  75562. defines.DIFFUSEHASALPHA = false;
  75563. defines.GAMMADIFFUSE = false;
  75564. defines.OPACITYFRESNEL = false;
  75565. }
  75566. var reflectionTexture = this._reflectionTexture;
  75567. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75568. if (!reflectionTexture.isReadyOrNotBlocking()) {
  75569. return false;
  75570. }
  75571. defines.REFLECTION = true;
  75572. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  75573. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  75574. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  75575. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  75576. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  75577. defines.INVERTCUBICMAP = true;
  75578. }
  75579. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  75580. switch (reflectionTexture.coordinatesMode) {
  75581. case BABYLON.Texture.CUBIC_MODE:
  75582. case BABYLON.Texture.INVCUBIC_MODE:
  75583. defines.REFLECTIONMAP_CUBIC = true;
  75584. break;
  75585. case BABYLON.Texture.EXPLICIT_MODE:
  75586. defines.REFLECTIONMAP_EXPLICIT = true;
  75587. break;
  75588. case BABYLON.Texture.PLANAR_MODE:
  75589. defines.REFLECTIONMAP_PLANAR = true;
  75590. break;
  75591. case BABYLON.Texture.PROJECTION_MODE:
  75592. defines.REFLECTIONMAP_PROJECTION = true;
  75593. break;
  75594. case BABYLON.Texture.SKYBOX_MODE:
  75595. defines.REFLECTIONMAP_SKYBOX = true;
  75596. break;
  75597. case BABYLON.Texture.SPHERICAL_MODE:
  75598. defines.REFLECTIONMAP_SPHERICAL = true;
  75599. break;
  75600. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  75601. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  75602. break;
  75603. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  75604. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  75605. break;
  75606. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  75607. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  75608. break;
  75609. }
  75610. if (this.reflectionFresnel) {
  75611. defines.REFLECTIONFRESNEL = true;
  75612. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  75613. this._reflectionControls.x = this.reflectionAmount;
  75614. this._reflectionControls.y = this.reflectionReflectance0;
  75615. this._reflectionControls.z = this.reflectionReflectance90;
  75616. this._reflectionControls.w = this.reflectionFalloffDistance;
  75617. }
  75618. else {
  75619. defines.REFLECTIONFRESNEL = false;
  75620. defines.REFLECTIONFALLOFF = false;
  75621. }
  75622. }
  75623. else {
  75624. defines.REFLECTION = false;
  75625. defines.REFLECTIONFALLOFF = false;
  75626. defines.REFLECTIONBLUR = false;
  75627. defines.REFLECTIONMAP_3D = false;
  75628. defines.REFLECTIONMAP_SPHERICAL = false;
  75629. defines.REFLECTIONMAP_PLANAR = false;
  75630. defines.REFLECTIONMAP_CUBIC = false;
  75631. defines.REFLECTIONMAP_PROJECTION = false;
  75632. defines.REFLECTIONMAP_SKYBOX = false;
  75633. defines.REFLECTIONMAP_EXPLICIT = false;
  75634. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75635. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75636. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75637. defines.INVERTCUBICMAP = false;
  75638. defines.REFLECTIONMAP_OPPOSITEZ = false;
  75639. defines.LODINREFLECTIONALPHA = false;
  75640. defines.GAMMAREFLECTION = false;
  75641. }
  75642. }
  75643. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  75644. defines.USERGBCOLOR = this._useRGBColor;
  75645. }
  75646. if (defines._areImageProcessingDirty) {
  75647. if (!this._imageProcessingConfiguration.isReady()) {
  75648. return false;
  75649. }
  75650. this._imageProcessingConfiguration.prepareDefines(defines);
  75651. }
  75652. // Misc.
  75653. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  75654. // Values that need to be evaluated on every frame
  75655. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  75656. // Attribs
  75657. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  75658. if (mesh) {
  75659. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75660. mesh.createNormals(true);
  75661. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  75662. }
  75663. }
  75664. }
  75665. // Get correct effect
  75666. if (defines.isDirty) {
  75667. defines.markAsProcessed();
  75668. scene.resetCachedMaterial();
  75669. // Fallbacks
  75670. var fallbacks = new BABYLON.EffectFallbacks();
  75671. if (defines.FOG) {
  75672. fallbacks.addFallback(0, "FOG");
  75673. }
  75674. if (defines.POINTSIZE) {
  75675. fallbacks.addFallback(1, "POINTSIZE");
  75676. }
  75677. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  75678. if (defines.NUM_BONE_INFLUENCERS > 0) {
  75679. fallbacks.addCPUSkinningFallback(0, mesh);
  75680. }
  75681. //Attributes
  75682. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75683. if (defines.NORMAL) {
  75684. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75685. }
  75686. if (defines.UV1) {
  75687. attribs.push(BABYLON.VertexBuffer.UVKind);
  75688. }
  75689. if (defines.UV2) {
  75690. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75691. }
  75692. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  75693. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  75694. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  75695. "vFogInfos", "vFogColor", "pointSize",
  75696. "vClipPlane", "mBones",
  75697. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  75698. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  75699. "shadowLevel", "alpha",
  75700. "vBackgroundCenter", "vReflectionControl",
  75701. "vDiffuseInfos", "diffuseMatrix",
  75702. ];
  75703. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  75704. var uniformBuffers = ["Material", "Scene"];
  75705. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  75706. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  75707. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  75708. uniformsNames: uniforms,
  75709. uniformBuffersNames: uniformBuffers,
  75710. samplers: samplers,
  75711. defines: defines,
  75712. maxSimultaneousLights: this._maxSimultaneousLights
  75713. });
  75714. var onCompiled = function (effect) {
  75715. if (_this.onCompiled) {
  75716. _this.onCompiled(effect);
  75717. }
  75718. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  75719. };
  75720. var join = defines.toString();
  75721. subMesh.setEffect(scene.getEngine().createEffect("background", {
  75722. attributes: attribs,
  75723. uniformsNames: uniforms,
  75724. uniformBuffersNames: uniformBuffers,
  75725. samplers: samplers,
  75726. defines: join,
  75727. fallbacks: fallbacks,
  75728. onCompiled: onCompiled,
  75729. onError: this.onError,
  75730. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  75731. }, engine), defines);
  75732. this.buildUniformLayout();
  75733. }
  75734. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75735. return false;
  75736. }
  75737. defines._renderId = scene.getRenderId();
  75738. this._wasPreviouslyReady = true;
  75739. return true;
  75740. };
  75741. /**
  75742. * Build the uniform buffer used in the material.
  75743. */
  75744. BackgroundMaterial.prototype.buildUniformLayout = function () {
  75745. // Order is important !
  75746. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  75747. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  75748. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  75749. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  75750. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  75751. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  75752. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  75753. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  75754. this._uniformBuffer.addUniform("pointSize", 1);
  75755. this._uniformBuffer.addUniform("shadowLevel", 1);
  75756. this._uniformBuffer.addUniform("alpha", 1);
  75757. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  75758. this._uniformBuffer.addUniform("vReflectionControl", 4);
  75759. this._uniformBuffer.create();
  75760. };
  75761. /**
  75762. * Unbind the material.
  75763. */
  75764. BackgroundMaterial.prototype.unbind = function () {
  75765. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  75766. this._uniformBuffer.setTexture("diffuseSampler", null);
  75767. }
  75768. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  75769. this._uniformBuffer.setTexture("reflectionSampler", null);
  75770. }
  75771. _super.prototype.unbind.call(this);
  75772. };
  75773. /**
  75774. * Bind only the world matrix to the material.
  75775. * @param world The world matrix to bind.
  75776. */
  75777. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  75778. this._activeEffect.setMatrix("world", world);
  75779. };
  75780. /**
  75781. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  75782. * @param world The world matrix to bind.
  75783. * @param subMesh The submesh to bind for.
  75784. */
  75785. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75786. var scene = this.getScene();
  75787. var defines = subMesh._materialDefines;
  75788. if (!defines) {
  75789. return;
  75790. }
  75791. var effect = subMesh.effect;
  75792. if (!effect) {
  75793. return;
  75794. }
  75795. this._activeEffect = effect;
  75796. // Matrices
  75797. this.bindOnlyWorldMatrix(world);
  75798. // Bones
  75799. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  75800. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  75801. if (mustRebind) {
  75802. this._uniformBuffer.bindToEffect(effect, "Material");
  75803. this.bindViewProjection(effect);
  75804. var reflectionTexture = this._reflectionTexture;
  75805. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  75806. // Texture uniforms
  75807. if (scene.texturesEnabled) {
  75808. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75809. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  75810. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  75811. }
  75812. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75813. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  75814. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  75815. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  75816. }
  75817. }
  75818. if (this.shadowLevel > 0) {
  75819. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  75820. }
  75821. this._uniformBuffer.updateFloat("alpha", this.alpha);
  75822. // Point size
  75823. if (this.pointsCloud) {
  75824. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  75825. }
  75826. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  75827. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  75828. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  75829. }
  75830. // Textures
  75831. if (scene.texturesEnabled) {
  75832. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75833. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  75834. }
  75835. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75836. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  75837. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75838. }
  75839. else if (!defines.REFLECTIONBLUR) {
  75840. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75841. }
  75842. else {
  75843. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  75844. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  75845. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  75846. }
  75847. if (defines.REFLECTIONFRESNEL) {
  75848. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  75849. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  75850. }
  75851. }
  75852. }
  75853. // Clip plane
  75854. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  75855. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  75856. }
  75857. if (mustRebind || !this.isFrozen) {
  75858. if (scene.lightsEnabled) {
  75859. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  75860. }
  75861. // View
  75862. this.bindView(effect);
  75863. // Fog
  75864. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75865. // image processing
  75866. this._imageProcessingConfiguration.bind(this._activeEffect);
  75867. }
  75868. this._uniformBuffer.update();
  75869. this._afterBind(mesh);
  75870. };
  75871. /**
  75872. * Dispose the material.
  75873. * @forceDisposeEffect Force disposal of the associated effect.
  75874. * @forceDisposeTextures Force disposal of the associated textures.
  75875. */
  75876. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75877. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  75878. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  75879. if (forceDisposeTextures) {
  75880. if (this.diffuseTexture) {
  75881. this.diffuseTexture.dispose();
  75882. }
  75883. if (this.reflectionTexture) {
  75884. this.reflectionTexture.dispose();
  75885. }
  75886. }
  75887. this._renderTargets.dispose();
  75888. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75889. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75890. }
  75891. _super.prototype.dispose.call(this, forceDisposeEffect);
  75892. };
  75893. /**
  75894. * Clones the material.
  75895. * @name The cloned name.
  75896. * @returns The cloned material.
  75897. */
  75898. BackgroundMaterial.prototype.clone = function (name) {
  75899. var _this = this;
  75900. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  75901. };
  75902. /**
  75903. * Serializes the current material to its JSON representation.
  75904. * @returns The JSON representation.
  75905. */
  75906. BackgroundMaterial.prototype.serialize = function () {
  75907. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75908. serializationObject.customType = "BABYLON.BackgroundMaterial";
  75909. return serializationObject;
  75910. };
  75911. /**
  75912. * Gets the class name of the material
  75913. * @returns "BackgroundMaterial"
  75914. */
  75915. BackgroundMaterial.prototype.getClassName = function () {
  75916. return "BackgroundMaterial";
  75917. };
  75918. /**
  75919. * Parse a JSON input to create back a background material.
  75920. * @param source
  75921. * @param scene
  75922. * @param rootUrl
  75923. * @returns the instantiated BackgroundMaterial.
  75924. */
  75925. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  75926. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  75927. };
  75928. /**
  75929. * Standard reflectance value at parallel view angle.
  75930. */
  75931. BackgroundMaterial.standardReflectance0 = 0.05;
  75932. /**
  75933. * Standard reflectance value at grazing angle.
  75934. */
  75935. BackgroundMaterial.standardReflectance90 = 0.5;
  75936. __decorate([
  75937. BABYLON.serializeAsColor3()
  75938. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  75939. __decorate([
  75940. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75941. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  75942. __decorate([
  75943. BABYLON.serialize()
  75944. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  75945. __decorate([
  75946. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75947. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  75948. __decorate([
  75949. BABYLON.serializeAsColor3()
  75950. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  75951. __decorate([
  75952. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75953. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  75954. __decorate([
  75955. BABYLON.serialize()
  75956. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  75957. __decorate([
  75958. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75959. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  75960. __decorate([
  75961. BABYLON.serializeAsColor3()
  75962. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  75963. __decorate([
  75964. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75965. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  75966. __decorate([
  75967. BABYLON.serialize()
  75968. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  75969. __decorate([
  75970. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75971. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  75972. __decorate([
  75973. BABYLON.serializeAsTexture()
  75974. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  75975. __decorate([
  75976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75977. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  75978. __decorate([
  75979. BABYLON.serialize()
  75980. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  75981. __decorate([
  75982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75983. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  75984. __decorate([
  75985. BABYLON.serializeAsTexture()
  75986. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  75987. __decorate([
  75988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75989. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  75990. __decorate([
  75991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75992. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  75993. __decorate([
  75994. BABYLON.serialize()
  75995. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  75996. __decorate([
  75997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75998. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  75999. __decorate([
  76000. BABYLON.serialize()
  76001. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  76002. __decorate([
  76003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76004. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  76005. __decorate([
  76006. BABYLON.serializeAsVector3()
  76007. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  76008. __decorate([
  76009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76010. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  76011. __decorate([
  76012. BABYLON.serialize()
  76013. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  76014. __decorate([
  76015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76016. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  76017. __decorate([
  76018. BABYLON.serialize()
  76019. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  76020. __decorate([
  76021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76022. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  76023. __decorate([
  76024. BABYLON.serialize()
  76025. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  76026. __decorate([
  76027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76028. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  76029. __decorate([
  76030. BABYLON.serialize()
  76031. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  76032. __decorate([
  76033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76034. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  76035. __decorate([
  76036. BABYLON.serialize()
  76037. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  76038. __decorate([
  76039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76040. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  76041. __decorate([
  76042. BABYLON.serialize()
  76043. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  76044. __decorate([
  76045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76046. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  76047. __decorate([
  76048. BABYLON.serialize()
  76049. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  76050. __decorate([
  76051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76052. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  76053. __decorate([
  76054. BABYLON.serialize()
  76055. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  76056. __decorate([
  76057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76058. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  76059. __decorate([
  76060. BABYLON.serializeAsImageProcessingConfiguration()
  76061. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  76062. return BackgroundMaterial;
  76063. }(BABYLON.PushMaterial));
  76064. BABYLON.BackgroundMaterial = BackgroundMaterial;
  76065. })(BABYLON || (BABYLON = {}));
  76066. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  76067. var __assign = (this && this.__assign) || Object.assign || function(t) {
  76068. for (var s, i = 1, n = arguments.length; i < n; i++) {
  76069. s = arguments[i];
  76070. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  76071. t[p] = s[p];
  76072. }
  76073. return t;
  76074. };
  76075. var BABYLON;
  76076. (function (BABYLON) {
  76077. /**
  76078. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  76079. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  76080. * It also helps with the default setup of your imageProcessing configuration.
  76081. */
  76082. var EnvironmentHelper = /** @class */ (function () {
  76083. /**
  76084. * constructor
  76085. * @param options
  76086. * @param scene The scene to add the material to
  76087. */
  76088. function EnvironmentHelper(options, scene) {
  76089. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  76090. this._scene = scene;
  76091. this._setupBackground();
  76092. this._setupImageProcessing();
  76093. }
  76094. /**
  76095. * Creates the default options for the helper.
  76096. */
  76097. EnvironmentHelper._getDefaultOptions = function () {
  76098. return {
  76099. createGround: true,
  76100. groundSize: 15,
  76101. groundTexture: this._groundTextureCDNUrl,
  76102. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3),
  76103. groundOpacity: 1,
  76104. enableGroundShadow: true,
  76105. groundShadowLevel: 0.5,
  76106. enableGroundMirror: false,
  76107. groundMirrorSizeRatio: 0.3,
  76108. groundMirrorBlurKernel: 64,
  76109. groundMirrorAmount: 1,
  76110. groundMirrorFresnelWeight: 1,
  76111. groundMirrorFallOffDistance: 0,
  76112. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  76113. createSkybox: true,
  76114. skyboxSize: 20,
  76115. skyboxTexture: this._skyboxTextureCDNUrl,
  76116. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3),
  76117. backgroundYRotation: 0,
  76118. sizeAuto: true,
  76119. setupImageProcessing: true,
  76120. environmentTexture: this._environmentTextureCDNUrl,
  76121. cameraExposure: 0.8,
  76122. cameraContrast: 1.6,
  76123. toneMappingEnabled: true,
  76124. };
  76125. };
  76126. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  76127. /**
  76128. * Gets the root mesh created by the helper.
  76129. */
  76130. get: function () {
  76131. return this._rootMesh;
  76132. },
  76133. enumerable: true,
  76134. configurable: true
  76135. });
  76136. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  76137. /**
  76138. * Gets the skybox created by the helper.
  76139. */
  76140. get: function () {
  76141. return this._skybox;
  76142. },
  76143. enumerable: true,
  76144. configurable: true
  76145. });
  76146. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  76147. /**
  76148. * Gets the skybox texture created by the helper.
  76149. */
  76150. get: function () {
  76151. return this._skyboxTexture;
  76152. },
  76153. enumerable: true,
  76154. configurable: true
  76155. });
  76156. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  76157. /**
  76158. * Gets the skybox material created by the helper.
  76159. */
  76160. get: function () {
  76161. return this._skyboxMaterial;
  76162. },
  76163. enumerable: true,
  76164. configurable: true
  76165. });
  76166. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  76167. /**
  76168. * Gets the ground mesh created by the helper.
  76169. */
  76170. get: function () {
  76171. return this._ground;
  76172. },
  76173. enumerable: true,
  76174. configurable: true
  76175. });
  76176. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  76177. /**
  76178. * Gets the ground texture created by the helper.
  76179. */
  76180. get: function () {
  76181. return this._groundTexture;
  76182. },
  76183. enumerable: true,
  76184. configurable: true
  76185. });
  76186. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  76187. /**
  76188. * Gets the ground mirror created by the helper.
  76189. */
  76190. get: function () {
  76191. return this._groundMirror;
  76192. },
  76193. enumerable: true,
  76194. configurable: true
  76195. });
  76196. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  76197. /**
  76198. * Gets the ground mirror render list to helps pushing the meshes
  76199. * you wish in the ground reflection.
  76200. */
  76201. get: function () {
  76202. return this._groundMirror.renderList;
  76203. },
  76204. enumerable: true,
  76205. configurable: true
  76206. });
  76207. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  76208. /**
  76209. * Gets the ground material created by the helper.
  76210. */
  76211. get: function () {
  76212. return this._groundMaterial;
  76213. },
  76214. enumerable: true,
  76215. configurable: true
  76216. });
  76217. /**
  76218. * Updates the background according to the new options
  76219. * @param options
  76220. */
  76221. EnvironmentHelper.prototype.updateOptions = function (options) {
  76222. var newOptions = __assign({}, this._options, options);
  76223. if (this._ground && !newOptions.createGround) {
  76224. this._ground.dispose();
  76225. this._ground = null;
  76226. }
  76227. if (this._groundMaterial && !newOptions.createGround) {
  76228. this._groundMaterial.dispose();
  76229. this._groundMaterial = null;
  76230. }
  76231. if (this._options.groundTexture && !newOptions.groundTexture && this._groundTexture) {
  76232. this._groundTexture.dispose();
  76233. this._groundTexture = null;
  76234. }
  76235. if (this._skybox && !newOptions.createSkybox) {
  76236. this._skybox.dispose();
  76237. this._skybox = null;
  76238. }
  76239. if (this._skyboxMaterial && !newOptions.createSkybox) {
  76240. this._skyboxMaterial.dispose();
  76241. this._skyboxMaterial = null;
  76242. }
  76243. if (this._options.skyboxTexture && !newOptions.skyboxTexture && this._skyboxTexture) {
  76244. this._skyboxTexture.dispose();
  76245. this._skyboxTexture = null;
  76246. }
  76247. if (this._groundMirror && !newOptions.enableGroundMirror) {
  76248. this._groundMirror.dispose();
  76249. this._groundMirror = null;
  76250. }
  76251. this._setupBackground();
  76252. if (this._options.environmentTexture && !newOptions.environmentTexture && this._scene.environmentTexture) {
  76253. this._scene.environmentTexture.dispose();
  76254. }
  76255. this._setupImageProcessing();
  76256. };
  76257. /**
  76258. * Sets the primary color of all the available elements.
  76259. * @param color
  76260. */
  76261. EnvironmentHelper.prototype.setMainColor = function (color) {
  76262. if (this.groundMaterial) {
  76263. this.groundMaterial.primaryColor = color;
  76264. }
  76265. if (this.skyboxMaterial) {
  76266. this.skyboxMaterial.primaryColor = color;
  76267. }
  76268. if (this.groundMirror) {
  76269. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  76270. }
  76271. };
  76272. /**
  76273. * Setup the image processing according to the specified options.
  76274. */
  76275. EnvironmentHelper.prototype._setupImageProcessing = function () {
  76276. if (this._options.setupImageProcessing) {
  76277. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  76278. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  76279. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  76280. this._setupEnvironmentTexture();
  76281. }
  76282. };
  76283. /**
  76284. * Setup the environment texture according to the specified options.
  76285. */
  76286. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  76287. if (this._scene.environmentTexture) {
  76288. return;
  76289. }
  76290. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  76291. this._scene.environmentTexture = this._options.environmentTexture;
  76292. return;
  76293. }
  76294. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  76295. this._scene.environmentTexture = environmentTexture;
  76296. };
  76297. /**
  76298. * Setup the background according to the specified options.
  76299. */
  76300. EnvironmentHelper.prototype._setupBackground = function () {
  76301. if (!this._rootMesh) {
  76302. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  76303. }
  76304. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  76305. if (this._options.createGround) {
  76306. this._setupGround();
  76307. this._setupGroundMaterial();
  76308. this._setupGroundDiffuseTexture();
  76309. if (this._options.enableGroundMirror) {
  76310. this._setupGroundMirrorTexture();
  76311. this._setupMirrorInGroundMaterial();
  76312. }
  76313. }
  76314. if (this._options.createSkybox) {
  76315. this._setupSkybox();
  76316. this._setupSkyboxMaterial();
  76317. this._setupSkyboxReflectionTexture();
  76318. }
  76319. };
  76320. /**
  76321. * Setup the ground according to the specified options.
  76322. */
  76323. EnvironmentHelper.prototype._setupGround = function () {
  76324. if (!this._ground) {
  76325. var size = this._options.groundSize;
  76326. if (this._options.sizeAuto) {
  76327. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  76328. this._scene.activeCamera.upperRadiusLimit) {
  76329. size = this._scene.activeCamera.upperRadiusLimit * 0.9;
  76330. }
  76331. }
  76332. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", size, this._scene);
  76333. }
  76334. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  76335. this._ground.receiveShadows = this._options.enableGroundShadow;
  76336. this._ground.parent = this._rootMesh;
  76337. };
  76338. /**
  76339. * Setup the ground material according to the specified options.
  76340. */
  76341. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  76342. if (!this._groundMaterial) {
  76343. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  76344. }
  76345. this._groundMaterial.alpha = this._options.groundOpacity;
  76346. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  76347. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  76348. this._groundMaterial.primaryLevel = 1;
  76349. this._groundMaterial.primaryColor = this._options.groundColor;
  76350. this._groundMaterial.secondaryLevel = 0;
  76351. this._groundMaterial.tertiaryLevel = 0;
  76352. this._groundMaterial.useRGBColor = false;
  76353. if (this._ground) {
  76354. this._ground.material = this._groundMaterial;
  76355. }
  76356. };
  76357. /**
  76358. * Setup the ground diffuse texture according to the specified options.
  76359. */
  76360. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  76361. if (!this._groundMaterial) {
  76362. return;
  76363. }
  76364. if (this._groundTexture) {
  76365. return;
  76366. }
  76367. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  76368. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  76369. return;
  76370. }
  76371. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  76372. diffuseTexture.gammaSpace = false;
  76373. diffuseTexture.hasAlpha = true;
  76374. this._groundMaterial.diffuseTexture = diffuseTexture;
  76375. };
  76376. /**
  76377. * Setup the ground mirror texture according to the specified options.
  76378. */
  76379. EnvironmentHelper.prototype._setupGroundMirrorTexture = function () {
  76380. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76381. if (!this._groundMirror) {
  76382. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  76383. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, 0);
  76384. this._groundMirror.anisotropicFilteringLevel = 1;
  76385. this._groundMirror.wrapU = wrapping;
  76386. this._groundMirror.wrapV = wrapping;
  76387. }
  76388. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  76389. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  76390. };
  76391. /**
  76392. * Setup the ground to receive the mirror texture.
  76393. */
  76394. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  76395. if (this._groundMaterial) {
  76396. this._groundMaterial.reflectionTexture = this._groundMirror;
  76397. this._groundMaterial.reflectionFresnel = true;
  76398. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  76399. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  76400. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  76401. }
  76402. };
  76403. /**
  76404. * Setup the skybox according to the specified options.
  76405. */
  76406. EnvironmentHelper.prototype._setupSkybox = function () {
  76407. if (!this._skybox) {
  76408. var size = this._options.skyboxSize;
  76409. if (this._options.sizeAuto) {
  76410. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  76411. this._scene.activeCamera.upperRadiusLimit) {
  76412. size = this._scene.activeCamera.upperRadiusLimit;
  76413. }
  76414. }
  76415. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", size, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  76416. }
  76417. this._skybox.parent = this._rootMesh;
  76418. };
  76419. /**
  76420. * Setup the skybox material according to the specified options.
  76421. */
  76422. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  76423. if (!this._skybox) {
  76424. return;
  76425. }
  76426. if (!this._skyboxMaterial) {
  76427. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  76428. }
  76429. this._skyboxMaterial.useRGBColor = false;
  76430. this._skyboxMaterial.primaryLevel = 1;
  76431. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  76432. this._skyboxMaterial.secondaryLevel = 0;
  76433. this._skyboxMaterial.tertiaryLevel = 0;
  76434. this._skybox.material = this._skyboxMaterial;
  76435. };
  76436. /**
  76437. * Setup the skybox reflection texture according to the specified options.
  76438. */
  76439. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  76440. if (!this._skyboxMaterial) {
  76441. return;
  76442. }
  76443. if (this._skyboxTexture) {
  76444. return;
  76445. }
  76446. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  76447. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  76448. return;
  76449. }
  76450. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  76451. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  76452. this._skyboxTexture.gammaSpace = false;
  76453. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  76454. };
  76455. /**
  76456. * Dispose all the elements created by the Helper.
  76457. */
  76458. EnvironmentHelper.prototype.dispose = function () {
  76459. if (this._groundMaterial) {
  76460. this._groundMaterial.dispose(true, true);
  76461. }
  76462. if (this._skyboxMaterial) {
  76463. this._skyboxMaterial.dispose(true, true);
  76464. }
  76465. this._rootMesh.dispose(true);
  76466. };
  76467. /**
  76468. * Default ground texture URL.
  76469. */
  76470. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  76471. /**
  76472. * Default skybox texture URL.
  76473. */
  76474. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  76475. /**
  76476. * Default environment texture URL.
  76477. */
  76478. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  76479. return EnvironmentHelper;
  76480. }());
  76481. BABYLON.EnvironmentHelper = EnvironmentHelper;
  76482. })(BABYLON || (BABYLON = {}));
  76483. //# sourceMappingURL=babylon.environmentHelper.js.map
  76484. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\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#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(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\ngl_FragColor=color;\n}"};
  76485. 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}","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","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};"};
  76486. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  76487. var BABYLON;
  76488. (function (BABYLON) {
  76489. var GridMaterialDefines = /** @class */ (function (_super) {
  76490. __extends(GridMaterialDefines, _super);
  76491. function GridMaterialDefines() {
  76492. var _this = _super.call(this) || this;
  76493. _this.TRANSPARENT = false;
  76494. _this.FOG = false;
  76495. _this.PREMULTIPLYALPHA = false;
  76496. _this.rebuild();
  76497. return _this;
  76498. }
  76499. return GridMaterialDefines;
  76500. }(BABYLON.MaterialDefines));
  76501. /**
  76502. * The grid materials allows you to wrap any shape with a grid.
  76503. * Colors are customizable.
  76504. */
  76505. var GridMaterial = /** @class */ (function (_super) {
  76506. __extends(GridMaterial, _super);
  76507. /**
  76508. * constructor
  76509. * @param name The name given to the material in order to identify it afterwards.
  76510. * @param scene The scene the material is used in.
  76511. */
  76512. function GridMaterial(name, scene) {
  76513. var _this = _super.call(this, name, scene) || this;
  76514. /**
  76515. * Main color of the grid (e.g. between lines)
  76516. */
  76517. _this.mainColor = BABYLON.Color3.Black();
  76518. /**
  76519. * Color of the grid lines.
  76520. */
  76521. _this.lineColor = BABYLON.Color3.Teal();
  76522. /**
  76523. * The scale of the grid compared to unit.
  76524. */
  76525. _this.gridRatio = 1.0;
  76526. /**
  76527. * Allows setting an offset for the grid lines.
  76528. */
  76529. _this.gridOffset = BABYLON.Vector3.Zero();
  76530. /**
  76531. * The frequency of thicker lines.
  76532. */
  76533. _this.majorUnitFrequency = 10;
  76534. /**
  76535. * The visibility of minor units in the grid.
  76536. */
  76537. _this.minorUnitVisibility = 0.33;
  76538. /**
  76539. * The grid opacity outside of the lines.
  76540. */
  76541. _this.opacity = 1.0;
  76542. /**
  76543. * Determine RBG output is premultiplied by alpha value.
  76544. */
  76545. _this.preMultiplyAlpha = false;
  76546. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  76547. return _this;
  76548. }
  76549. /**
  76550. * Returns wehter or not the grid requires alpha blending.
  76551. */
  76552. GridMaterial.prototype.needAlphaBlending = function () {
  76553. return this.opacity < 1.0;
  76554. };
  76555. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  76556. if (this.isFrozen) {
  76557. if (this._wasPreviouslyReady && subMesh.effect) {
  76558. return true;
  76559. }
  76560. }
  76561. if (!subMesh._materialDefines) {
  76562. subMesh._materialDefines = new GridMaterialDefines();
  76563. }
  76564. var defines = subMesh._materialDefines;
  76565. var scene = this.getScene();
  76566. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  76567. if (this._renderId === scene.getRenderId()) {
  76568. return true;
  76569. }
  76570. }
  76571. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  76572. defines.TRANSPARENT = !defines.TRANSPARENT;
  76573. defines.markAsUnprocessed();
  76574. }
  76575. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  76576. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  76577. defines.markAsUnprocessed();
  76578. }
  76579. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  76580. // Get correct effect
  76581. if (defines.isDirty) {
  76582. defines.markAsProcessed();
  76583. scene.resetCachedMaterial();
  76584. // Attributes
  76585. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76586. // Defines
  76587. var join = defines.toString();
  76588. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  76589. }
  76590. if (!subMesh.effect || !subMesh.effect.isReady()) {
  76591. return false;
  76592. }
  76593. this._renderId = scene.getRenderId();
  76594. this._wasPreviouslyReady = true;
  76595. return true;
  76596. };
  76597. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  76598. var scene = this.getScene();
  76599. var defines = subMesh._materialDefines;
  76600. if (!defines) {
  76601. return;
  76602. }
  76603. var effect = subMesh.effect;
  76604. if (!effect) {
  76605. return;
  76606. }
  76607. this._activeEffect = effect;
  76608. // Matrices
  76609. this.bindOnlyWorldMatrix(world);
  76610. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  76611. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  76612. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  76613. // Uniforms
  76614. if (this._mustRebind(scene, effect)) {
  76615. this._activeEffect.setColor3("mainColor", this.mainColor);
  76616. this._activeEffect.setColor3("lineColor", this.lineColor);
  76617. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  76618. this._gridControl.x = this.gridRatio;
  76619. this._gridControl.y = Math.round(this.majorUnitFrequency);
  76620. this._gridControl.z = this.minorUnitVisibility;
  76621. this._gridControl.w = this.opacity;
  76622. this._activeEffect.setVector4("gridControl", this._gridControl);
  76623. }
  76624. // Fog
  76625. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  76626. this._afterBind(mesh, this._activeEffect);
  76627. };
  76628. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  76629. _super.prototype.dispose.call(this, forceDisposeEffect);
  76630. };
  76631. GridMaterial.prototype.clone = function (name) {
  76632. var _this = this;
  76633. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  76634. };
  76635. GridMaterial.prototype.serialize = function () {
  76636. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76637. serializationObject.customType = "BABYLON.GridMaterial";
  76638. return serializationObject;
  76639. };
  76640. GridMaterial.prototype.getClassName = function () {
  76641. return "GridMaterial";
  76642. };
  76643. GridMaterial.Parse = function (source, scene, rootUrl) {
  76644. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  76645. };
  76646. __decorate([
  76647. BABYLON.serializeAsColor3()
  76648. ], GridMaterial.prototype, "mainColor", void 0);
  76649. __decorate([
  76650. BABYLON.serializeAsColor3()
  76651. ], GridMaterial.prototype, "lineColor", void 0);
  76652. __decorate([
  76653. BABYLON.serialize()
  76654. ], GridMaterial.prototype, "gridRatio", void 0);
  76655. __decorate([
  76656. BABYLON.serializeAsColor3()
  76657. ], GridMaterial.prototype, "gridOffset", void 0);
  76658. __decorate([
  76659. BABYLON.serialize()
  76660. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  76661. __decorate([
  76662. BABYLON.serialize()
  76663. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  76664. __decorate([
  76665. BABYLON.serialize()
  76666. ], GridMaterial.prototype, "opacity", void 0);
  76667. __decorate([
  76668. BABYLON.serialize()
  76669. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  76670. return GridMaterial;
  76671. }(BABYLON.PushMaterial));
  76672. BABYLON.GridMaterial = GridMaterial;
  76673. })(BABYLON || (BABYLON = {}));
  76674. //# sourceMappingURL=babylon.gridmaterial.js.map
  76675. 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}";
  76676. 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}";
  76677. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  76678. var BABYLON;
  76679. (function (BABYLON) {
  76680. var GLTFLoaderCoordinateSystemMode;
  76681. (function (GLTFLoaderCoordinateSystemMode) {
  76682. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  76683. // 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.
  76684. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  76685. // The glTF right-handed data is not transformed in any form and is loaded directly.
  76686. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  76687. // Sets the useRightHandedSystem flag on the scene.
  76688. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  76689. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  76690. var GLTFFileLoader = /** @class */ (function () {
  76691. function GLTFFileLoader() {
  76692. // V2 options
  76693. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  76694. this.name = "gltf";
  76695. this.extensions = {
  76696. ".gltf": { isBinary: false },
  76697. ".glb": { isBinary: true }
  76698. };
  76699. }
  76700. GLTFFileLoader.prototype.dispose = function () {
  76701. if (this._loader) {
  76702. this._loader.dispose();
  76703. }
  76704. };
  76705. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  76706. try {
  76707. var loaderData = GLTFFileLoader._parse(data);
  76708. if (this.onParsed) {
  76709. this.onParsed(loaderData);
  76710. }
  76711. this._loader = this._getLoader(loaderData);
  76712. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  76713. }
  76714. catch (e) {
  76715. onError(e.message);
  76716. }
  76717. };
  76718. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  76719. try {
  76720. var loaderData = GLTFFileLoader._parse(data);
  76721. if (this.onParsed) {
  76722. this.onParsed(loaderData);
  76723. }
  76724. this._loader = this._getLoader(loaderData);
  76725. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  76726. }
  76727. catch (e) {
  76728. onError(e.message);
  76729. }
  76730. };
  76731. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  76732. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  76733. };
  76734. GLTFFileLoader._parse = function (data) {
  76735. if (data instanceof ArrayBuffer) {
  76736. return GLTFFileLoader._parseBinary(data);
  76737. }
  76738. return {
  76739. json: JSON.parse(data),
  76740. bin: null
  76741. };
  76742. };
  76743. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  76744. var loaderVersion = { major: 2, minor: 0 };
  76745. var asset = loaderData.json.asset || {};
  76746. var version = GLTFFileLoader._parseVersion(asset.version);
  76747. if (!version) {
  76748. throw new Error("Invalid version: " + asset.version);
  76749. }
  76750. if (asset.minVersion !== undefined) {
  76751. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  76752. if (!minVersion) {
  76753. throw new Error("Invalid minimum version: " + asset.minVersion);
  76754. }
  76755. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  76756. throw new Error("Incompatible minimum version: " + asset.minVersion);
  76757. }
  76758. }
  76759. var createLoaders = {
  76760. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  76761. 2: GLTFFileLoader.CreateGLTFLoaderV2
  76762. };
  76763. var createLoader = createLoaders[version.major];
  76764. if (!createLoader) {
  76765. throw new Error("Unsupported version: " + asset.version);
  76766. }
  76767. return createLoader(this);
  76768. };
  76769. GLTFFileLoader._parseBinary = function (data) {
  76770. var Binary = {
  76771. Magic: 0x46546C67
  76772. };
  76773. var binaryReader = new BinaryReader(data);
  76774. var magic = binaryReader.readUint32();
  76775. if (magic !== Binary.Magic) {
  76776. throw new Error("Unexpected magic: " + magic);
  76777. }
  76778. var version = binaryReader.readUint32();
  76779. switch (version) {
  76780. case 1: return GLTFFileLoader._parseV1(binaryReader);
  76781. case 2: return GLTFFileLoader._parseV2(binaryReader);
  76782. }
  76783. throw new Error("Unsupported version: " + version);
  76784. };
  76785. GLTFFileLoader._parseV1 = function (binaryReader) {
  76786. var ContentFormat = {
  76787. JSON: 0
  76788. };
  76789. var length = binaryReader.readUint32();
  76790. if (length != binaryReader.getLength()) {
  76791. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  76792. }
  76793. var contentLength = binaryReader.readUint32();
  76794. var contentFormat = binaryReader.readUint32();
  76795. var content;
  76796. switch (contentFormat) {
  76797. case ContentFormat.JSON: {
  76798. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  76799. break;
  76800. }
  76801. default: {
  76802. throw new Error("Unexpected content format: " + contentFormat);
  76803. }
  76804. }
  76805. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  76806. var body = binaryReader.readUint8Array(bytesRemaining);
  76807. return {
  76808. json: content,
  76809. bin: body
  76810. };
  76811. };
  76812. GLTFFileLoader._parseV2 = function (binaryReader) {
  76813. var ChunkFormat = {
  76814. JSON: 0x4E4F534A,
  76815. BIN: 0x004E4942
  76816. };
  76817. var length = binaryReader.readUint32();
  76818. if (length !== binaryReader.getLength()) {
  76819. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  76820. }
  76821. // JSON chunk
  76822. var chunkLength = binaryReader.readUint32();
  76823. var chunkFormat = binaryReader.readUint32();
  76824. if (chunkFormat !== ChunkFormat.JSON) {
  76825. throw new Error("First chunk format is not JSON");
  76826. }
  76827. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  76828. // Look for BIN chunk
  76829. var bin = null;
  76830. while (binaryReader.getPosition() < binaryReader.getLength()) {
  76831. var chunkLength_1 = binaryReader.readUint32();
  76832. var chunkFormat_1 = binaryReader.readUint32();
  76833. switch (chunkFormat_1) {
  76834. case ChunkFormat.JSON: {
  76835. throw new Error("Unexpected JSON chunk");
  76836. }
  76837. case ChunkFormat.BIN: {
  76838. bin = binaryReader.readUint8Array(chunkLength_1);
  76839. break;
  76840. }
  76841. default: {
  76842. // ignore unrecognized chunkFormat
  76843. binaryReader.skipBytes(chunkLength_1);
  76844. break;
  76845. }
  76846. }
  76847. }
  76848. return {
  76849. json: json,
  76850. bin: bin
  76851. };
  76852. };
  76853. GLTFFileLoader._parseVersion = function (version) {
  76854. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  76855. if (!match) {
  76856. return null;
  76857. }
  76858. return {
  76859. major: parseInt(match[1]),
  76860. minor: parseInt(match[2])
  76861. };
  76862. };
  76863. GLTFFileLoader._compareVersion = function (a, b) {
  76864. if (a.major > b.major)
  76865. return 1;
  76866. if (a.major < b.major)
  76867. return -1;
  76868. if (a.minor > b.minor)
  76869. return 1;
  76870. if (a.minor < b.minor)
  76871. return -1;
  76872. return 0;
  76873. };
  76874. GLTFFileLoader._decodeBufferToText = function (buffer) {
  76875. var result = "";
  76876. var length = buffer.byteLength;
  76877. for (var i = 0; i < length; i++) {
  76878. result += String.fromCharCode(buffer[i]);
  76879. }
  76880. return result;
  76881. };
  76882. // V1 options
  76883. GLTFFileLoader.HomogeneousCoordinates = false;
  76884. GLTFFileLoader.IncrementalLoading = true;
  76885. return GLTFFileLoader;
  76886. }());
  76887. BABYLON.GLTFFileLoader = GLTFFileLoader;
  76888. var BinaryReader = /** @class */ (function () {
  76889. function BinaryReader(arrayBuffer) {
  76890. this._arrayBuffer = arrayBuffer;
  76891. this._dataView = new DataView(arrayBuffer);
  76892. this._byteOffset = 0;
  76893. }
  76894. BinaryReader.prototype.getPosition = function () {
  76895. return this._byteOffset;
  76896. };
  76897. BinaryReader.prototype.getLength = function () {
  76898. return this._arrayBuffer.byteLength;
  76899. };
  76900. BinaryReader.prototype.readUint32 = function () {
  76901. var value = this._dataView.getUint32(this._byteOffset, true);
  76902. this._byteOffset += 4;
  76903. return value;
  76904. };
  76905. BinaryReader.prototype.readUint8Array = function (length) {
  76906. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  76907. this._byteOffset += length;
  76908. return value;
  76909. };
  76910. BinaryReader.prototype.skipBytes = function (length) {
  76911. this._byteOffset += length;
  76912. };
  76913. return BinaryReader;
  76914. }());
  76915. if (BABYLON.SceneLoader) {
  76916. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  76917. }
  76918. })(BABYLON || (BABYLON = {}));
  76919. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  76920. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76921. var BABYLON;
  76922. (function (BABYLON) {
  76923. var GLTF1;
  76924. (function (GLTF1) {
  76925. /**
  76926. * Enums
  76927. */
  76928. var EComponentType;
  76929. (function (EComponentType) {
  76930. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  76931. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  76932. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  76933. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  76934. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  76935. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  76936. var EShaderType;
  76937. (function (EShaderType) {
  76938. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  76939. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  76940. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  76941. var EParameterType;
  76942. (function (EParameterType) {
  76943. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  76944. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  76945. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  76946. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  76947. EParameterType[EParameterType["INT"] = 5124] = "INT";
  76948. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  76949. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  76950. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  76951. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  76952. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  76953. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  76954. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  76955. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  76956. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  76957. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  76958. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  76959. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  76960. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  76961. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  76962. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  76963. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  76964. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  76965. var ETextureWrapMode;
  76966. (function (ETextureWrapMode) {
  76967. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  76968. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  76969. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  76970. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  76971. var ETextureFilterType;
  76972. (function (ETextureFilterType) {
  76973. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  76974. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  76975. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  76976. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  76977. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  76978. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  76979. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  76980. var ETextureFormat;
  76981. (function (ETextureFormat) {
  76982. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  76983. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  76984. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  76985. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  76986. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  76987. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  76988. var ECullingType;
  76989. (function (ECullingType) {
  76990. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  76991. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  76992. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  76993. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  76994. var EBlendingFunction;
  76995. (function (EBlendingFunction) {
  76996. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  76997. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  76998. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  76999. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  77000. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  77001. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  77002. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  77003. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  77004. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  77005. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  77006. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  77007. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  77008. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  77009. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  77010. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  77011. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  77012. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77013. })(BABYLON || (BABYLON = {}));
  77014. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  77015. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77016. var BABYLON;
  77017. (function (BABYLON) {
  77018. var GLTF1;
  77019. (function (GLTF1) {
  77020. /**
  77021. * Tokenizer. Used for shaders compatibility
  77022. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  77023. */
  77024. var ETokenType;
  77025. (function (ETokenType) {
  77026. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  77027. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  77028. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  77029. })(ETokenType || (ETokenType = {}));
  77030. var Tokenizer = /** @class */ (function () {
  77031. function Tokenizer(toParse) {
  77032. this._pos = 0;
  77033. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  77034. this._toParse = toParse;
  77035. this._maxPos = toParse.length;
  77036. }
  77037. Tokenizer.prototype.getNextToken = function () {
  77038. if (this.isEnd())
  77039. return ETokenType.END_OF_INPUT;
  77040. this.currentString = this.read();
  77041. this.currentToken = ETokenType.UNKNOWN;
  77042. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  77043. this.currentToken = ETokenType.IDENTIFIER;
  77044. this.currentIdentifier = this.currentString;
  77045. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  77046. this.currentIdentifier += this.currentString;
  77047. this.forward();
  77048. }
  77049. }
  77050. return this.currentToken;
  77051. };
  77052. Tokenizer.prototype.peek = function () {
  77053. return this._toParse[this._pos];
  77054. };
  77055. Tokenizer.prototype.read = function () {
  77056. return this._toParse[this._pos++];
  77057. };
  77058. Tokenizer.prototype.forward = function () {
  77059. this._pos++;
  77060. };
  77061. Tokenizer.prototype.isEnd = function () {
  77062. return this._pos >= this._maxPos;
  77063. };
  77064. return Tokenizer;
  77065. }());
  77066. /**
  77067. * Values
  77068. */
  77069. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  77070. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  77071. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  77072. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  77073. /**
  77074. * Parse
  77075. */
  77076. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  77077. for (var buf in parsedBuffers) {
  77078. var parsedBuffer = parsedBuffers[buf];
  77079. gltfRuntime.buffers[buf] = parsedBuffer;
  77080. gltfRuntime.buffersCount++;
  77081. }
  77082. };
  77083. var parseShaders = function (parsedShaders, gltfRuntime) {
  77084. for (var sha in parsedShaders) {
  77085. var parsedShader = parsedShaders[sha];
  77086. gltfRuntime.shaders[sha] = parsedShader;
  77087. gltfRuntime.shaderscount++;
  77088. }
  77089. };
  77090. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  77091. for (var object in parsedObjects) {
  77092. var parsedObject = parsedObjects[object];
  77093. gltfRuntime[runtimeProperty][object] = parsedObject;
  77094. }
  77095. };
  77096. /**
  77097. * Utils
  77098. */
  77099. var normalizeUVs = function (buffer) {
  77100. if (!buffer) {
  77101. return;
  77102. }
  77103. for (var i = 0; i < buffer.length / 2; i++) {
  77104. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  77105. }
  77106. };
  77107. var getAttribute = function (attributeParameter) {
  77108. if (attributeParameter.semantic === "NORMAL") {
  77109. return "normal";
  77110. }
  77111. else if (attributeParameter.semantic === "POSITION") {
  77112. return "position";
  77113. }
  77114. else if (attributeParameter.semantic === "JOINT") {
  77115. return "matricesIndices";
  77116. }
  77117. else if (attributeParameter.semantic === "WEIGHT") {
  77118. return "matricesWeights";
  77119. }
  77120. else if (attributeParameter.semantic === "COLOR") {
  77121. return "color";
  77122. }
  77123. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  77124. var channel = Number(attributeParameter.semantic.split("_")[1]);
  77125. return "uv" + (channel === 0 ? "" : channel + 1);
  77126. }
  77127. return null;
  77128. };
  77129. /**
  77130. * Loads and creates animations
  77131. */
  77132. var loadAnimations = function (gltfRuntime) {
  77133. for (var anim in gltfRuntime.animations) {
  77134. var animation = gltfRuntime.animations[anim];
  77135. if (!animation.channels || !animation.samplers) {
  77136. continue;
  77137. }
  77138. var lastAnimation = null;
  77139. for (var i = 0; i < animation.channels.length; i++) {
  77140. // Get parameters and load buffers
  77141. var channel = animation.channels[i];
  77142. var sampler = animation.samplers[channel.sampler];
  77143. if (!sampler) {
  77144. continue;
  77145. }
  77146. var inputData = null;
  77147. var outputData = null;
  77148. if (animation.parameters) {
  77149. inputData = animation.parameters[sampler.input];
  77150. outputData = animation.parameters[sampler.output];
  77151. }
  77152. else {
  77153. inputData = sampler.input;
  77154. outputData = sampler.output;
  77155. }
  77156. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  77157. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  77158. var targetID = channel.target.id;
  77159. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  77160. if (targetNode === null) {
  77161. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  77162. }
  77163. if (targetNode === null) {
  77164. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  77165. continue;
  77166. }
  77167. var isBone = targetNode instanceof BABYLON.Bone;
  77168. // Get target path (position, rotation or scaling)
  77169. var targetPath = channel.target.path;
  77170. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  77171. if (targetPathIndex !== -1) {
  77172. targetPath = babylonAnimationPaths[targetPathIndex];
  77173. }
  77174. // Determine animation type
  77175. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  77176. if (!isBone) {
  77177. if (targetPath === "rotationQuaternion") {
  77178. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  77179. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  77180. }
  77181. else {
  77182. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  77183. }
  77184. }
  77185. // Create animation and key frames
  77186. var babylonAnimation = null;
  77187. var keys = [];
  77188. var arrayOffset = 0;
  77189. var modifyKey = false;
  77190. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  77191. babylonAnimation = lastAnimation;
  77192. modifyKey = true;
  77193. }
  77194. if (!modifyKey) {
  77195. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  77196. }
  77197. // For each frame
  77198. for (var j = 0; j < bufferInput.length; j++) {
  77199. var value = null;
  77200. if (targetPath === "rotationQuaternion") {
  77201. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  77202. arrayOffset += 4;
  77203. }
  77204. else {
  77205. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  77206. arrayOffset += 3;
  77207. }
  77208. if (isBone) {
  77209. var bone = targetNode;
  77210. var translation = BABYLON.Vector3.Zero();
  77211. var rotationQuaternion = new BABYLON.Quaternion();
  77212. var scaling = BABYLON.Vector3.Zero();
  77213. // Warning on decompose
  77214. var mat = bone.getBaseMatrix();
  77215. if (modifyKey && lastAnimation) {
  77216. mat = lastAnimation.getKeys()[j].value;
  77217. }
  77218. mat.decompose(scaling, rotationQuaternion, translation);
  77219. if (targetPath === "position") {
  77220. translation = value;
  77221. }
  77222. else if (targetPath === "rotationQuaternion") {
  77223. rotationQuaternion = value;
  77224. }
  77225. else {
  77226. scaling = value;
  77227. }
  77228. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  77229. }
  77230. if (!modifyKey) {
  77231. keys.push({
  77232. frame: bufferInput[j],
  77233. value: value
  77234. });
  77235. }
  77236. else if (lastAnimation) {
  77237. lastAnimation.getKeys()[j].value = value;
  77238. }
  77239. }
  77240. // Finish
  77241. if (!modifyKey && babylonAnimation) {
  77242. babylonAnimation.setKeys(keys);
  77243. targetNode.animations.push(babylonAnimation);
  77244. }
  77245. lastAnimation = babylonAnimation;
  77246. gltfRuntime.scene.stopAnimation(targetNode);
  77247. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  77248. }
  77249. }
  77250. };
  77251. /**
  77252. * Returns the bones transformation matrix
  77253. */
  77254. var configureBoneTransformation = function (node) {
  77255. var mat = null;
  77256. if (node.translation || node.rotation || node.scale) {
  77257. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  77258. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  77259. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  77260. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  77261. }
  77262. else {
  77263. mat = BABYLON.Matrix.FromArray(node.matrix);
  77264. }
  77265. return mat;
  77266. };
  77267. /**
  77268. * Returns the parent bone
  77269. */
  77270. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  77271. // Try to find
  77272. for (var i = 0; i < newSkeleton.bones.length; i++) {
  77273. if (newSkeleton.bones[i].name === jointName) {
  77274. return newSkeleton.bones[i];
  77275. }
  77276. }
  77277. // Not found, search in gltf nodes
  77278. var nodes = gltfRuntime.nodes;
  77279. for (var nde in nodes) {
  77280. var node = nodes[nde];
  77281. if (!node.jointName) {
  77282. continue;
  77283. }
  77284. var children = node.children;
  77285. for (var i = 0; i < children.length; i++) {
  77286. var child = gltfRuntime.nodes[children[i]];
  77287. if (!child.jointName) {
  77288. continue;
  77289. }
  77290. if (child.jointName === jointName) {
  77291. var mat = configureBoneTransformation(node);
  77292. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  77293. bone.id = nde;
  77294. return bone;
  77295. }
  77296. }
  77297. }
  77298. return null;
  77299. };
  77300. /**
  77301. * Returns the appropriate root node
  77302. */
  77303. var getNodeToRoot = function (nodesToRoot, id) {
  77304. for (var i = 0; i < nodesToRoot.length; i++) {
  77305. var nodeToRoot = nodesToRoot[i];
  77306. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  77307. var child = nodeToRoot.node.children[j];
  77308. if (child === id) {
  77309. return nodeToRoot.bone;
  77310. }
  77311. }
  77312. }
  77313. return null;
  77314. };
  77315. /**
  77316. * Returns the node with the joint name
  77317. */
  77318. var getJointNode = function (gltfRuntime, jointName) {
  77319. var nodes = gltfRuntime.nodes;
  77320. var node = nodes[jointName];
  77321. if (node) {
  77322. return {
  77323. node: node,
  77324. id: jointName
  77325. };
  77326. }
  77327. for (var nde in nodes) {
  77328. node = nodes[nde];
  77329. if (node.jointName === jointName) {
  77330. return {
  77331. node: node,
  77332. id: nde
  77333. };
  77334. }
  77335. }
  77336. return null;
  77337. };
  77338. /**
  77339. * Checks if a nodes is in joints
  77340. */
  77341. var nodeIsInJoints = function (skins, id) {
  77342. for (var i = 0; i < skins.jointNames.length; i++) {
  77343. if (skins.jointNames[i] === id) {
  77344. return true;
  77345. }
  77346. }
  77347. return false;
  77348. };
  77349. /**
  77350. * Fills the nodes to root for bones and builds hierarchy
  77351. */
  77352. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  77353. // Creates nodes for root
  77354. for (var nde in gltfRuntime.nodes) {
  77355. var node = gltfRuntime.nodes[nde];
  77356. var id = nde;
  77357. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  77358. continue;
  77359. }
  77360. // Create node to root bone
  77361. var mat = configureBoneTransformation(node);
  77362. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  77363. bone.id = id;
  77364. nodesToRoot.push({ bone: bone, node: node, id: id });
  77365. }
  77366. // Parenting
  77367. for (var i = 0; i < nodesToRoot.length; i++) {
  77368. var nodeToRoot = nodesToRoot[i];
  77369. var children = nodeToRoot.node.children;
  77370. for (var j = 0; j < children.length; j++) {
  77371. var child = null;
  77372. for (var k = 0; k < nodesToRoot.length; k++) {
  77373. if (nodesToRoot[k].id === children[j]) {
  77374. child = nodesToRoot[k];
  77375. break;
  77376. }
  77377. }
  77378. if (child) {
  77379. child.bone._parent = nodeToRoot.bone;
  77380. nodeToRoot.bone.children.push(child.bone);
  77381. }
  77382. }
  77383. }
  77384. };
  77385. /**
  77386. * Imports a skeleton
  77387. */
  77388. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  77389. if (!newSkeleton) {
  77390. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  77391. }
  77392. if (!skins.babylonSkeleton) {
  77393. return newSkeleton;
  77394. }
  77395. // Find the root bones
  77396. var nodesToRoot = [];
  77397. var nodesToRootToAdd = [];
  77398. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  77399. newSkeleton.bones = [];
  77400. // Joints
  77401. for (var i = 0; i < skins.jointNames.length; i++) {
  77402. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  77403. if (!jointNode) {
  77404. continue;
  77405. }
  77406. var node = jointNode.node;
  77407. if (!node) {
  77408. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  77409. continue;
  77410. }
  77411. var id = jointNode.id;
  77412. // Optimize, if the bone already exists...
  77413. var existingBone = gltfRuntime.scene.getBoneByID(id);
  77414. if (existingBone) {
  77415. newSkeleton.bones.push(existingBone);
  77416. continue;
  77417. }
  77418. // Search for parent bone
  77419. var foundBone = false;
  77420. var parentBone = null;
  77421. for (var j = 0; j < i; j++) {
  77422. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  77423. if (!jointNode_1) {
  77424. continue;
  77425. }
  77426. var joint = jointNode_1.node;
  77427. if (!joint) {
  77428. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  77429. continue;
  77430. }
  77431. var children = joint.children;
  77432. if (!children) {
  77433. continue;
  77434. }
  77435. foundBone = false;
  77436. for (var k = 0; k < children.length; k++) {
  77437. if (children[k] === id) {
  77438. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  77439. foundBone = true;
  77440. break;
  77441. }
  77442. }
  77443. if (foundBone) {
  77444. break;
  77445. }
  77446. }
  77447. // Create bone
  77448. var mat = configureBoneTransformation(node);
  77449. if (!parentBone && nodesToRoot.length > 0) {
  77450. parentBone = getNodeToRoot(nodesToRoot, id);
  77451. if (parentBone) {
  77452. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  77453. nodesToRootToAdd.push(parentBone);
  77454. }
  77455. }
  77456. }
  77457. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  77458. bone.id = id;
  77459. }
  77460. // Polish
  77461. var bones = newSkeleton.bones;
  77462. newSkeleton.bones = [];
  77463. for (var i = 0; i < skins.jointNames.length; i++) {
  77464. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  77465. if (!jointNode) {
  77466. continue;
  77467. }
  77468. for (var j = 0; j < bones.length; j++) {
  77469. if (bones[j].id === jointNode.id) {
  77470. newSkeleton.bones.push(bones[j]);
  77471. break;
  77472. }
  77473. }
  77474. }
  77475. newSkeleton.prepare();
  77476. // Finish
  77477. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  77478. newSkeleton.bones.push(nodesToRootToAdd[i]);
  77479. }
  77480. return newSkeleton;
  77481. };
  77482. /**
  77483. * Imports a mesh and its geometries
  77484. */
  77485. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  77486. if (!newMesh) {
  77487. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  77488. newMesh.id = id;
  77489. }
  77490. if (!node.babylonNode) {
  77491. return newMesh;
  77492. }
  77493. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  77494. if (!newMesh.material) {
  77495. newMesh.material = multiMat;
  77496. }
  77497. var vertexData = new BABYLON.VertexData();
  77498. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  77499. var verticesStarts = new Array();
  77500. var verticesCounts = new Array();
  77501. var indexStarts = new Array();
  77502. var indexCounts = new Array();
  77503. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  77504. var meshID = meshes[meshIndex];
  77505. var mesh = gltfRuntime.meshes[meshID];
  77506. if (!mesh) {
  77507. continue;
  77508. }
  77509. // Positions, normals and UVs
  77510. for (var i = 0; i < mesh.primitives.length; i++) {
  77511. // Temporary vertex data
  77512. var tempVertexData = new BABYLON.VertexData();
  77513. var primitive = mesh.primitives[i];
  77514. if (primitive.mode !== 4) {
  77515. // continue;
  77516. }
  77517. var attributes = primitive.attributes;
  77518. var accessor = null;
  77519. var buffer = null;
  77520. // Set positions, normal and uvs
  77521. for (var semantic in attributes) {
  77522. // Link accessor and buffer view
  77523. accessor = gltfRuntime.accessors[attributes[semantic]];
  77524. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  77525. if (semantic === "NORMAL") {
  77526. tempVertexData.normals = new Float32Array(buffer.length);
  77527. tempVertexData.normals.set(buffer);
  77528. }
  77529. else if (semantic === "POSITION") {
  77530. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  77531. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  77532. for (var j = 0; j < buffer.length; j += 4) {
  77533. tempVertexData.positions[j] = buffer[j];
  77534. tempVertexData.positions[j + 1] = buffer[j + 1];
  77535. tempVertexData.positions[j + 2] = buffer[j + 2];
  77536. }
  77537. }
  77538. else {
  77539. tempVertexData.positions = new Float32Array(buffer.length);
  77540. tempVertexData.positions.set(buffer);
  77541. }
  77542. verticesCounts.push(tempVertexData.positions.length);
  77543. }
  77544. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  77545. var channel = Number(semantic.split("_")[1]);
  77546. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  77547. var uvs = new Float32Array(buffer.length);
  77548. uvs.set(buffer);
  77549. normalizeUVs(uvs);
  77550. tempVertexData.set(uvs, uvKind);
  77551. }
  77552. else if (semantic === "JOINT") {
  77553. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  77554. tempVertexData.matricesIndices.set(buffer);
  77555. }
  77556. else if (semantic === "WEIGHT") {
  77557. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  77558. tempVertexData.matricesWeights.set(buffer);
  77559. }
  77560. else if (semantic === "COLOR") {
  77561. tempVertexData.colors = new Float32Array(buffer.length);
  77562. tempVertexData.colors.set(buffer);
  77563. }
  77564. }
  77565. // Indices
  77566. accessor = gltfRuntime.accessors[primitive.indices];
  77567. if (accessor) {
  77568. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  77569. tempVertexData.indices = new Int32Array(buffer.length);
  77570. tempVertexData.indices.set(buffer);
  77571. indexCounts.push(tempVertexData.indices.length);
  77572. }
  77573. else {
  77574. // Set indices on the fly
  77575. var indices = [];
  77576. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  77577. indices.push(j);
  77578. }
  77579. tempVertexData.indices = new Int32Array(indices);
  77580. indexCounts.push(tempVertexData.indices.length);
  77581. }
  77582. vertexData.merge(tempVertexData);
  77583. // Sub material
  77584. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  77585. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  77586. // Update vertices start and index start
  77587. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  77588. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  77589. }
  77590. }
  77591. // Apply geometry
  77592. geometry.setAllVerticesData(vertexData, false);
  77593. newMesh.computeWorldMatrix(true);
  77594. // Apply submeshes
  77595. newMesh.subMeshes = [];
  77596. var index = 0;
  77597. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  77598. var meshID = meshes[meshIndex];
  77599. var mesh = gltfRuntime.meshes[meshID];
  77600. if (!mesh) {
  77601. continue;
  77602. }
  77603. for (var i = 0; i < mesh.primitives.length; i++) {
  77604. if (mesh.primitives[i].mode !== 4) {
  77605. //continue;
  77606. }
  77607. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  77608. index++;
  77609. }
  77610. }
  77611. // Finish
  77612. return newMesh;
  77613. };
  77614. /**
  77615. * Configure node transformation from position, rotation and scaling
  77616. */
  77617. var configureNode = function (newNode, position, rotation, scaling) {
  77618. if (newNode.position) {
  77619. newNode.position = position;
  77620. }
  77621. if (newNode.rotationQuaternion || newNode.rotation) {
  77622. newNode.rotationQuaternion = rotation;
  77623. }
  77624. if (newNode.scaling) {
  77625. newNode.scaling = scaling;
  77626. }
  77627. };
  77628. /**
  77629. * Configures node from transformation matrix
  77630. */
  77631. var configureNodeFromMatrix = function (newNode, node, parent) {
  77632. if (node.matrix) {
  77633. var position = new BABYLON.Vector3(0, 0, 0);
  77634. var rotation = new BABYLON.Quaternion();
  77635. var scaling = new BABYLON.Vector3(0, 0, 0);
  77636. var mat = BABYLON.Matrix.FromArray(node.matrix);
  77637. mat.decompose(scaling, rotation, position);
  77638. configureNode(newNode, position, rotation, scaling);
  77639. }
  77640. else if (node.translation && node.rotation && node.scale) {
  77641. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  77642. }
  77643. newNode.computeWorldMatrix(true);
  77644. };
  77645. /**
  77646. * Imports a node
  77647. */
  77648. var importNode = function (gltfRuntime, node, id, parent) {
  77649. var lastNode = null;
  77650. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  77651. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  77652. return null;
  77653. }
  77654. }
  77655. // Meshes
  77656. if (node.skin) {
  77657. if (node.meshes) {
  77658. var skin = gltfRuntime.skins[node.skin];
  77659. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  77660. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  77661. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  77662. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  77663. if (!skin.babylonSkeleton) {
  77664. skin.babylonSkeleton = newMesh.skeleton;
  77665. }
  77666. }
  77667. lastNode = newMesh;
  77668. }
  77669. }
  77670. else if (node.meshes) {
  77671. /**
  77672. * Improve meshes property
  77673. */
  77674. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  77675. lastNode = newMesh;
  77676. }
  77677. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  77678. var light = gltfRuntime.lights[node.light];
  77679. if (light) {
  77680. if (light.type === "ambient") {
  77681. var ambienLight = light[light.type];
  77682. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77683. hemiLight.name = node.name || "";
  77684. if (ambienLight.color) {
  77685. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  77686. }
  77687. lastNode = hemiLight;
  77688. }
  77689. else if (light.type === "directional") {
  77690. var directionalLight = light[light.type];
  77691. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77692. dirLight.name = node.name || "";
  77693. if (directionalLight.color) {
  77694. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  77695. }
  77696. lastNode = dirLight;
  77697. }
  77698. else if (light.type === "point") {
  77699. var pointLight = light[light.type];
  77700. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77701. ptLight.name = node.name || "";
  77702. if (pointLight.color) {
  77703. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  77704. }
  77705. lastNode = ptLight;
  77706. }
  77707. else if (light.type === "spot") {
  77708. var spotLight = light[light.type];
  77709. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  77710. spLight.name = node.name || "";
  77711. if (spotLight.color) {
  77712. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  77713. }
  77714. if (spotLight.fallOfAngle) {
  77715. spLight.angle = spotLight.fallOfAngle;
  77716. }
  77717. if (spotLight.fallOffExponent) {
  77718. spLight.exponent = spotLight.fallOffExponent;
  77719. }
  77720. lastNode = spLight;
  77721. }
  77722. }
  77723. }
  77724. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  77725. var camera = gltfRuntime.cameras[node.camera];
  77726. if (camera) {
  77727. if (camera.type === "orthographic") {
  77728. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77729. orthoCamera.name = node.name || "";
  77730. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  77731. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  77732. lastNode = orthoCamera;
  77733. }
  77734. else if (camera.type === "perspective") {
  77735. var perspectiveCamera = camera[camera.type];
  77736. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77737. persCamera.name = node.name || "";
  77738. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  77739. if (!perspectiveCamera.aspectRatio) {
  77740. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  77741. }
  77742. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  77743. persCamera.maxZ = perspectiveCamera.zfar;
  77744. persCamera.minZ = perspectiveCamera.znear;
  77745. }
  77746. lastNode = persCamera;
  77747. }
  77748. }
  77749. }
  77750. // Empty node
  77751. if (!node.jointName) {
  77752. if (node.babylonNode) {
  77753. return node.babylonNode;
  77754. }
  77755. else if (lastNode === null) {
  77756. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  77757. node.babylonNode = dummy;
  77758. lastNode = dummy;
  77759. }
  77760. }
  77761. if (lastNode !== null) {
  77762. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  77763. configureNodeFromMatrix(lastNode, node, parent);
  77764. }
  77765. else {
  77766. var translation = node.translation || [0, 0, 0];
  77767. var rotation = node.rotation || [0, 0, 0, 1];
  77768. var scale = node.scale || [1, 1, 1];
  77769. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  77770. }
  77771. lastNode.updateCache(true);
  77772. node.babylonNode = lastNode;
  77773. }
  77774. return lastNode;
  77775. };
  77776. /**
  77777. * Traverses nodes and creates them
  77778. */
  77779. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  77780. if (meshIncluded === void 0) { meshIncluded = false; }
  77781. var node = gltfRuntime.nodes[id];
  77782. var newNode = null;
  77783. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  77784. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  77785. meshIncluded = true;
  77786. }
  77787. else {
  77788. meshIncluded = false;
  77789. }
  77790. }
  77791. else {
  77792. meshIncluded = true;
  77793. }
  77794. if (!node.jointName && meshIncluded) {
  77795. newNode = importNode(gltfRuntime, node, id, parent);
  77796. if (newNode !== null) {
  77797. newNode.id = id;
  77798. newNode.parent = parent;
  77799. }
  77800. }
  77801. if (node.children) {
  77802. for (var i = 0; i < node.children.length; i++) {
  77803. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  77804. }
  77805. }
  77806. };
  77807. /**
  77808. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  77809. */
  77810. var postLoad = function (gltfRuntime) {
  77811. // Nodes
  77812. var currentScene = gltfRuntime.currentScene;
  77813. if (currentScene) {
  77814. for (var i = 0; i < currentScene.nodes.length; i++) {
  77815. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77816. }
  77817. }
  77818. else {
  77819. for (var thing in gltfRuntime.scenes) {
  77820. currentScene = gltfRuntime.scenes[thing];
  77821. for (var i = 0; i < currentScene.nodes.length; i++) {
  77822. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77823. }
  77824. }
  77825. }
  77826. // Set animations
  77827. loadAnimations(gltfRuntime);
  77828. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  77829. var skeleton = gltfRuntime.scene.skeletons[i];
  77830. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  77831. }
  77832. };
  77833. /**
  77834. * onBind shaderrs callback to set uniforms and matrices
  77835. */
  77836. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  77837. var materialValues = material.values || technique.parameters;
  77838. for (var unif in unTreatedUniforms) {
  77839. var uniform = unTreatedUniforms[unif];
  77840. var type = uniform.type;
  77841. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  77842. if (uniform.semantic && !uniform.source && !uniform.node) {
  77843. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  77844. }
  77845. else if (uniform.semantic && (uniform.source || uniform.node)) {
  77846. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  77847. if (source === null) {
  77848. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  77849. }
  77850. if (source === null) {
  77851. continue;
  77852. }
  77853. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  77854. }
  77855. }
  77856. else {
  77857. var value = materialValues[technique.uniforms[unif]];
  77858. if (!value) {
  77859. continue;
  77860. }
  77861. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  77862. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  77863. if (texture === null || texture === undefined) {
  77864. continue;
  77865. }
  77866. shaderMaterial.getEffect().setTexture(unif, texture);
  77867. }
  77868. else {
  77869. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  77870. }
  77871. }
  77872. }
  77873. onSuccess(shaderMaterial);
  77874. };
  77875. /**
  77876. * Prepare uniforms to send the only one time
  77877. * Loads the appropriate textures
  77878. */
  77879. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  77880. var materialValues = material.values || technique.parameters;
  77881. var techniqueUniforms = technique.uniforms;
  77882. /**
  77883. * Prepare values here (not matrices)
  77884. */
  77885. for (var unif in unTreatedUniforms) {
  77886. var uniform = unTreatedUniforms[unif];
  77887. var type = uniform.type;
  77888. var value = materialValues[techniqueUniforms[unif]];
  77889. if (value === undefined) {
  77890. // In case the value is the same for all materials
  77891. value = uniform.value;
  77892. }
  77893. if (!value) {
  77894. continue;
  77895. }
  77896. var onLoadTexture = function (uniformName) {
  77897. return function (texture) {
  77898. if (uniform.value && uniformName) {
  77899. // Static uniform
  77900. shaderMaterial.setTexture(uniformName, texture);
  77901. delete unTreatedUniforms[uniformName];
  77902. }
  77903. };
  77904. };
  77905. // Texture (sampler2D)
  77906. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  77907. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  77908. }
  77909. else {
  77910. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  77911. // Static uniform
  77912. delete unTreatedUniforms[unif];
  77913. }
  77914. }
  77915. }
  77916. };
  77917. /**
  77918. * Shader compilation failed
  77919. */
  77920. var onShaderCompileError = function (program, shaderMaterial, onError) {
  77921. return function (effect, error) {
  77922. shaderMaterial.dispose(true);
  77923. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  77924. };
  77925. };
  77926. /**
  77927. * Shader compilation success
  77928. */
  77929. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  77930. return function (_) {
  77931. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  77932. shaderMaterial.onBind = function (mesh) {
  77933. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  77934. };
  77935. };
  77936. };
  77937. /**
  77938. * Returns the appropriate uniform if already handled by babylon
  77939. */
  77940. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  77941. for (var unif in technique.uniforms) {
  77942. var uniform = technique.uniforms[unif];
  77943. var uniformParameter = technique.parameters[uniform];
  77944. if (tokenizer.currentIdentifier === unif) {
  77945. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  77946. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  77947. if (transformIndex !== -1) {
  77948. delete unTreatedUniforms[unif];
  77949. return babylonTransforms[transformIndex];
  77950. }
  77951. }
  77952. }
  77953. }
  77954. return tokenizer.currentIdentifier;
  77955. };
  77956. /**
  77957. * All shaders loaded. Create materials one by one
  77958. */
  77959. var importMaterials = function (gltfRuntime) {
  77960. // Create materials
  77961. for (var mat in gltfRuntime.materials) {
  77962. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  77963. }
  77964. };
  77965. /**
  77966. * Implementation of the base glTF spec
  77967. */
  77968. var GLTFLoaderBase = /** @class */ (function () {
  77969. function GLTFLoaderBase() {
  77970. }
  77971. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  77972. var gltfRuntime = {
  77973. extensions: {},
  77974. accessors: {},
  77975. buffers: {},
  77976. bufferViews: {},
  77977. meshes: {},
  77978. lights: {},
  77979. cameras: {},
  77980. nodes: {},
  77981. images: {},
  77982. textures: {},
  77983. shaders: {},
  77984. programs: {},
  77985. samplers: {},
  77986. techniques: {},
  77987. materials: {},
  77988. animations: {},
  77989. skins: {},
  77990. extensionsUsed: [],
  77991. scenes: {},
  77992. buffersCount: 0,
  77993. shaderscount: 0,
  77994. scene: scene,
  77995. rootUrl: rootUrl,
  77996. loadedBufferCount: 0,
  77997. loadedBufferViews: {},
  77998. loadedShaderCount: 0,
  77999. importOnlyMeshes: false,
  78000. dummyNodes: []
  78001. };
  78002. // Parse
  78003. if (parsedData.extensions) {
  78004. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  78005. }
  78006. if (parsedData.extensionsUsed) {
  78007. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  78008. }
  78009. if (parsedData.buffers) {
  78010. parseBuffers(parsedData.buffers, gltfRuntime);
  78011. }
  78012. if (parsedData.bufferViews) {
  78013. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  78014. }
  78015. if (parsedData.accessors) {
  78016. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  78017. }
  78018. if (parsedData.meshes) {
  78019. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  78020. }
  78021. if (parsedData.lights) {
  78022. parseObject(parsedData.lights, "lights", gltfRuntime);
  78023. }
  78024. if (parsedData.cameras) {
  78025. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  78026. }
  78027. if (parsedData.nodes) {
  78028. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  78029. }
  78030. if (parsedData.images) {
  78031. parseObject(parsedData.images, "images", gltfRuntime);
  78032. }
  78033. if (parsedData.textures) {
  78034. parseObject(parsedData.textures, "textures", gltfRuntime);
  78035. }
  78036. if (parsedData.shaders) {
  78037. parseShaders(parsedData.shaders, gltfRuntime);
  78038. }
  78039. if (parsedData.programs) {
  78040. parseObject(parsedData.programs, "programs", gltfRuntime);
  78041. }
  78042. if (parsedData.samplers) {
  78043. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  78044. }
  78045. if (parsedData.techniques) {
  78046. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  78047. }
  78048. if (parsedData.materials) {
  78049. parseObject(parsedData.materials, "materials", gltfRuntime);
  78050. }
  78051. if (parsedData.animations) {
  78052. parseObject(parsedData.animations, "animations", gltfRuntime);
  78053. }
  78054. if (parsedData.skins) {
  78055. parseObject(parsedData.skins, "skins", gltfRuntime);
  78056. }
  78057. if (parsedData.scenes) {
  78058. gltfRuntime.scenes = parsedData.scenes;
  78059. }
  78060. if (parsedData.scene && parsedData.scenes) {
  78061. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  78062. }
  78063. return gltfRuntime;
  78064. };
  78065. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  78066. var buffer = gltfRuntime.buffers[id];
  78067. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  78068. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  78069. }
  78070. else {
  78071. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  78072. if (request) {
  78073. onError(request.status + " " + request.statusText);
  78074. }
  78075. });
  78076. }
  78077. };
  78078. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78079. var texture = gltfRuntime.textures[id];
  78080. if (!texture || !texture.source) {
  78081. onError("");
  78082. return;
  78083. }
  78084. if (texture.babylonTexture) {
  78085. onSuccess(null);
  78086. return;
  78087. }
  78088. var source = gltfRuntime.images[texture.source];
  78089. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  78090. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  78091. }
  78092. else {
  78093. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  78094. if (request) {
  78095. onError(request.status + " " + request.statusText);
  78096. }
  78097. });
  78098. }
  78099. };
  78100. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  78101. var texture = gltfRuntime.textures[id];
  78102. if (texture.babylonTexture) {
  78103. onSuccess(texture.babylonTexture);
  78104. return;
  78105. }
  78106. var sampler = gltfRuntime.samplers[texture.sampler];
  78107. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  78108. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  78109. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  78110. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  78111. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  78112. var blob = new Blob([buffer]);
  78113. var blobURL = URL.createObjectURL(blob);
  78114. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  78115. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  78116. if (sampler.wrapS !== undefined) {
  78117. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  78118. }
  78119. if (sampler.wrapT !== undefined) {
  78120. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  78121. }
  78122. newTexture.name = id;
  78123. texture.babylonTexture = newTexture;
  78124. onSuccess(newTexture);
  78125. };
  78126. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78127. var shader = gltfRuntime.shaders[id];
  78128. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  78129. var shaderString = atob(shader.uri.split(",")[1]);
  78130. onSuccess(shaderString);
  78131. }
  78132. else {
  78133. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  78134. if (request) {
  78135. onError(request.status + " " + request.statusText);
  78136. }
  78137. });
  78138. }
  78139. };
  78140. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78141. var material = gltfRuntime.materials[id];
  78142. if (!material.technique) {
  78143. if (onError) {
  78144. onError("No technique found.");
  78145. }
  78146. return;
  78147. }
  78148. var technique = gltfRuntime.techniques[material.technique];
  78149. if (!technique) {
  78150. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  78151. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  78152. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78153. onSuccess(defaultMaterial);
  78154. return;
  78155. }
  78156. var program = gltfRuntime.programs[technique.program];
  78157. var states = technique.states;
  78158. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  78159. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  78160. var newVertexShader = "";
  78161. var newPixelShader = "";
  78162. var vertexTokenizer = new Tokenizer(vertexShader);
  78163. var pixelTokenizer = new Tokenizer(pixelShader);
  78164. var unTreatedUniforms = {};
  78165. var uniforms = [];
  78166. var attributes = [];
  78167. var samplers = [];
  78168. // Fill uniform, sampler2D and attributes
  78169. for (var unif in technique.uniforms) {
  78170. var uniform = technique.uniforms[unif];
  78171. var uniformParameter = technique.parameters[uniform];
  78172. unTreatedUniforms[unif] = uniformParameter;
  78173. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  78174. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  78175. if (transformIndex !== -1) {
  78176. uniforms.push(babylonTransforms[transformIndex]);
  78177. delete unTreatedUniforms[unif];
  78178. }
  78179. else {
  78180. uniforms.push(unif);
  78181. }
  78182. }
  78183. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  78184. samplers.push(unif);
  78185. }
  78186. else {
  78187. uniforms.push(unif);
  78188. }
  78189. }
  78190. for (var attr in technique.attributes) {
  78191. var attribute = technique.attributes[attr];
  78192. var attributeParameter = technique.parameters[attribute];
  78193. if (attributeParameter.semantic) {
  78194. attributes.push(getAttribute(attributeParameter));
  78195. }
  78196. }
  78197. // Configure vertex shader
  78198. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  78199. var tokenType = vertexTokenizer.currentToken;
  78200. if (tokenType !== ETokenType.IDENTIFIER) {
  78201. newVertexShader += vertexTokenizer.currentString;
  78202. continue;
  78203. }
  78204. var foundAttribute = false;
  78205. for (var attr in technique.attributes) {
  78206. var attribute = technique.attributes[attr];
  78207. var attributeParameter = technique.parameters[attribute];
  78208. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  78209. newVertexShader += getAttribute(attributeParameter);
  78210. foundAttribute = true;
  78211. break;
  78212. }
  78213. }
  78214. if (foundAttribute) {
  78215. continue;
  78216. }
  78217. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  78218. }
  78219. // Configure pixel shader
  78220. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  78221. var tokenType = pixelTokenizer.currentToken;
  78222. if (tokenType !== ETokenType.IDENTIFIER) {
  78223. newPixelShader += pixelTokenizer.currentString;
  78224. continue;
  78225. }
  78226. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  78227. }
  78228. // Create shader material
  78229. var shaderPath = {
  78230. vertex: program.vertexShader + id,
  78231. fragment: program.fragmentShader + id
  78232. };
  78233. var options = {
  78234. attributes: attributes,
  78235. uniforms: uniforms,
  78236. samplers: samplers,
  78237. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  78238. };
  78239. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  78240. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  78241. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  78242. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  78243. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  78244. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78245. if (states && states.functions) {
  78246. var functions = states.functions;
  78247. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  78248. shaderMaterial.backFaceCulling = false;
  78249. }
  78250. var blendFunc = functions.blendFuncSeparate;
  78251. if (blendFunc) {
  78252. 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) {
  78253. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  78254. }
  78255. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  78256. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  78257. }
  78258. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  78259. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  78260. }
  78261. 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) {
  78262. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  78263. }
  78264. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  78265. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  78266. }
  78267. 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) {
  78268. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  78269. }
  78270. }
  78271. }
  78272. };
  78273. return GLTFLoaderBase;
  78274. }());
  78275. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  78276. /**
  78277. * glTF V1 Loader
  78278. */
  78279. var GLTFLoader = /** @class */ (function () {
  78280. function GLTFLoader() {
  78281. }
  78282. GLTFLoader.RegisterExtension = function (extension) {
  78283. if (GLTFLoader.Extensions[extension.name]) {
  78284. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  78285. return;
  78286. }
  78287. GLTFLoader.Extensions[extension.name] = extension;
  78288. };
  78289. GLTFLoader.prototype.dispose = function () {
  78290. // do nothing
  78291. };
  78292. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78293. var _this = this;
  78294. scene.useRightHandedSystem = true;
  78295. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  78296. gltfRuntime.importOnlyMeshes = true;
  78297. if (meshesNames === "") {
  78298. gltfRuntime.importMeshesNames = [];
  78299. }
  78300. else if (typeof meshesNames === "string") {
  78301. gltfRuntime.importMeshesNames = [meshesNames];
  78302. }
  78303. else if (meshesNames && !(meshesNames instanceof Array)) {
  78304. gltfRuntime.importMeshesNames = [meshesNames];
  78305. }
  78306. else {
  78307. gltfRuntime.importMeshesNames = [];
  78308. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  78309. }
  78310. // Create nodes
  78311. _this._createNodes(gltfRuntime);
  78312. var meshes = new Array();
  78313. var skeletons = new Array();
  78314. // Fill arrays of meshes and skeletons
  78315. for (var nde in gltfRuntime.nodes) {
  78316. var node = gltfRuntime.nodes[nde];
  78317. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  78318. meshes.push(node.babylonNode);
  78319. }
  78320. }
  78321. for (var skl in gltfRuntime.skins) {
  78322. var skin = gltfRuntime.skins[skl];
  78323. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  78324. skeletons.push(skin.babylonSkeleton);
  78325. }
  78326. }
  78327. // Load buffers, shaders, materials, etc.
  78328. _this._loadBuffersAsync(gltfRuntime, function () {
  78329. _this._loadShadersAsync(gltfRuntime, function () {
  78330. importMaterials(gltfRuntime);
  78331. postLoad(gltfRuntime);
  78332. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  78333. onSuccess(meshes, [], skeletons);
  78334. }
  78335. });
  78336. }, onProgress);
  78337. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  78338. onSuccess(meshes, [], skeletons);
  78339. }
  78340. }, onError);
  78341. return true;
  78342. };
  78343. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  78344. var _this = this;
  78345. scene.useRightHandedSystem = true;
  78346. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  78347. // Load runtime extensios
  78348. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  78349. // Create nodes
  78350. _this._createNodes(gltfRuntime);
  78351. // Load buffers, shaders, materials, etc.
  78352. _this._loadBuffersAsync(gltfRuntime, function () {
  78353. _this._loadShadersAsync(gltfRuntime, function () {
  78354. importMaterials(gltfRuntime);
  78355. postLoad(gltfRuntime);
  78356. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  78357. onSuccess();
  78358. }
  78359. });
  78360. });
  78361. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  78362. onSuccess();
  78363. }
  78364. }, onError);
  78365. }, onError);
  78366. };
  78367. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  78368. var hasShaders = false;
  78369. var processShader = function (sha, shader) {
  78370. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  78371. gltfRuntime.loadedShaderCount++;
  78372. if (shaderString) {
  78373. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  78374. }
  78375. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  78376. onload();
  78377. }
  78378. }, function () {
  78379. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  78380. });
  78381. };
  78382. for (var sha in gltfRuntime.shaders) {
  78383. hasShaders = true;
  78384. var shader = gltfRuntime.shaders[sha];
  78385. if (shader) {
  78386. processShader.bind(this, sha, shader)();
  78387. }
  78388. else {
  78389. BABYLON.Tools.Error("No shader named: " + sha);
  78390. }
  78391. }
  78392. if (!hasShaders) {
  78393. onload();
  78394. }
  78395. };
  78396. ;
  78397. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  78398. var hasBuffers = false;
  78399. var processBuffer = function (buf, buffer) {
  78400. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  78401. gltfRuntime.loadedBufferCount++;
  78402. if (bufferView) {
  78403. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  78404. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  78405. }
  78406. gltfRuntime.loadedBufferViews[buf] = bufferView;
  78407. }
  78408. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  78409. onLoad();
  78410. }
  78411. }, function () {
  78412. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  78413. });
  78414. };
  78415. for (var buf in gltfRuntime.buffers) {
  78416. hasBuffers = true;
  78417. var buffer = gltfRuntime.buffers[buf];
  78418. if (buffer) {
  78419. processBuffer.bind(this, buf, buffer)();
  78420. }
  78421. else {
  78422. BABYLON.Tools.Error("No buffer named: " + buf);
  78423. }
  78424. }
  78425. if (!hasBuffers) {
  78426. onLoad();
  78427. }
  78428. };
  78429. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  78430. var currentScene = gltfRuntime.currentScene;
  78431. if (currentScene) {
  78432. // Only one scene even if multiple scenes are defined
  78433. for (var i = 0; i < currentScene.nodes.length; i++) {
  78434. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  78435. }
  78436. }
  78437. else {
  78438. // Load all scenes
  78439. for (var thing in gltfRuntime.scenes) {
  78440. currentScene = gltfRuntime.scenes[thing];
  78441. for (var i = 0; i < currentScene.nodes.length; i++) {
  78442. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  78443. }
  78444. }
  78445. }
  78446. };
  78447. GLTFLoader.Extensions = {};
  78448. return GLTFLoader;
  78449. }());
  78450. GLTF1.GLTFLoader = GLTFLoader;
  78451. ;
  78452. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  78453. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78454. })(BABYLON || (BABYLON = {}));
  78455. //# sourceMappingURL=babylon.glTFLoader.js.map
  78456. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78457. var BABYLON;
  78458. (function (BABYLON) {
  78459. var GLTF1;
  78460. (function (GLTF1) {
  78461. /**
  78462. * Utils functions for GLTF
  78463. */
  78464. var GLTFUtils = /** @class */ (function () {
  78465. function GLTFUtils() {
  78466. }
  78467. /**
  78468. * Sets the given "parameter" matrix
  78469. * @param scene: the {BABYLON.Scene} object
  78470. * @param source: the source node where to pick the matrix
  78471. * @param parameter: the GLTF technique parameter
  78472. * @param uniformName: the name of the shader's uniform
  78473. * @param shaderMaterial: the shader material
  78474. */
  78475. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  78476. var mat = null;
  78477. if (parameter.semantic === "MODEL") {
  78478. mat = source.getWorldMatrix();
  78479. }
  78480. else if (parameter.semantic === "PROJECTION") {
  78481. mat = scene.getProjectionMatrix();
  78482. }
  78483. else if (parameter.semantic === "VIEW") {
  78484. mat = scene.getViewMatrix();
  78485. }
  78486. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  78487. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  78488. }
  78489. else if (parameter.semantic === "MODELVIEW") {
  78490. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  78491. }
  78492. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  78493. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  78494. }
  78495. else if (parameter.semantic === "MODELINVERSE") {
  78496. mat = source.getWorldMatrix().invert();
  78497. }
  78498. else if (parameter.semantic === "VIEWINVERSE") {
  78499. mat = scene.getViewMatrix().invert();
  78500. }
  78501. else if (parameter.semantic === "PROJECTIONINVERSE") {
  78502. mat = scene.getProjectionMatrix().invert();
  78503. }
  78504. else if (parameter.semantic === "MODELVIEWINVERSE") {
  78505. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  78506. }
  78507. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  78508. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  78509. }
  78510. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  78511. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  78512. }
  78513. else {
  78514. debugger;
  78515. }
  78516. if (mat) {
  78517. switch (parameter.type) {
  78518. case GLTF1.EParameterType.FLOAT_MAT2:
  78519. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  78520. break;
  78521. case GLTF1.EParameterType.FLOAT_MAT3:
  78522. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  78523. break;
  78524. case GLTF1.EParameterType.FLOAT_MAT4:
  78525. shaderMaterial.setMatrix(uniformName, mat);
  78526. break;
  78527. default: break;
  78528. }
  78529. }
  78530. };
  78531. /**
  78532. * Sets the given "parameter" matrix
  78533. * @param shaderMaterial: the shader material
  78534. * @param uniform: the name of the shader's uniform
  78535. * @param value: the value of the uniform
  78536. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  78537. */
  78538. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  78539. switch (type) {
  78540. case GLTF1.EParameterType.FLOAT:
  78541. shaderMaterial.setFloat(uniform, value);
  78542. return true;
  78543. case GLTF1.EParameterType.FLOAT_VEC2:
  78544. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  78545. return true;
  78546. case GLTF1.EParameterType.FLOAT_VEC3:
  78547. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  78548. return true;
  78549. case GLTF1.EParameterType.FLOAT_VEC4:
  78550. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  78551. return true;
  78552. default: return false;
  78553. }
  78554. };
  78555. /**
  78556. * If the uri is a base64 string
  78557. * @param uri: the uri to test
  78558. */
  78559. GLTFUtils.IsBase64 = function (uri) {
  78560. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  78561. };
  78562. /**
  78563. * Decode the base64 uri
  78564. * @param uri: the uri to decode
  78565. */
  78566. GLTFUtils.DecodeBase64 = function (uri) {
  78567. var decodedString = atob(uri.split(",")[1]);
  78568. var bufferLength = decodedString.length;
  78569. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  78570. for (var i = 0; i < bufferLength; i++) {
  78571. bufferView[i] = decodedString.charCodeAt(i);
  78572. }
  78573. return bufferView.buffer;
  78574. };
  78575. /**
  78576. * Returns the wrap mode of the texture
  78577. * @param mode: the mode value
  78578. */
  78579. GLTFUtils.GetWrapMode = function (mode) {
  78580. switch (mode) {
  78581. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  78582. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  78583. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  78584. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  78585. }
  78586. };
  78587. /**
  78588. * Returns the byte stride giving an accessor
  78589. * @param accessor: the GLTF accessor objet
  78590. */
  78591. GLTFUtils.GetByteStrideFromType = function (accessor) {
  78592. // Needs this function since "byteStride" isn't requiered in glTF format
  78593. var type = accessor.type;
  78594. switch (type) {
  78595. case "VEC2": return 2;
  78596. case "VEC3": return 3;
  78597. case "VEC4": return 4;
  78598. case "MAT2": return 4;
  78599. case "MAT3": return 9;
  78600. case "MAT4": return 16;
  78601. default: return 1;
  78602. }
  78603. };
  78604. /**
  78605. * Returns the texture filter mode giving a mode value
  78606. * @param mode: the filter mode value
  78607. */
  78608. GLTFUtils.GetTextureFilterMode = function (mode) {
  78609. switch (mode) {
  78610. case GLTF1.ETextureFilterType.LINEAR:
  78611. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  78612. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  78613. case GLTF1.ETextureFilterType.NEAREST:
  78614. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  78615. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  78616. }
  78617. };
  78618. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  78619. var byteOffset = bufferView.byteOffset + byteOffset;
  78620. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  78621. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  78622. throw new Error("Buffer access is out of range");
  78623. }
  78624. var buffer = loadedBufferView.buffer;
  78625. byteOffset += loadedBufferView.byteOffset;
  78626. switch (componentType) {
  78627. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  78628. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  78629. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  78630. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  78631. default: return new Float32Array(buffer, byteOffset, byteLength);
  78632. }
  78633. };
  78634. /**
  78635. * Returns a buffer from its accessor
  78636. * @param gltfRuntime: the GLTF runtime
  78637. * @param accessor: the GLTF accessor
  78638. */
  78639. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  78640. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  78641. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  78642. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  78643. };
  78644. /**
  78645. * Decodes a buffer view into a string
  78646. * @param view: the buffer view
  78647. */
  78648. GLTFUtils.DecodeBufferToText = function (view) {
  78649. var result = "";
  78650. var length = view.byteLength;
  78651. for (var i = 0; i < length; ++i) {
  78652. result += String.fromCharCode(view[i]);
  78653. }
  78654. return result;
  78655. };
  78656. /**
  78657. * Returns the default material of gltf. Related to
  78658. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  78659. * @param scene: the Babylon.js scene
  78660. */
  78661. GLTFUtils.GetDefaultMaterial = function (scene) {
  78662. if (!GLTFUtils._DefaultMaterial) {
  78663. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  78664. "precision highp float;",
  78665. "",
  78666. "uniform mat4 worldView;",
  78667. "uniform mat4 projection;",
  78668. "",
  78669. "attribute vec3 position;",
  78670. "",
  78671. "void main(void)",
  78672. "{",
  78673. " gl_Position = projection * worldView * vec4(position, 1.0);",
  78674. "}"
  78675. ].join("\n");
  78676. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  78677. "precision highp float;",
  78678. "",
  78679. "uniform vec4 u_emission;",
  78680. "",
  78681. "void main(void)",
  78682. "{",
  78683. " gl_FragColor = u_emission;",
  78684. "}"
  78685. ].join("\n");
  78686. var shaderPath = {
  78687. vertex: "GLTFDefaultMaterial",
  78688. fragment: "GLTFDefaultMaterial"
  78689. };
  78690. var options = {
  78691. attributes: ["position"],
  78692. uniforms: ["worldView", "projection", "u_emission"],
  78693. samplers: new Array(),
  78694. needAlphaBlending: false
  78695. };
  78696. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  78697. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  78698. }
  78699. return GLTFUtils._DefaultMaterial;
  78700. };
  78701. // The GLTF default material
  78702. GLTFUtils._DefaultMaterial = null;
  78703. return GLTFUtils;
  78704. }());
  78705. GLTF1.GLTFUtils = GLTFUtils;
  78706. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78707. })(BABYLON || (BABYLON = {}));
  78708. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  78709. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78710. var BABYLON;
  78711. (function (BABYLON) {
  78712. var GLTF1;
  78713. (function (GLTF1) {
  78714. var GLTFLoaderExtension = /** @class */ (function () {
  78715. function GLTFLoaderExtension(name) {
  78716. this._name = name;
  78717. }
  78718. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  78719. get: function () {
  78720. return this._name;
  78721. },
  78722. enumerable: true,
  78723. configurable: true
  78724. });
  78725. /**
  78726. * Defines an override for loading the runtime
  78727. * Return true to stop further extensions from loading the runtime
  78728. */
  78729. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78730. return false;
  78731. };
  78732. /**
  78733. * Defines an onverride for creating gltf runtime
  78734. * Return true to stop further extensions from creating the runtime
  78735. */
  78736. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78737. return false;
  78738. };
  78739. /**
  78740. * Defines an override for loading buffers
  78741. * Return true to stop further extensions from loading this buffer
  78742. */
  78743. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  78744. return false;
  78745. };
  78746. /**
  78747. * Defines an override for loading texture buffers
  78748. * Return true to stop further extensions from loading this texture data
  78749. */
  78750. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78751. return false;
  78752. };
  78753. /**
  78754. * Defines an override for creating textures
  78755. * Return true to stop further extensions from loading this texture
  78756. */
  78757. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  78758. return false;
  78759. };
  78760. /**
  78761. * Defines an override for loading shader strings
  78762. * Return true to stop further extensions from loading this shader data
  78763. */
  78764. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78765. return false;
  78766. };
  78767. /**
  78768. * Defines an override for loading materials
  78769. * Return true to stop further extensions from loading this material
  78770. */
  78771. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78772. return false;
  78773. };
  78774. // ---------
  78775. // Utilities
  78776. // ---------
  78777. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78778. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78779. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  78780. }, function () {
  78781. setTimeout(function () {
  78782. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  78783. });
  78784. });
  78785. };
  78786. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78787. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78788. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  78789. }, function () {
  78790. setTimeout(function () {
  78791. onSuccess();
  78792. });
  78793. });
  78794. };
  78795. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  78796. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78797. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  78798. }, function () {
  78799. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  78800. });
  78801. };
  78802. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  78803. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  78804. };
  78805. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78806. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78807. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  78808. }, function () {
  78809. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  78810. });
  78811. };
  78812. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78813. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78814. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  78815. }, function () {
  78816. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  78817. });
  78818. };
  78819. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78820. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78821. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  78822. }, function () {
  78823. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  78824. });
  78825. };
  78826. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  78827. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78828. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  78829. }, function () {
  78830. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  78831. });
  78832. };
  78833. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  78834. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  78835. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  78836. if (func(loaderExtension)) {
  78837. return;
  78838. }
  78839. }
  78840. defaultFunc();
  78841. };
  78842. return GLTFLoaderExtension;
  78843. }());
  78844. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  78845. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78846. })(BABYLON || (BABYLON = {}));
  78847. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  78848. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78849. var BABYLON;
  78850. (function (BABYLON) {
  78851. var GLTF1;
  78852. (function (GLTF1) {
  78853. var BinaryExtensionBufferName = "binary_glTF";
  78854. ;
  78855. ;
  78856. var GLTFBinaryExtension = /** @class */ (function (_super) {
  78857. __extends(GLTFBinaryExtension, _super);
  78858. function GLTFBinaryExtension() {
  78859. return _super.call(this, "KHR_binary_glTF") || this;
  78860. }
  78861. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78862. var extensionsUsed = data.json.extensionsUsed;
  78863. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  78864. return false;
  78865. }
  78866. this._bin = data.bin;
  78867. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  78868. return true;
  78869. };
  78870. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78871. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  78872. return false;
  78873. }
  78874. if (id !== BinaryExtensionBufferName) {
  78875. return false;
  78876. }
  78877. onSuccess(this._bin);
  78878. return true;
  78879. };
  78880. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78881. var texture = gltfRuntime.textures[id];
  78882. var source = gltfRuntime.images[texture.source];
  78883. if (!source.extensions || !(this.name in source.extensions)) {
  78884. return false;
  78885. }
  78886. var sourceExt = source.extensions[this.name];
  78887. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  78888. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  78889. onSuccess(buffer);
  78890. return true;
  78891. };
  78892. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78893. var shader = gltfRuntime.shaders[id];
  78894. if (!shader.extensions || !(this.name in shader.extensions)) {
  78895. return false;
  78896. }
  78897. var binaryExtensionShader = shader.extensions[this.name];
  78898. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  78899. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  78900. setTimeout(function () {
  78901. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  78902. onSuccess(shaderString);
  78903. });
  78904. return true;
  78905. };
  78906. return GLTFBinaryExtension;
  78907. }(GLTF1.GLTFLoaderExtension));
  78908. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  78909. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  78910. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78911. })(BABYLON || (BABYLON = {}));
  78912. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  78913. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78914. var BABYLON;
  78915. (function (BABYLON) {
  78916. var GLTF1;
  78917. (function (GLTF1) {
  78918. ;
  78919. ;
  78920. ;
  78921. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  78922. __extends(GLTFMaterialsCommonExtension, _super);
  78923. function GLTFMaterialsCommonExtension() {
  78924. return _super.call(this, "KHR_materials_common") || this;
  78925. }
  78926. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78927. if (!gltfRuntime.extensions)
  78928. return false;
  78929. var extension = gltfRuntime.extensions[this.name];
  78930. if (!extension)
  78931. return false;
  78932. // Create lights
  78933. var lights = extension.lights;
  78934. if (lights) {
  78935. for (var thing in lights) {
  78936. var light = lights[thing];
  78937. switch (light.type) {
  78938. case "ambient":
  78939. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  78940. var ambient = light.ambient;
  78941. if (ambient) {
  78942. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  78943. }
  78944. break;
  78945. case "point":
  78946. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  78947. var point = light.point;
  78948. if (point) {
  78949. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  78950. }
  78951. break;
  78952. case "directional":
  78953. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  78954. var directional = light.directional;
  78955. if (directional) {
  78956. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  78957. }
  78958. break;
  78959. case "spot":
  78960. var spot = light.spot;
  78961. if (spot) {
  78962. 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);
  78963. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  78964. }
  78965. break;
  78966. default:
  78967. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  78968. break;
  78969. }
  78970. }
  78971. }
  78972. return false;
  78973. };
  78974. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78975. var material = gltfRuntime.materials[id];
  78976. if (!material || !material.extensions)
  78977. return false;
  78978. var extension = material.extensions[this.name];
  78979. if (!extension)
  78980. return false;
  78981. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  78982. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78983. if (extension.technique === "CONSTANT") {
  78984. standardMaterial.disableLighting = true;
  78985. }
  78986. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  78987. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  78988. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  78989. // Ambient
  78990. if (typeof extension.values.ambient === "string") {
  78991. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  78992. }
  78993. else {
  78994. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  78995. }
  78996. // Diffuse
  78997. if (typeof extension.values.diffuse === "string") {
  78998. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  78999. }
  79000. else {
  79001. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  79002. }
  79003. // Emission
  79004. if (typeof extension.values.emission === "string") {
  79005. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  79006. }
  79007. else {
  79008. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  79009. }
  79010. // Specular
  79011. if (typeof extension.values.specular === "string") {
  79012. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  79013. }
  79014. else {
  79015. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  79016. }
  79017. return true;
  79018. };
  79019. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  79020. // Create buffer from texture url
  79021. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  79022. // Create texture from buffer
  79023. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  79024. }, onError);
  79025. };
  79026. return GLTFMaterialsCommonExtension;
  79027. }(GLTF1.GLTFLoaderExtension));
  79028. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  79029. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  79030. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  79031. })(BABYLON || (BABYLON = {}));
  79032. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  79033. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79034. var BABYLON;
  79035. (function (BABYLON) {
  79036. var GLTF2;
  79037. (function (GLTF2) {
  79038. /**
  79039. * Enums
  79040. */
  79041. var EComponentType;
  79042. (function (EComponentType) {
  79043. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  79044. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  79045. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  79046. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  79047. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  79048. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  79049. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  79050. var EMeshPrimitiveMode;
  79051. (function (EMeshPrimitiveMode) {
  79052. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  79053. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  79054. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  79055. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  79056. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  79057. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  79058. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  79059. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  79060. var ETextureMagFilter;
  79061. (function (ETextureMagFilter) {
  79062. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  79063. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  79064. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  79065. var ETextureMinFilter;
  79066. (function (ETextureMinFilter) {
  79067. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  79068. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  79069. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  79070. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  79071. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  79072. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  79073. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  79074. var ETextureWrapMode;
  79075. (function (ETextureWrapMode) {
  79076. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  79077. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  79078. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  79079. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  79080. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79081. })(BABYLON || (BABYLON = {}));
  79082. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  79083. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79084. var BABYLON;
  79085. (function (BABYLON) {
  79086. var GLTF2;
  79087. (function (GLTF2) {
  79088. var GLTFLoaderTracker = /** @class */ (function () {
  79089. function GLTFLoaderTracker(onComplete) {
  79090. this._pendingCount = 0;
  79091. this._callback = onComplete;
  79092. }
  79093. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  79094. this._pendingCount++;
  79095. };
  79096. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  79097. if (--this._pendingCount === 0) {
  79098. this._callback();
  79099. }
  79100. };
  79101. return GLTFLoaderTracker;
  79102. }());
  79103. var GLTFLoader = /** @class */ (function () {
  79104. function GLTFLoader(parent) {
  79105. this._disposed = false;
  79106. this._renderReady = false;
  79107. this._requests = new Array();
  79108. this._renderReadyObservable = new BABYLON.Observable();
  79109. // Count of pending work that needs to complete before the asset is rendered.
  79110. this._renderPendingCount = 0;
  79111. // Count of pending work that needs to complete before the loader is disposed.
  79112. this._loaderPendingCount = 0;
  79113. this._loaderTrackers = new Array();
  79114. this._parent = parent;
  79115. }
  79116. GLTFLoader.RegisterExtension = function (extension) {
  79117. if (GLTFLoader.Extensions[extension.name]) {
  79118. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  79119. return;
  79120. }
  79121. GLTFLoader.Extensions[extension.name] = extension;
  79122. // Keep the order of registration so that extensions registered first are called first.
  79123. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  79124. };
  79125. GLTFLoader.prototype.dispose = function () {
  79126. if (this._disposed) {
  79127. return;
  79128. }
  79129. this._disposed = true;
  79130. // Abort requests that are not complete
  79131. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  79132. var request = _a[_i];
  79133. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  79134. request.abort();
  79135. }
  79136. }
  79137. // Revoke object urls created during load
  79138. if (this._gltf.textures) {
  79139. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  79140. var texture = _c[_b];
  79141. if (texture.url) {
  79142. URL.revokeObjectURL(texture.url);
  79143. }
  79144. }
  79145. }
  79146. };
  79147. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  79148. var _this = this;
  79149. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  79150. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  79151. }, onProgress, onError);
  79152. };
  79153. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  79154. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  79155. };
  79156. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  79157. var _this = this;
  79158. this._tryCatchOnError(function () {
  79159. _this._loadData(data);
  79160. _this._babylonScene = scene;
  79161. _this._rootUrl = rootUrl;
  79162. _this._successCallback = onSuccess;
  79163. _this._progressCallback = onProgress;
  79164. _this._errorCallback = onError;
  79165. _this._addPendingData(_this);
  79166. _this._loadDefaultScene(nodeNames);
  79167. _this._loadAnimations();
  79168. _this._removePendingData(_this);
  79169. });
  79170. };
  79171. GLTFLoader.prototype._onProgress = function (event) {
  79172. if (this._progressCallback) {
  79173. this._progressCallback(event);
  79174. }
  79175. };
  79176. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  79177. if (this._renderReady) {
  79178. func();
  79179. }
  79180. else {
  79181. this._renderReadyObservable.add(func);
  79182. }
  79183. };
  79184. GLTFLoader.prototype._onRenderReady = function () {
  79185. this._rootNode.babylonMesh.setEnabled(true);
  79186. this._startAnimations();
  79187. this._successCallback();
  79188. this._renderReadyObservable.notifyObservers(this);
  79189. };
  79190. GLTFLoader.prototype._onComplete = function () {
  79191. if (this._parent.onComplete) {
  79192. this._parent.onComplete();
  79193. }
  79194. this.dispose();
  79195. };
  79196. GLTFLoader.prototype._loadData = function (data) {
  79197. this._gltf = data.json;
  79198. // Assign the index of each object for convinience.
  79199. GLTFLoader._AssignIndices(this._gltf.accessors);
  79200. GLTFLoader._AssignIndices(this._gltf.animations);
  79201. GLTFLoader._AssignIndices(this._gltf.buffers);
  79202. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  79203. GLTFLoader._AssignIndices(this._gltf.images);
  79204. GLTFLoader._AssignIndices(this._gltf.materials);
  79205. GLTFLoader._AssignIndices(this._gltf.meshes);
  79206. GLTFLoader._AssignIndices(this._gltf.nodes);
  79207. GLTFLoader._AssignIndices(this._gltf.scenes);
  79208. GLTFLoader._AssignIndices(this._gltf.skins);
  79209. GLTFLoader._AssignIndices(this._gltf.textures);
  79210. if (data.bin) {
  79211. var buffers = this._gltf.buffers;
  79212. if (buffers && buffers[0] && !buffers[0].uri) {
  79213. var binaryBuffer = buffers[0];
  79214. if (binaryBuffer.byteLength != data.bin.byteLength) {
  79215. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  79216. }
  79217. binaryBuffer.loadedData = data.bin;
  79218. }
  79219. else {
  79220. BABYLON.Tools.Warn("Unexpected BIN chunk");
  79221. }
  79222. }
  79223. };
  79224. GLTFLoader.prototype._getMeshes = function () {
  79225. var meshes = new Array();
  79226. // Root mesh is always first.
  79227. meshes.push(this._rootNode.babylonMesh);
  79228. var nodes = this._gltf.nodes;
  79229. if (nodes) {
  79230. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  79231. var node = nodes_1[_i];
  79232. if (node.babylonMesh) {
  79233. meshes.push(node.babylonMesh);
  79234. }
  79235. }
  79236. }
  79237. return meshes;
  79238. };
  79239. GLTFLoader.prototype._getSkeletons = function () {
  79240. var skeletons = new Array();
  79241. var skins = this._gltf.skins;
  79242. if (skins) {
  79243. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  79244. var skin = skins_1[_i];
  79245. if (skin.babylonSkeleton) {
  79246. skeletons.push(skin.babylonSkeleton);
  79247. }
  79248. }
  79249. }
  79250. return skeletons;
  79251. };
  79252. GLTFLoader.prototype._getAnimationTargets = function () {
  79253. var targets = new Array();
  79254. var animations = this._gltf.animations;
  79255. if (animations) {
  79256. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  79257. var animation = animations_1[_i];
  79258. targets.push.apply(targets, animation.targets);
  79259. }
  79260. }
  79261. return targets;
  79262. };
  79263. GLTFLoader.prototype._startAnimations = function () {
  79264. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  79265. var target = _a[_i];
  79266. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  79267. }
  79268. };
  79269. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  79270. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  79271. if (!scene) {
  79272. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  79273. }
  79274. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  79275. };
  79276. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  79277. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  79278. switch (this._parent.coordinateSystemMode) {
  79279. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  79280. if (!this._babylonScene.useRightHandedSystem) {
  79281. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  79282. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  79283. }
  79284. break;
  79285. }
  79286. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  79287. // do nothing
  79288. break;
  79289. }
  79290. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  79291. this._babylonScene.useRightHandedSystem = true;
  79292. break;
  79293. }
  79294. default: {
  79295. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  79296. return;
  79297. }
  79298. }
  79299. var nodeIndices = scene.nodes;
  79300. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  79301. node.parent = parentNode;
  79302. return true;
  79303. }, this._rootNode);
  79304. if (nodeNames) {
  79305. if (!(nodeNames instanceof Array)) {
  79306. nodeNames = [nodeNames];
  79307. }
  79308. var filteredNodeIndices_1 = new Array();
  79309. this._traverseNodes(context, nodeIndices, function (node) {
  79310. if (nodeNames.indexOf(node.name) !== -1) {
  79311. filteredNodeIndices_1.push(node.index);
  79312. return false;
  79313. }
  79314. return true;
  79315. }, this._rootNode);
  79316. nodeIndices = filteredNodeIndices_1;
  79317. }
  79318. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  79319. var index = nodeIndices_1[_i];
  79320. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  79321. if (!node) {
  79322. throw new Error(context + ": Failed to find node " + index);
  79323. }
  79324. this._loadNode("#/nodes/" + index, node);
  79325. }
  79326. // Disable the root mesh until the asset is ready to render.
  79327. this._rootNode.babylonMesh.setEnabled(false);
  79328. };
  79329. GLTFLoader.prototype._loadNode = function (context, node) {
  79330. node.babylonBones = {};
  79331. node.babylonAnimationTargets = [];
  79332. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  79333. return;
  79334. }
  79335. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  79336. node.babylonMesh.hasVertexAlpha = true;
  79337. this._loadTransform(node);
  79338. if (node.mesh != null) {
  79339. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  79340. if (!mesh) {
  79341. throw new Error(context + ": Failed to find mesh " + node.mesh);
  79342. }
  79343. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  79344. }
  79345. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  79346. node.babylonAnimationTargets.push(node.babylonMesh);
  79347. if (node.skin != null) {
  79348. var skin = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  79349. if (!skin) {
  79350. throw new Error(context + ": Failed to find skin " + node.skin);
  79351. }
  79352. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  79353. }
  79354. if (node.camera != null) {
  79355. // TODO: handle cameras
  79356. }
  79357. if (node.children) {
  79358. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  79359. var index = _a[_i];
  79360. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  79361. if (!childNode) {
  79362. throw new Error(context + ": Failed to find child node " + index);
  79363. }
  79364. this._loadNode("#/nodes/" + index, childNode);
  79365. }
  79366. }
  79367. };
  79368. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  79369. var _this = this;
  79370. var primitives = mesh.primitives;
  79371. if (!primitives || primitives.length === 0) {
  79372. throw new Error(context + ": Primitives are missing");
  79373. }
  79374. this._createMorphTargets(context, node, mesh);
  79375. this._loadAllVertexDataAsync(context, mesh, function () {
  79376. _this._loadMorphTargets(context, node, mesh);
  79377. var vertexData = new BABYLON.VertexData();
  79378. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  79379. var primitive = primitives_1[_i];
  79380. vertexData.merge(primitive.vertexData);
  79381. }
  79382. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  79383. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  79384. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  79385. node.babylonMesh.subMeshes = [];
  79386. var verticesStart = 0;
  79387. var indicesStart = 0;
  79388. for (var index = 0; index < primitives.length; index++) {
  79389. var vertexData_1 = primitives[index].vertexData;
  79390. var verticesCount = vertexData_1.positions.length;
  79391. var indicesCount = vertexData_1.indices.length;
  79392. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  79393. verticesStart += verticesCount;
  79394. indicesStart += indicesCount;
  79395. }
  79396. ;
  79397. });
  79398. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  79399. node.babylonMesh.material = multiMaterial;
  79400. var subMaterials = multiMaterial.subMaterials;
  79401. var _loop_1 = function (index) {
  79402. var primitive = primitives[index];
  79403. if (primitive.material == null) {
  79404. subMaterials[index] = this_1._getDefaultMaterial();
  79405. }
  79406. else {
  79407. var material_1 = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  79408. if (!material_1) {
  79409. throw new Error(context + ": Failed to find material " + primitive.material);
  79410. }
  79411. this_1._loadMaterial("#/materials/" + material_1.index, material_1, function (babylonMaterial, isNew) {
  79412. if (isNew && _this._parent.onMaterialLoaded) {
  79413. _this._parent.onMaterialLoaded(babylonMaterial);
  79414. }
  79415. if (_this._parent.onBeforeMaterialReadyAsync) {
  79416. _this._addLoaderPendingData(material_1);
  79417. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  79418. _this._tryCatchOnError(function () {
  79419. subMaterials[index] = babylonMaterial;
  79420. _this._removeLoaderPendingData(material_1);
  79421. });
  79422. });
  79423. }
  79424. else {
  79425. subMaterials[index] = babylonMaterial;
  79426. }
  79427. });
  79428. }
  79429. };
  79430. var this_1 = this;
  79431. for (var index = 0; index < primitives.length; index++) {
  79432. _loop_1(index);
  79433. }
  79434. ;
  79435. };
  79436. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  79437. var primitives = mesh.primitives;
  79438. var numRemainingPrimitives = primitives.length;
  79439. var _loop_2 = function (index) {
  79440. var primitive = primitives[index];
  79441. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  79442. primitive.vertexData = vertexData;
  79443. if (--numRemainingPrimitives === 0) {
  79444. onSuccess();
  79445. }
  79446. });
  79447. };
  79448. var this_2 = this;
  79449. for (var index = 0; index < primitives.length; index++) {
  79450. _loop_2(index);
  79451. }
  79452. };
  79453. /**
  79454. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  79455. * @param {ArrayBufferView} data
  79456. * @param {IGLTFAccessor} accessor
  79457. */
  79458. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  79459. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  79460. return data;
  79461. }
  79462. var buffer = data;
  79463. var factor = 1;
  79464. switch (accessor.componentType) {
  79465. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  79466. factor = 1 / 255;
  79467. break;
  79468. }
  79469. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  79470. factor = 1 / 65535;
  79471. break;
  79472. }
  79473. default: {
  79474. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  79475. }
  79476. }
  79477. var result = new Float32Array(accessor.count * 2);
  79478. for (var i = 0; i < result.length; ++i) {
  79479. result[i] = buffer[i] * factor;
  79480. }
  79481. return result;
  79482. };
  79483. /**
  79484. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  79485. * @param {ArrayBufferView} data
  79486. * @param {IGLTFAccessor} accessor
  79487. */
  79488. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  79489. var colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  79490. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  79491. return data;
  79492. }
  79493. var buffer = data;
  79494. var factor = 1;
  79495. switch (accessor.componentType) {
  79496. case GLTF2.EComponentType.FLOAT: {
  79497. factor = 1;
  79498. break;
  79499. }
  79500. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  79501. factor = 1 / 255;
  79502. break;
  79503. }
  79504. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  79505. factor = 1 / 65535;
  79506. break;
  79507. }
  79508. default: {
  79509. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  79510. }
  79511. }
  79512. var result = new Float32Array(accessor.count * 4);
  79513. if (colorComponentCount === 4) {
  79514. for (var i = 0; i < result.length; ++i) {
  79515. result[i] = buffer[i] * factor;
  79516. }
  79517. }
  79518. else {
  79519. var offset = 0;
  79520. for (var i = 0; i < result.length; ++i) {
  79521. if ((i + 1) % 4 === 0) {
  79522. result[i] = 1;
  79523. }
  79524. else {
  79525. result[i] = buffer[offset++] * factor;
  79526. }
  79527. }
  79528. }
  79529. return result;
  79530. };
  79531. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  79532. var _this = this;
  79533. var attributes = primitive.attributes;
  79534. if (!attributes) {
  79535. throw new Error(context + ": Attributes are missing");
  79536. }
  79537. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  79538. // TODO: handle other primitive modes
  79539. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  79540. }
  79541. var vertexData = new BABYLON.VertexData();
  79542. var numRemainingAttributes = Object.keys(attributes).length;
  79543. var _loop_3 = function (attribute) {
  79544. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  79545. if (!accessor) {
  79546. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  79547. }
  79548. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  79549. switch (attribute) {
  79550. case "POSITION": {
  79551. vertexData.positions = data;
  79552. break;
  79553. }
  79554. case "NORMAL": {
  79555. vertexData.normals = data;
  79556. break;
  79557. }
  79558. case "TANGENT": {
  79559. vertexData.tangents = data;
  79560. break;
  79561. }
  79562. case "TEXCOORD_0": {
  79563. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  79564. break;
  79565. }
  79566. case "TEXCOORD_1": {
  79567. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  79568. break;
  79569. }
  79570. case "JOINTS_0": {
  79571. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  79572. break;
  79573. }
  79574. case "WEIGHTS_0": {
  79575. //TODO: need to add support for normalized weights.
  79576. vertexData.matricesWeights = data;
  79577. break;
  79578. }
  79579. case "COLOR_0": {
  79580. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  79581. break;
  79582. }
  79583. default: {
  79584. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  79585. break;
  79586. }
  79587. }
  79588. if (--numRemainingAttributes === 0) {
  79589. if (primitive.indices == null) {
  79590. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  79591. for (var i = 0; i < vertexData.indices.length; i++) {
  79592. vertexData.indices[i] = i;
  79593. }
  79594. onSuccess(vertexData);
  79595. }
  79596. else {
  79597. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  79598. if (!indicesAccessor) {
  79599. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  79600. }
  79601. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  79602. vertexData.indices = data;
  79603. onSuccess(vertexData);
  79604. });
  79605. }
  79606. }
  79607. });
  79608. };
  79609. var this_3 = this;
  79610. for (var attribute in attributes) {
  79611. _loop_3(attribute);
  79612. }
  79613. };
  79614. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  79615. var primitives = mesh.primitives;
  79616. var targets = primitives[0].targets;
  79617. if (!targets) {
  79618. return;
  79619. }
  79620. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  79621. var primitive = primitives_2[_i];
  79622. if (!primitive.targets || primitive.targets.length != targets.length) {
  79623. throw new Error(context + ": All primitives are required to list the same number of targets");
  79624. }
  79625. }
  79626. var morphTargetManager = new BABYLON.MorphTargetManager();
  79627. node.babylonMesh.morphTargetManager = morphTargetManager;
  79628. for (var index = 0; index < targets.length; index++) {
  79629. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  79630. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  79631. }
  79632. };
  79633. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  79634. var morphTargetManager = node.babylonMesh.morphTargetManager;
  79635. if (!morphTargetManager) {
  79636. return;
  79637. }
  79638. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  79639. var numTargets = morphTargetManager.numTargets;
  79640. for (var index = 0; index < numTargets; index++) {
  79641. var vertexData = new BABYLON.VertexData();
  79642. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  79643. var primitive = _a[_i];
  79644. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  79645. }
  79646. if (!vertexData.positions) {
  79647. throw new Error(context + ": Positions are missing");
  79648. }
  79649. var target = morphTargetManager.getTarget(index);
  79650. target.setPositions(vertexData.positions);
  79651. target.setNormals(vertexData.normals);
  79652. target.setTangents(vertexData.tangents);
  79653. }
  79654. });
  79655. };
  79656. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  79657. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  79658. var _loop_4 = function (primitive) {
  79659. var targets = primitive.targets;
  79660. primitive.targetsVertexData = new Array(targets.length);
  79661. var _loop_5 = function (index) {
  79662. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  79663. primitive.targetsVertexData[index] = vertexData;
  79664. if (--numRemainingTargets === 0) {
  79665. onSuccess();
  79666. }
  79667. });
  79668. };
  79669. for (var index = 0; index < targets.length; index++) {
  79670. _loop_5(index);
  79671. }
  79672. };
  79673. var this_4 = this;
  79674. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  79675. var primitive = _a[_i];
  79676. _loop_4(primitive);
  79677. }
  79678. };
  79679. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  79680. var targetVertexData = new BABYLON.VertexData();
  79681. var numRemainingAttributes = Object.keys(attributes).length;
  79682. var _loop_6 = function (attribute) {
  79683. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  79684. if (!accessor) {
  79685. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  79686. }
  79687. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  79688. // glTF stores morph target information as deltas while babylon.js expects the final data.
  79689. // As a result we have to add the original data to the delta to calculate the final data.
  79690. var values = data;
  79691. switch (attribute) {
  79692. case "POSITION": {
  79693. for (var i = 0; i < values.length; i++) {
  79694. values[i] += vertexData.positions[i];
  79695. }
  79696. targetVertexData.positions = values;
  79697. break;
  79698. }
  79699. case "NORMAL": {
  79700. for (var i = 0; i < values.length; i++) {
  79701. values[i] += vertexData.normals[i];
  79702. }
  79703. targetVertexData.normals = values;
  79704. break;
  79705. }
  79706. case "TANGENT": {
  79707. // Tangent data for morph targets is stored as xyz delta.
  79708. // The vertexData.tangent is stored as xyzw.
  79709. // So we need to skip every fourth vertexData.tangent.
  79710. for (var i = 0, j = 0; i < values.length; i++, j++) {
  79711. values[i] += vertexData.tangents[j];
  79712. if ((i + 1) % 3 == 0) {
  79713. j++;
  79714. }
  79715. }
  79716. targetVertexData.tangents = values;
  79717. break;
  79718. }
  79719. default: {
  79720. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  79721. break;
  79722. }
  79723. }
  79724. if (--numRemainingAttributes === 0) {
  79725. onSuccess(targetVertexData);
  79726. }
  79727. });
  79728. };
  79729. var this_5 = this;
  79730. for (var attribute in attributes) {
  79731. _loop_6(attribute);
  79732. }
  79733. };
  79734. GLTFLoader.prototype._loadTransform = function (node) {
  79735. var position = BABYLON.Vector3.Zero();
  79736. var rotation = BABYLON.Quaternion.Identity();
  79737. var scaling = BABYLON.Vector3.One();
  79738. if (node.matrix) {
  79739. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  79740. matrix.decompose(scaling, rotation, position);
  79741. }
  79742. else {
  79743. if (node.translation)
  79744. position = BABYLON.Vector3.FromArray(node.translation);
  79745. if (node.rotation)
  79746. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  79747. if (node.scale)
  79748. scaling = BABYLON.Vector3.FromArray(node.scale);
  79749. }
  79750. node.babylonMesh.position = position;
  79751. node.babylonMesh.rotationQuaternion = rotation;
  79752. node.babylonMesh.scaling = scaling;
  79753. };
  79754. GLTFLoader.prototype._loadSkin = function (context, skin) {
  79755. var _this = this;
  79756. var skeletonId = "skeleton" + skin.index;
  79757. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  79758. if (skin.inverseBindMatrices == null) {
  79759. this._loadBones(context, skin, null);
  79760. }
  79761. else {
  79762. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  79763. if (!accessor) {
  79764. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  79765. }
  79766. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  79767. _this._loadBones(context, skin, data);
  79768. });
  79769. }
  79770. return skin.babylonSkeleton;
  79771. };
  79772. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  79773. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  79774. node.babylonBones[skin.index] = babylonBone;
  79775. node.babylonAnimationTargets.push(babylonBone);
  79776. return babylonBone;
  79777. };
  79778. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  79779. var babylonBones = {};
  79780. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  79781. var index = _a[_i];
  79782. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  79783. if (!node) {
  79784. throw new Error(context + ": Failed to find joint " + index);
  79785. }
  79786. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  79787. }
  79788. };
  79789. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  79790. var babylonBone = babylonBones[node.index];
  79791. if (babylonBone) {
  79792. return babylonBone;
  79793. }
  79794. var boneIndex = skin.joints.indexOf(node.index);
  79795. var baseMatrix = BABYLON.Matrix.Identity();
  79796. if (inverseBindMatrixData && boneIndex !== -1) {
  79797. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  79798. baseMatrix.invertToRef(baseMatrix);
  79799. }
  79800. var babylonParentBone = null;
  79801. if (node.index !== skin.skeleton && node.parent && node.parent !== this._rootNode) {
  79802. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  79803. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  79804. }
  79805. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  79806. babylonBones[node.index] = babylonBone;
  79807. return babylonBone;
  79808. };
  79809. GLTFLoader.prototype._getNodeMatrix = function (node) {
  79810. return node.matrix ?
  79811. BABYLON.Matrix.FromArray(node.matrix) :
  79812. 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());
  79813. };
  79814. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  79815. if (parentNode === void 0) { parentNode = null; }
  79816. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  79817. var index = indices_1[_i];
  79818. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  79819. if (!node) {
  79820. throw new Error(context + ": Failed to find node " + index);
  79821. }
  79822. this._traverseNode(context, node, action, parentNode);
  79823. }
  79824. };
  79825. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  79826. if (parentNode === void 0) { parentNode = null; }
  79827. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  79828. return;
  79829. }
  79830. if (!action(node, parentNode)) {
  79831. return;
  79832. }
  79833. if (node.children) {
  79834. this._traverseNodes(context, node.children, action, node);
  79835. }
  79836. };
  79837. GLTFLoader.prototype._loadAnimations = function () {
  79838. var animations = this._gltf.animations;
  79839. if (!animations) {
  79840. return;
  79841. }
  79842. for (var index = 0; index < animations.length; index++) {
  79843. var animation = animations[index];
  79844. this._loadAnimation("#/animations/" + index, animation);
  79845. }
  79846. };
  79847. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  79848. animation.targets = [];
  79849. for (var index = 0; index < animation.channels.length; index++) {
  79850. var channel = GLTFLoader._GetProperty(animation.channels, index);
  79851. if (!channel) {
  79852. throw new Error(context + ": Failed to find channel " + index);
  79853. }
  79854. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  79855. if (!sampler) {
  79856. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  79857. }
  79858. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  79859. }
  79860. };
  79861. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  79862. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  79863. if (!targetNode) {
  79864. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  79865. }
  79866. var targetPath;
  79867. var animationType;
  79868. switch (channel.target.path) {
  79869. case "translation": {
  79870. targetPath = "position";
  79871. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  79872. break;
  79873. }
  79874. case "rotation": {
  79875. targetPath = "rotationQuaternion";
  79876. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  79877. break;
  79878. }
  79879. case "scale": {
  79880. targetPath = "scaling";
  79881. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  79882. break;
  79883. }
  79884. case "weights": {
  79885. targetPath = "influence";
  79886. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  79887. break;
  79888. }
  79889. default: {
  79890. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  79891. }
  79892. }
  79893. var inputData;
  79894. var outputData;
  79895. var checkSuccess = function () {
  79896. if (!inputData || !outputData) {
  79897. return;
  79898. }
  79899. var outputBufferOffset = 0;
  79900. var getNextOutputValue;
  79901. switch (targetPath) {
  79902. case "position": {
  79903. getNextOutputValue = function () {
  79904. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  79905. outputBufferOffset += 3;
  79906. return value;
  79907. };
  79908. break;
  79909. }
  79910. case "rotationQuaternion": {
  79911. getNextOutputValue = function () {
  79912. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  79913. outputBufferOffset += 4;
  79914. return value;
  79915. };
  79916. break;
  79917. }
  79918. case "scaling": {
  79919. getNextOutputValue = function () {
  79920. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  79921. outputBufferOffset += 3;
  79922. return value;
  79923. };
  79924. break;
  79925. }
  79926. case "influence": {
  79927. getNextOutputValue = function () {
  79928. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  79929. var value = new Array(numTargets);
  79930. for (var i = 0; i < numTargets; i++) {
  79931. value[i] = outputData[outputBufferOffset++];
  79932. }
  79933. return value;
  79934. };
  79935. break;
  79936. }
  79937. }
  79938. var getNextKey;
  79939. switch (sampler.interpolation) {
  79940. case "LINEAR": {
  79941. getNextKey = function (frameIndex) { return ({
  79942. frame: inputData[frameIndex],
  79943. value: getNextOutputValue()
  79944. }); };
  79945. break;
  79946. }
  79947. case "CUBICSPLINE": {
  79948. getNextKey = function (frameIndex) { return ({
  79949. frame: inputData[frameIndex],
  79950. inTangent: getNextOutputValue(),
  79951. value: getNextOutputValue(),
  79952. outTangent: getNextOutputValue()
  79953. }); };
  79954. break;
  79955. }
  79956. default: {
  79957. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  79958. }
  79959. }
  79960. ;
  79961. var keys = new Array(inputData.length);
  79962. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  79963. keys[frameIndex] = getNextKey(frameIndex);
  79964. }
  79965. if (targetPath === "influence") {
  79966. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  79967. var _loop_7 = function (targetIndex) {
  79968. var morphTarget = morphTargetManager.getTarget(targetIndex);
  79969. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  79970. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  79971. babylonAnimation.setKeys(keys.map(function (key) { return ({
  79972. frame: key.frame,
  79973. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  79974. value: key.value[targetIndex],
  79975. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  79976. }); }));
  79977. morphTarget.animations.push(babylonAnimation);
  79978. animation.targets.push(morphTarget);
  79979. };
  79980. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  79981. _loop_7(targetIndex);
  79982. }
  79983. }
  79984. else {
  79985. var animationName = animation.name || "anim" + animation.index;
  79986. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  79987. babylonAnimation.setKeys(keys);
  79988. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  79989. var target = _a[_i];
  79990. target.animations.push(babylonAnimation.clone());
  79991. animation.targets.push(target);
  79992. }
  79993. }
  79994. };
  79995. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  79996. if (!inputAccessor) {
  79997. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  79998. }
  79999. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  80000. inputData = data;
  80001. checkSuccess();
  80002. });
  80003. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  80004. if (!outputAccessor) {
  80005. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  80006. }
  80007. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  80008. outputData = data;
  80009. checkSuccess();
  80010. });
  80011. };
  80012. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  80013. var _this = this;
  80014. this._addPendingData(buffer);
  80015. if (buffer.loadedData) {
  80016. onSuccess(buffer.loadedData);
  80017. this._removePendingData(buffer);
  80018. }
  80019. else if (buffer.loadedObservable) {
  80020. buffer.loadedObservable.add(function (buffer) {
  80021. onSuccess(buffer.loadedData);
  80022. _this._removePendingData(buffer);
  80023. });
  80024. }
  80025. else {
  80026. if (!buffer.uri) {
  80027. throw new Error(context + ": Uri is missing");
  80028. }
  80029. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  80030. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  80031. buffer.loadedData = new Uint8Array(data);
  80032. onSuccess(buffer.loadedData);
  80033. this._removePendingData(buffer);
  80034. }
  80035. else {
  80036. buffer.loadedObservable = new BABYLON.Observable();
  80037. buffer.loadedObservable.add(function (buffer) {
  80038. onSuccess(buffer.loadedData);
  80039. _this._removePendingData(buffer);
  80040. });
  80041. this._loadUri(context, buffer.uri, function (data) {
  80042. buffer.loadedData = data;
  80043. buffer.loadedObservable.notifyObservers(buffer);
  80044. buffer.loadedObservable = undefined;
  80045. });
  80046. }
  80047. }
  80048. };
  80049. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  80050. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  80051. if (!buffer) {
  80052. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  80053. }
  80054. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  80055. var data;
  80056. try {
  80057. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  80058. }
  80059. catch (e) {
  80060. throw new Error(context + ": " + e.message);
  80061. }
  80062. onSuccess(data);
  80063. });
  80064. };
  80065. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  80066. var _this = this;
  80067. if (accessor.sparse) {
  80068. throw new Error(context + ": Sparse accessors are not currently supported");
  80069. }
  80070. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  80071. if (!bufferView) {
  80072. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  80073. }
  80074. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  80075. var numComponents = GLTFLoader._GetNumComponents(accessor.type);
  80076. if (numComponents === 0) {
  80077. throw new Error(context + ": Invalid type " + accessor.type);
  80078. }
  80079. var data;
  80080. var byteOffset = accessor.byteOffset || 0;
  80081. var byteStride = bufferView.byteStride;
  80082. try {
  80083. switch (accessor.componentType) {
  80084. case GLTF2.EComponentType.BYTE: {
  80085. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  80086. break;
  80087. }
  80088. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  80089. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  80090. break;
  80091. }
  80092. case GLTF2.EComponentType.SHORT: {
  80093. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  80094. break;
  80095. }
  80096. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  80097. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  80098. break;
  80099. }
  80100. case GLTF2.EComponentType.UNSIGNED_INT: {
  80101. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  80102. break;
  80103. }
  80104. case GLTF2.EComponentType.FLOAT: {
  80105. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  80106. break;
  80107. }
  80108. default: {
  80109. throw new Error(context + ": Invalid component type " + accessor.componentType);
  80110. }
  80111. }
  80112. }
  80113. catch (e) {
  80114. throw new Error(context + ": " + e);
  80115. }
  80116. onSuccess(data);
  80117. });
  80118. };
  80119. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  80120. byteOffset += data.byteOffset;
  80121. var targetLength = count * numComponents;
  80122. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  80123. return new typedArray(data.buffer, byteOffset, targetLength);
  80124. }
  80125. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  80126. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  80127. var targetBuffer = new typedArray(targetLength);
  80128. var sourceIndex = 0;
  80129. var targetIndex = 0;
  80130. while (targetIndex < targetLength) {
  80131. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  80132. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  80133. targetIndex++;
  80134. }
  80135. sourceIndex += elementStride;
  80136. }
  80137. return targetBuffer;
  80138. };
  80139. GLTFLoader.prototype._addPendingData = function (data) {
  80140. if (!this._renderReady) {
  80141. this._renderPendingCount++;
  80142. }
  80143. this._addLoaderPendingData(data);
  80144. };
  80145. GLTFLoader.prototype._removePendingData = function (data) {
  80146. if (!this._renderReady) {
  80147. if (--this._renderPendingCount === 0) {
  80148. this._renderReady = true;
  80149. this._onRenderReady();
  80150. }
  80151. }
  80152. this._removeLoaderPendingData(data);
  80153. };
  80154. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  80155. this._loaderPendingCount++;
  80156. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  80157. var tracker = _a[_i];
  80158. tracker._addPendingData(data);
  80159. }
  80160. };
  80161. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  80162. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  80163. var tracker = _a[_i];
  80164. tracker._removePendingData(data);
  80165. }
  80166. if (--this._loaderPendingCount === 0) {
  80167. this._onComplete();
  80168. }
  80169. };
  80170. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  80171. var _this = this;
  80172. var tracker = new GLTFLoaderTracker(function () {
  80173. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  80174. onComplete();
  80175. });
  80176. this._loaderTrackers.push(tracker);
  80177. this._addLoaderPendingData(tracker);
  80178. action();
  80179. this._removeLoaderPendingData(tracker);
  80180. };
  80181. GLTFLoader.prototype._getDefaultMaterial = function () {
  80182. if (!this._defaultMaterial) {
  80183. var id = "__gltf_default";
  80184. var material = this._babylonScene.getMaterialByName(id);
  80185. if (!material) {
  80186. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  80187. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  80188. material.metallic = 1;
  80189. material.roughness = 1;
  80190. }
  80191. this._defaultMaterial = material;
  80192. }
  80193. return this._defaultMaterial;
  80194. };
  80195. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  80196. var babylonMaterial = material.babylonMaterial;
  80197. // Ensure metallic workflow
  80198. babylonMaterial.metallic = 1;
  80199. babylonMaterial.roughness = 1;
  80200. var properties = material.pbrMetallicRoughness;
  80201. if (!properties) {
  80202. return;
  80203. }
  80204. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  80205. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  80206. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  80207. if (properties.baseColorTexture) {
  80208. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  80209. if (!texture) {
  80210. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  80211. }
  80212. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  80213. }
  80214. if (properties.metallicRoughnessTexture) {
  80215. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  80216. if (!texture) {
  80217. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  80218. }
  80219. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  80220. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  80221. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  80222. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  80223. }
  80224. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  80225. };
  80226. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  80227. if (material.babylonMaterial) {
  80228. assign(material.babylonMaterial, false);
  80229. return;
  80230. }
  80231. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  80232. return;
  80233. }
  80234. this._createPbrMaterial(material);
  80235. this._loadMaterialBaseProperties(context, material);
  80236. this._loadMaterialMetallicRoughnessProperties(context, material);
  80237. assign(material.babylonMaterial, true);
  80238. };
  80239. GLTFLoader.prototype._createPbrMaterial = function (material) {
  80240. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  80241. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  80242. material.babylonMaterial = babylonMaterial;
  80243. };
  80244. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  80245. var babylonMaterial = material.babylonMaterial;
  80246. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  80247. if (material.doubleSided) {
  80248. babylonMaterial.backFaceCulling = false;
  80249. babylonMaterial.twoSidedLighting = true;
  80250. }
  80251. if (material.normalTexture) {
  80252. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  80253. if (!texture) {
  80254. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  80255. }
  80256. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  80257. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  80258. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  80259. if (material.normalTexture.scale != null) {
  80260. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  80261. }
  80262. }
  80263. if (material.occlusionTexture) {
  80264. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  80265. if (!texture) {
  80266. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  80267. }
  80268. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  80269. babylonMaterial.useAmbientInGrayScale = true;
  80270. if (material.occlusionTexture.strength != null) {
  80271. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  80272. }
  80273. }
  80274. if (material.emissiveTexture) {
  80275. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  80276. if (!texture) {
  80277. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  80278. }
  80279. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  80280. }
  80281. };
  80282. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  80283. var babylonMaterial = material.babylonMaterial;
  80284. var alphaMode = material.alphaMode || "OPAQUE";
  80285. switch (alphaMode) {
  80286. case "OPAQUE": {
  80287. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  80288. break;
  80289. }
  80290. case "MASK": {
  80291. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  80292. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  80293. if (colorFactor) {
  80294. if (colorFactor[3] == 0) {
  80295. babylonMaterial.alphaCutOff = 1;
  80296. }
  80297. else {
  80298. babylonMaterial.alphaCutOff /= colorFactor[3];
  80299. }
  80300. }
  80301. if (babylonMaterial.albedoTexture) {
  80302. babylonMaterial.albedoTexture.hasAlpha = true;
  80303. }
  80304. break;
  80305. }
  80306. case "BLEND": {
  80307. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  80308. if (colorFactor) {
  80309. babylonMaterial.alpha = colorFactor[3];
  80310. }
  80311. if (babylonMaterial.albedoTexture) {
  80312. babylonMaterial.albedoTexture.hasAlpha = true;
  80313. babylonMaterial.useAlphaFromAlbedoTexture = true;
  80314. }
  80315. break;
  80316. }
  80317. default: {
  80318. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  80319. }
  80320. }
  80321. };
  80322. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  80323. var _this = this;
  80324. var sampler = (texture.sampler == null ? {} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  80325. if (!sampler) {
  80326. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  80327. }
  80328. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  80329. var samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  80330. this._addPendingData(texture);
  80331. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  80332. _this._tryCatchOnError(function () {
  80333. _this._removePendingData(texture);
  80334. });
  80335. }, function (message) {
  80336. _this._tryCatchOnError(function () {
  80337. throw new Error(context + ": " + message);
  80338. });
  80339. });
  80340. if (texture.url) {
  80341. babylonTexture.updateURL(texture.url);
  80342. }
  80343. else if (texture.dataReadyObservable) {
  80344. texture.dataReadyObservable.add(function (texture) {
  80345. babylonTexture.updateURL(texture.url);
  80346. });
  80347. }
  80348. else {
  80349. texture.dataReadyObservable = new BABYLON.Observable();
  80350. texture.dataReadyObservable.add(function (texture) {
  80351. babylonTexture.updateURL(texture.url);
  80352. });
  80353. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  80354. if (!image_1) {
  80355. throw new Error(context + ": Failed to find source " + texture.source);
  80356. }
  80357. this._loadImage("#/images/" + image_1.index, image_1, function (data) {
  80358. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  80359. texture.dataReadyObservable.notifyObservers(texture);
  80360. texture.dataReadyObservable = undefined;
  80361. });
  80362. }
  80363. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  80364. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  80365. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  80366. babylonTexture.name = texture.name || "texture" + texture.index;
  80367. if (this._parent.onTextureLoaded) {
  80368. this._parent.onTextureLoaded(babylonTexture);
  80369. }
  80370. return babylonTexture;
  80371. };
  80372. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  80373. if (image.uri) {
  80374. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  80375. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  80376. }
  80377. else {
  80378. this._loadUri(context, image.uri, onSuccess);
  80379. }
  80380. }
  80381. else {
  80382. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  80383. if (!bufferView) {
  80384. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  80385. }
  80386. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  80387. }
  80388. };
  80389. GLTFLoader.prototype._loadUri = function (context, uri, onSuccess) {
  80390. var _this = this;
  80391. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  80392. throw new Error(context + ": Uri '" + uri + "' is invalid");
  80393. }
  80394. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  80395. _this._tryCatchOnError(function () {
  80396. onSuccess(new Uint8Array(data));
  80397. });
  80398. }, function (event) {
  80399. _this._tryCatchOnError(function () {
  80400. _this._onProgress(event);
  80401. });
  80402. }, this._babylonScene.database, true, function (request) {
  80403. _this._tryCatchOnError(function () {
  80404. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  80405. });
  80406. });
  80407. if (request) {
  80408. this._requests.push(request);
  80409. }
  80410. };
  80411. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  80412. if (this._disposed) {
  80413. return;
  80414. }
  80415. try {
  80416. handler();
  80417. }
  80418. catch (e) {
  80419. BABYLON.Tools.Error("glTF Loader: " + e.message);
  80420. if (this._errorCallback) {
  80421. this._errorCallback(e.message);
  80422. }
  80423. this.dispose();
  80424. }
  80425. };
  80426. GLTFLoader._AssignIndices = function (array) {
  80427. if (array) {
  80428. for (var index = 0; index < array.length; index++) {
  80429. array[index].index = index;
  80430. }
  80431. }
  80432. };
  80433. GLTFLoader._GetProperty = function (array, index) {
  80434. if (!array || index == undefined || !array[index]) {
  80435. return null;
  80436. }
  80437. return array[index];
  80438. };
  80439. GLTFLoader._GetTextureWrapMode = function (mode) {
  80440. // Set defaults if undefined
  80441. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  80442. switch (mode) {
  80443. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  80444. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  80445. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  80446. default:
  80447. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  80448. return BABYLON.Texture.WRAP_ADDRESSMODE;
  80449. }
  80450. };
  80451. GLTFLoader._GetTextureSamplingMode = function (magFilter, minFilter) {
  80452. // Set defaults if undefined
  80453. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  80454. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  80455. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  80456. switch (minFilter) {
  80457. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  80458. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  80459. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  80460. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  80461. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  80462. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  80463. default:
  80464. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  80465. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  80466. }
  80467. }
  80468. else {
  80469. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  80470. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  80471. }
  80472. switch (minFilter) {
  80473. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  80474. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  80475. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  80476. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  80477. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  80478. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  80479. default:
  80480. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  80481. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  80482. }
  80483. }
  80484. };
  80485. GLTFLoader._GetNumComponents = function (type) {
  80486. switch (type) {
  80487. case "SCALAR": return 1;
  80488. case "VEC2": return 2;
  80489. case "VEC3": return 3;
  80490. case "VEC4": return 4;
  80491. case "MAT2": return 4;
  80492. case "MAT3": return 9;
  80493. case "MAT4": return 16;
  80494. }
  80495. return 0;
  80496. };
  80497. GLTFLoader.Extensions = {};
  80498. return GLTFLoader;
  80499. }());
  80500. GLTF2.GLTFLoader = GLTFLoader;
  80501. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  80502. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80503. })(BABYLON || (BABYLON = {}));
  80504. //# sourceMappingURL=babylon.glTFLoader.js.map
  80505. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80506. var BABYLON;
  80507. (function (BABYLON) {
  80508. var GLTF2;
  80509. (function (GLTF2) {
  80510. /**
  80511. * Utils functions for GLTF
  80512. */
  80513. var GLTFUtils = /** @class */ (function () {
  80514. function GLTFUtils() {
  80515. }
  80516. /**
  80517. * If the uri is a base64 string
  80518. * @param uri: the uri to test
  80519. */
  80520. GLTFUtils.IsBase64 = function (uri) {
  80521. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  80522. };
  80523. /**
  80524. * Decode the base64 uri
  80525. * @param uri: the uri to decode
  80526. */
  80527. GLTFUtils.DecodeBase64 = function (uri) {
  80528. var decodedString = atob(uri.split(",")[1]);
  80529. var bufferLength = decodedString.length;
  80530. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  80531. for (var i = 0; i < bufferLength; i++) {
  80532. bufferView[i] = decodedString.charCodeAt(i);
  80533. }
  80534. return bufferView.buffer;
  80535. };
  80536. GLTFUtils.ValidateUri = function (uri) {
  80537. return (uri.indexOf("..") === -1);
  80538. };
  80539. return GLTFUtils;
  80540. }());
  80541. GLTF2.GLTFUtils = GLTFUtils;
  80542. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80543. })(BABYLON || (BABYLON = {}));
  80544. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  80545. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80546. var BABYLON;
  80547. (function (BABYLON) {
  80548. var GLTF2;
  80549. (function (GLTF2) {
  80550. var GLTFLoaderExtension = /** @class */ (function () {
  80551. function GLTFLoaderExtension() {
  80552. this.enabled = true;
  80553. }
  80554. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  80555. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  80556. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  80557. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  80558. var _this = this;
  80559. if (!property.extensions) {
  80560. return false;
  80561. }
  80562. var extension = property.extensions[this.name];
  80563. if (!extension) {
  80564. return false;
  80565. }
  80566. // Clear out the extension before executing the action to avoid recursing into the same property.
  80567. property.extensions[this.name] = undefined;
  80568. action(context + "extensions/" + this.name, extension, function () {
  80569. // Restore the extension after completing the action.
  80570. property.extensions[_this.name] = extension;
  80571. });
  80572. return true;
  80573. };
  80574. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  80575. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  80576. };
  80577. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  80578. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  80579. };
  80580. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  80581. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  80582. };
  80583. GLTFLoaderExtension._ApplyExtensions = function (action) {
  80584. var extensions = GLTFLoaderExtension._Extensions;
  80585. if (!extensions) {
  80586. return false;
  80587. }
  80588. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  80589. var extension = extensions_1[_i];
  80590. if (extension.enabled && action(extension)) {
  80591. return true;
  80592. }
  80593. }
  80594. return false;
  80595. };
  80596. //
  80597. // Utilities
  80598. //
  80599. GLTFLoaderExtension._Extensions = [];
  80600. return GLTFLoaderExtension;
  80601. }());
  80602. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  80603. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80604. })(BABYLON || (BABYLON = {}));
  80605. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  80606. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  80607. var BABYLON;
  80608. (function (BABYLON) {
  80609. var GLTF2;
  80610. (function (GLTF2) {
  80611. var Extensions;
  80612. (function (Extensions) {
  80613. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  80614. var MSFTLOD = /** @class */ (function (_super) {
  80615. __extends(MSFTLOD, _super);
  80616. function MSFTLOD() {
  80617. return _super !== null && _super.apply(this, arguments) || this;
  80618. }
  80619. Object.defineProperty(MSFTLOD.prototype, "name", {
  80620. get: function () {
  80621. return "MSFT_lod";
  80622. },
  80623. enumerable: true,
  80624. configurable: true
  80625. });
  80626. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  80627. return this._loadExtension(context, node, function (context, extension, onComplete) {
  80628. for (var i = extension.ids.length - 1; i >= 0; i--) {
  80629. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  80630. if (!lodNode) {
  80631. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  80632. }
  80633. loader._traverseNode(context, lodNode, action, parentNode);
  80634. }
  80635. loader._traverseNode(context, node, action, parentNode);
  80636. onComplete();
  80637. });
  80638. };
  80639. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  80640. var _this = this;
  80641. return this._loadExtension(context, node, function (context, extension, onComplete) {
  80642. var nodes = [node];
  80643. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  80644. var index = _a[_i];
  80645. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  80646. if (!lodNode) {
  80647. throw new Error(context + ": Failed to find node " + index);
  80648. }
  80649. nodes.push(lodNode);
  80650. }
  80651. loader._addLoaderPendingData(node);
  80652. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  80653. loader._removeLoaderPendingData(node);
  80654. onComplete();
  80655. });
  80656. });
  80657. };
  80658. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  80659. var _this = this;
  80660. loader._whenAction(function () {
  80661. loader._loadNode(context, nodes[index]);
  80662. }, function () {
  80663. if (index !== nodes.length - 1) {
  80664. var previousNode = nodes[index + 1];
  80665. previousNode.babylonMesh.setEnabled(false);
  80666. }
  80667. if (index === 0) {
  80668. onComplete();
  80669. return;
  80670. }
  80671. setTimeout(function () {
  80672. loader._tryCatchOnError(function () {
  80673. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  80674. });
  80675. }, MSFTLOD.MinimalLODDelay);
  80676. });
  80677. };
  80678. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  80679. var _this = this;
  80680. return this._loadExtension(context, material, function (context, extension, onComplete) {
  80681. var materials = [material];
  80682. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  80683. var index = _a[_i];
  80684. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  80685. if (!lodMaterial) {
  80686. throw new Error(context + ": Failed to find material " + index);
  80687. }
  80688. materials.push(lodMaterial);
  80689. }
  80690. loader._addLoaderPendingData(material);
  80691. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  80692. loader._removeLoaderPendingData(material);
  80693. onComplete();
  80694. });
  80695. });
  80696. };
  80697. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  80698. var _this = this;
  80699. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  80700. assign(babylonMaterial, isNew);
  80701. if (index === 0) {
  80702. onComplete();
  80703. return;
  80704. }
  80705. // Load the next LOD when the loader is ready to render and
  80706. // all active material textures of the current LOD are loaded.
  80707. loader._executeWhenRenderReady(function () {
  80708. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  80709. setTimeout(function () {
  80710. loader._tryCatchOnError(function () {
  80711. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  80712. });
  80713. }, MSFTLOD.MinimalLODDelay);
  80714. });
  80715. });
  80716. });
  80717. };
  80718. /**
  80719. * Specify the minimal delay between LODs in ms (default = 250)
  80720. */
  80721. MSFTLOD.MinimalLODDelay = 250;
  80722. return MSFTLOD;
  80723. }(GLTF2.GLTFLoaderExtension));
  80724. Extensions.MSFTLOD = MSFTLOD;
  80725. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  80726. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  80727. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80728. })(BABYLON || (BABYLON = {}));
  80729. //# sourceMappingURL=MSFT_lod.js.map
  80730. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  80731. var BABYLON;
  80732. (function (BABYLON) {
  80733. var GLTF2;
  80734. (function (GLTF2) {
  80735. var Extensions;
  80736. (function (Extensions) {
  80737. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  80738. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  80739. function KHRMaterialsPbrSpecularGlossiness() {
  80740. return _super !== null && _super.apply(this, arguments) || this;
  80741. }
  80742. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  80743. get: function () {
  80744. return "KHR_materials_pbrSpecularGlossiness";
  80745. },
  80746. enumerable: true,
  80747. configurable: true
  80748. });
  80749. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  80750. var _this = this;
  80751. return this._loadExtension(context, material, function (context, extension, onComplete) {
  80752. loader._createPbrMaterial(material);
  80753. loader._loadMaterialBaseProperties(context, material);
  80754. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  80755. assign(material.babylonMaterial, true);
  80756. });
  80757. };
  80758. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  80759. var babylonMaterial = material.babylonMaterial;
  80760. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  80761. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  80762. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  80763. if (properties.diffuseTexture) {
  80764. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  80765. if (!texture) {
  80766. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  80767. }
  80768. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  80769. }
  80770. if (properties.specularGlossinessTexture) {
  80771. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  80772. if (!texture) {
  80773. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  80774. }
  80775. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  80776. babylonMaterial.reflectivityTexture.hasAlpha = true;
  80777. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  80778. }
  80779. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  80780. };
  80781. return KHRMaterialsPbrSpecularGlossiness;
  80782. }(GLTF2.GLTFLoaderExtension));
  80783. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  80784. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  80785. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  80786. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80787. })(BABYLON || (BABYLON = {}));
  80788. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  80789. (function universalModuleDefinition(root, factory) {
  80790. var f = factory();
  80791. if (root && root["BABYLON"]) {
  80792. return;
  80793. }
  80794. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  80795. globalObject["BABYLON"] = f;
  80796. if(typeof exports === 'object' && typeof module === 'object')
  80797. module.exports = f;
  80798. else if(typeof define === 'function' && define.amd)
  80799. define(["BABYLON"], factory);
  80800. else if(typeof exports === 'object')
  80801. exports["BABYLON"] = f;
  80802. else {
  80803. root["BABYLON"] = f;
  80804. }
  80805. })(this, function() {
  80806. return BABYLON;
  80807. });