babylon.max.js 3.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798
  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._duplicateId = 0;
  5617. this.data = new Array(capacity);
  5618. this._id = SmartArray._GlobalId++;
  5619. }
  5620. SmartArray.prototype.push = function (value) {
  5621. this.data[this.length++] = value;
  5622. if (this.length > this.data.length) {
  5623. this.data.length *= 2;
  5624. }
  5625. if (!value.__smartArrayFlags) {
  5626. value.__smartArrayFlags = {};
  5627. }
  5628. value.__smartArrayFlags[this._id] = this._duplicateId;
  5629. };
  5630. SmartArray.prototype.forEach = function (func) {
  5631. for (var index = 0; index < this.length; index++) {
  5632. func(this.data[index]);
  5633. }
  5634. };
  5635. SmartArray.prototype.pushNoDuplicate = function (value) {
  5636. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5637. return false;
  5638. }
  5639. this.push(value);
  5640. return true;
  5641. };
  5642. SmartArray.prototype.sort = function (compareFn) {
  5643. this.data.sort(compareFn);
  5644. };
  5645. SmartArray.prototype.reset = function () {
  5646. this.length = 0;
  5647. this._duplicateId++;
  5648. };
  5649. SmartArray.prototype.dispose = function () {
  5650. this.reset();
  5651. if (this.data) {
  5652. this.data.length = 0;
  5653. this.data = [];
  5654. }
  5655. };
  5656. SmartArray.prototype.concat = function (array) {
  5657. if (array.length === 0) {
  5658. return;
  5659. }
  5660. if (this.length + array.length > this.data.length) {
  5661. this.data.length = (this.length + array.length) * 2;
  5662. }
  5663. for (var index = 0; index < array.length; index++) {
  5664. this.data[this.length++] = (array.data || array)[index];
  5665. }
  5666. };
  5667. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5668. if (array.length === 0) {
  5669. return;
  5670. }
  5671. if (this.length + array.length > this.data.length) {
  5672. this.data.length = (this.length + array.length) * 2;
  5673. }
  5674. for (var index = 0; index < array.length; index++) {
  5675. var item = (array.data || array)[index];
  5676. this.pushNoDuplicate(item);
  5677. }
  5678. };
  5679. SmartArray.prototype.indexOf = function (value) {
  5680. var position = this.data.indexOf(value);
  5681. if (position >= this.length) {
  5682. return -1;
  5683. }
  5684. return position;
  5685. };
  5686. SmartArray.prototype.contains = function (value) {
  5687. return this.data.indexOf(value) !== -1;
  5688. };
  5689. // Statics
  5690. SmartArray._GlobalId = 0;
  5691. return SmartArray;
  5692. }());
  5693. BABYLON.SmartArray = SmartArray;
  5694. })(BABYLON || (BABYLON = {}));
  5695. //# sourceMappingURL=babylon.smartArray.js.map
  5696. var BABYLON;
  5697. (function (BABYLON) {
  5698. // Screenshots
  5699. var screenshotCanvas;
  5700. var cloneValue = function (source, destinationObject) {
  5701. if (!source)
  5702. return null;
  5703. if (source instanceof BABYLON.Mesh) {
  5704. return null;
  5705. }
  5706. if (source instanceof BABYLON.SubMesh) {
  5707. return source.clone(destinationObject);
  5708. }
  5709. else if (source.clone) {
  5710. return source.clone();
  5711. }
  5712. return null;
  5713. };
  5714. var Tools = /** @class */ (function () {
  5715. function Tools() {
  5716. }
  5717. ;
  5718. /**
  5719. * Interpolates between a and b via alpha
  5720. * @param a The lower value (returned when alpha = 0)
  5721. * @param b The upper value (returned when alpha = 1)
  5722. * @param alpha The interpolation-factor
  5723. * @return The mixed value
  5724. */
  5725. Tools.Mix = function (a, b, alpha) {
  5726. return a * (1 - alpha) + b * alpha;
  5727. };
  5728. Tools.Instantiate = function (className) {
  5729. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5730. return Tools.RegisteredExternalClasses[className];
  5731. }
  5732. var arr = className.split(".");
  5733. var fn = (window || this);
  5734. for (var i = 0, len = arr.length; i < len; i++) {
  5735. fn = fn[arr[i]];
  5736. }
  5737. if (typeof fn !== "function") {
  5738. return null;
  5739. }
  5740. return fn;
  5741. };
  5742. Tools.SetImmediate = function (action) {
  5743. if (window.setImmediate) {
  5744. window.setImmediate(action);
  5745. }
  5746. else {
  5747. setTimeout(action, 1);
  5748. }
  5749. };
  5750. Tools.IsExponentOfTwo = function (value) {
  5751. var count = 1;
  5752. do {
  5753. count *= 2;
  5754. } while (count < value);
  5755. return count === value;
  5756. };
  5757. /**
  5758. * Find the next highest power of two.
  5759. * @param x Number to start search from.
  5760. * @return Next highest power of two.
  5761. */
  5762. Tools.CeilingPOT = function (x) {
  5763. x--;
  5764. x |= x >> 1;
  5765. x |= x >> 2;
  5766. x |= x >> 4;
  5767. x |= x >> 8;
  5768. x |= x >> 16;
  5769. x++;
  5770. return x;
  5771. };
  5772. /**
  5773. * Find the next lowest power of two.
  5774. * @param x Number to start search from.
  5775. * @return Next lowest power of two.
  5776. */
  5777. Tools.FloorPOT = function (x) {
  5778. x = x | (x >> 1);
  5779. x = x | (x >> 2);
  5780. x = x | (x >> 4);
  5781. x = x | (x >> 8);
  5782. x = x | (x >> 16);
  5783. return x - (x >> 1);
  5784. };
  5785. /**
  5786. * Find the nearest power of two.
  5787. * @param x Number to start search from.
  5788. * @return Next nearest power of two.
  5789. */
  5790. Tools.NearestPOT = function (x) {
  5791. var c = Tools.CeilingPOT(x);
  5792. var f = Tools.FloorPOT(x);
  5793. return (c - x) > (x - f) ? f : c;
  5794. };
  5795. Tools.GetExponentOfTwo = function (value, max, mode) {
  5796. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5797. var pot;
  5798. switch (mode) {
  5799. case BABYLON.Engine.SCALEMODE_FLOOR:
  5800. pot = Tools.FloorPOT(value);
  5801. break;
  5802. case BABYLON.Engine.SCALEMODE_NEAREST:
  5803. pot = Tools.NearestPOT(value);
  5804. break;
  5805. case BABYLON.Engine.SCALEMODE_CEILING:
  5806. default:
  5807. pot = Tools.CeilingPOT(value);
  5808. break;
  5809. }
  5810. return Math.min(pot, max);
  5811. };
  5812. Tools.GetFilename = function (path) {
  5813. var index = path.lastIndexOf("/");
  5814. if (index < 0)
  5815. return path;
  5816. return path.substring(index + 1);
  5817. };
  5818. Tools.GetDOMTextContent = function (element) {
  5819. var result = "";
  5820. var child = element.firstChild;
  5821. while (child) {
  5822. if (child.nodeType === 3) {
  5823. result += child.textContent;
  5824. }
  5825. child = child.nextSibling;
  5826. }
  5827. return result;
  5828. };
  5829. Tools.ToDegrees = function (angle) {
  5830. return angle * 180 / Math.PI;
  5831. };
  5832. Tools.ToRadians = function (angle) {
  5833. return angle * Math.PI / 180;
  5834. };
  5835. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5836. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5837. var output = "";
  5838. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5839. var i = 0;
  5840. var bytes = new Uint8Array(buffer);
  5841. while (i < bytes.length) {
  5842. chr1 = bytes[i++];
  5843. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5844. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5845. enc1 = chr1 >> 2;
  5846. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5847. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5848. enc4 = chr3 & 63;
  5849. if (isNaN(chr2)) {
  5850. enc3 = enc4 = 64;
  5851. }
  5852. else if (isNaN(chr3)) {
  5853. enc4 = 64;
  5854. }
  5855. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5856. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5857. }
  5858. return "data:image/png;base64," + output;
  5859. };
  5860. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5861. if (bias === void 0) { bias = null; }
  5862. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5863. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5864. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5865. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5866. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5867. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5868. }
  5869. if (bias) {
  5870. minimum.x -= minimum.x * bias.x + bias.y;
  5871. minimum.y -= minimum.y * bias.x + bias.y;
  5872. minimum.z -= minimum.z * bias.x + bias.y;
  5873. maximum.x += maximum.x * bias.x + bias.y;
  5874. maximum.y += maximum.y * bias.x + bias.y;
  5875. maximum.z += maximum.z * bias.x + bias.y;
  5876. }
  5877. return {
  5878. minimum: minimum,
  5879. maximum: maximum
  5880. };
  5881. };
  5882. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5883. if (bias === void 0) { bias = null; }
  5884. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5885. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5886. if (!stride) {
  5887. stride = 3;
  5888. }
  5889. for (var index = start; index < start + count; index++) {
  5890. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5891. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5892. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5893. }
  5894. if (bias) {
  5895. minimum.x -= minimum.x * bias.x + bias.y;
  5896. minimum.y -= minimum.y * bias.x + bias.y;
  5897. minimum.z -= minimum.z * bias.x + bias.y;
  5898. maximum.x += maximum.x * bias.x + bias.y;
  5899. maximum.y += maximum.y * bias.x + bias.y;
  5900. maximum.z += maximum.z * bias.x + bias.y;
  5901. }
  5902. return {
  5903. minimum: minimum,
  5904. maximum: maximum
  5905. };
  5906. };
  5907. Tools.Vector2ArrayFeeder = function (array) {
  5908. return function (index) {
  5909. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5910. var length = isFloatArray ? array.length / 2 : array.length;
  5911. if (index >= length) {
  5912. return null;
  5913. }
  5914. if (isFloatArray) {
  5915. var fa = array;
  5916. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5917. }
  5918. var a = array;
  5919. return a[index];
  5920. };
  5921. };
  5922. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5923. if (bias === void 0) { bias = null; }
  5924. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5925. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5926. var i = 0;
  5927. var cur = feeder(i++);
  5928. while (cur) {
  5929. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5930. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5931. cur = feeder(i++);
  5932. }
  5933. if (bias) {
  5934. minimum.x -= minimum.x * bias.x + bias.y;
  5935. minimum.y -= minimum.y * bias.x + bias.y;
  5936. maximum.x += maximum.x * bias.x + bias.y;
  5937. maximum.y += maximum.y * bias.x + bias.y;
  5938. }
  5939. return {
  5940. minimum: minimum,
  5941. maximum: maximum
  5942. };
  5943. };
  5944. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5945. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5946. return null;
  5947. return Array.isArray(obj) ? obj : [obj];
  5948. };
  5949. // Misc.
  5950. Tools.GetPointerPrefix = function () {
  5951. var eventPrefix = "pointer";
  5952. // Check if pointer events are supported
  5953. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5954. eventPrefix = "mouse";
  5955. }
  5956. return eventPrefix;
  5957. };
  5958. /**
  5959. * @param func - the function to be called
  5960. * @param requester - the object that will request the next frame. Falls back to window.
  5961. */
  5962. Tools.QueueNewFrame = function (func, requester) {
  5963. if (!Tools.IsWindowObjectExist()) {
  5964. return setTimeout(func, 16);
  5965. }
  5966. if (!requester) {
  5967. requester = window;
  5968. }
  5969. if (requester.requestAnimationFrame) {
  5970. return requester.requestAnimationFrame(func);
  5971. }
  5972. else if (requester.msRequestAnimationFrame) {
  5973. return requester.msRequestAnimationFrame(func);
  5974. }
  5975. else if (requester.webkitRequestAnimationFrame) {
  5976. return requester.webkitRequestAnimationFrame(func);
  5977. }
  5978. else if (requester.mozRequestAnimationFrame) {
  5979. return requester.mozRequestAnimationFrame(func);
  5980. }
  5981. else if (requester.oRequestAnimationFrame) {
  5982. return requester.oRequestAnimationFrame(func);
  5983. }
  5984. else {
  5985. return window.setTimeout(func, 16);
  5986. }
  5987. };
  5988. Tools.RequestFullscreen = function (element) {
  5989. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5990. if (!requestFunction)
  5991. return;
  5992. requestFunction.call(element);
  5993. };
  5994. Tools.ExitFullscreen = function () {
  5995. if (document.exitFullscreen) {
  5996. document.exitFullscreen();
  5997. }
  5998. else if (document.mozCancelFullScreen) {
  5999. document.mozCancelFullScreen();
  6000. }
  6001. else if (document.webkitCancelFullScreen) {
  6002. document.webkitCancelFullScreen();
  6003. }
  6004. else if (document.msCancelFullScreen) {
  6005. document.msCancelFullScreen();
  6006. }
  6007. };
  6008. Tools.SetCorsBehavior = function (url, img) {
  6009. if (Tools.CorsBehavior) {
  6010. switch (typeof (Tools.CorsBehavior)) {
  6011. case "function":
  6012. var result = Tools.CorsBehavior(url);
  6013. if (result) {
  6014. img.crossOrigin = result;
  6015. }
  6016. break;
  6017. case "string":
  6018. default:
  6019. img.crossOrigin = Tools.CorsBehavior;
  6020. break;
  6021. }
  6022. }
  6023. };
  6024. // External files
  6025. Tools.CleanUrl = function (url) {
  6026. url = url.replace(/#/mg, "%23");
  6027. return url;
  6028. };
  6029. Tools.LoadImage = function (url, onLoad, onError, database) {
  6030. if (url instanceof ArrayBuffer) {
  6031. url = Tools.EncodeArrayBufferTobase64(url);
  6032. }
  6033. url = Tools.CleanUrl(url);
  6034. url = Tools.PreprocessUrl(url);
  6035. var img = new Image();
  6036. if (url.substr(0, 5) !== "data:") {
  6037. Tools.SetCorsBehavior(url, img);
  6038. }
  6039. img.onload = function () {
  6040. onLoad(img);
  6041. };
  6042. img.onerror = function (err) {
  6043. Tools.Error("Error while trying to load image: " + url);
  6044. if (Tools.UseFallbackTexture) {
  6045. img.src = Tools.fallbackTexture;
  6046. onLoad(img);
  6047. }
  6048. else {
  6049. onError("Error while trying to load image: " + url, err);
  6050. }
  6051. };
  6052. var noIndexedDB = function () {
  6053. img.src = url;
  6054. };
  6055. var loadFromIndexedDB = function () {
  6056. if (database) {
  6057. database.loadImageFromDB(url, img);
  6058. }
  6059. };
  6060. //ANY database to do!
  6061. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6062. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6063. }
  6064. else {
  6065. if (url.indexOf("file:") !== 0) {
  6066. noIndexedDB();
  6067. }
  6068. else {
  6069. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6070. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6071. try {
  6072. var blobURL;
  6073. try {
  6074. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6075. }
  6076. catch (ex) {
  6077. // Chrome doesn't support oneTimeOnly parameter
  6078. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6079. }
  6080. img.src = blobURL;
  6081. }
  6082. catch (e) {
  6083. img.src = "";
  6084. }
  6085. }
  6086. else {
  6087. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6088. img.src = Tools.fallbackTexture;
  6089. }
  6090. }
  6091. }
  6092. return img;
  6093. };
  6094. //ANY
  6095. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6096. url = Tools.CleanUrl(url);
  6097. url = Tools.PreprocessUrl(url);
  6098. var request = null;
  6099. var noIndexedDB = function () {
  6100. request = new XMLHttpRequest();
  6101. var loadUrl = Tools.BaseUrl + url;
  6102. request.open('GET', loadUrl, true);
  6103. if (useArrayBuffer) {
  6104. request.responseType = "arraybuffer";
  6105. }
  6106. if (progressCallBack) {
  6107. request.onprogress = progressCallBack;
  6108. }
  6109. request.onreadystatechange = function () {
  6110. var req = request;
  6111. // In case of undefined state in some browsers.
  6112. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6113. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6114. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6115. callback(!useArrayBuffer ? req.responseText : req.response);
  6116. }
  6117. else {
  6118. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6119. if (onError) {
  6120. onError(req, e);
  6121. }
  6122. else {
  6123. throw e;
  6124. }
  6125. }
  6126. }
  6127. };
  6128. request.send(null);
  6129. };
  6130. var loadFromIndexedDB = function () {
  6131. if (database) {
  6132. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6133. }
  6134. };
  6135. if (url.indexOf("file:") !== -1) {
  6136. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6137. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6138. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6139. }
  6140. else {
  6141. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6142. if (onError) {
  6143. var e = new Error(errorMessage);
  6144. onError(undefined, e);
  6145. }
  6146. else {
  6147. Tools.Error(errorMessage);
  6148. }
  6149. }
  6150. }
  6151. else {
  6152. // Caching all files
  6153. if (database && database.enableSceneOffline) {
  6154. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6155. }
  6156. else {
  6157. noIndexedDB();
  6158. }
  6159. }
  6160. return request;
  6161. };
  6162. /**
  6163. * Load a script (identified by an url). When the url returns, the
  6164. * content of this file is added into a new script element, attached to the DOM (body element)
  6165. */
  6166. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6167. var head = document.getElementsByTagName('head')[0];
  6168. var script = document.createElement('script');
  6169. script.type = 'text/javascript';
  6170. script.src = scriptUrl;
  6171. script.onload = function () {
  6172. if (onSuccess) {
  6173. onSuccess();
  6174. }
  6175. };
  6176. script.onerror = function (e) {
  6177. if (onError) {
  6178. onError("Unable to load script", e);
  6179. }
  6180. };
  6181. head.appendChild(script);
  6182. };
  6183. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6184. var reader = new FileReader();
  6185. reader.onload = function (e) {
  6186. //target doesn't have result from ts 1.3
  6187. callback(e.target['result']);
  6188. };
  6189. reader.onprogress = progressCallback;
  6190. reader.readAsDataURL(fileToLoad);
  6191. };
  6192. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6193. var reader = new FileReader();
  6194. reader.onerror = function (e) {
  6195. Tools.Log("Error while reading file: " + fileToLoad.name);
  6196. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6197. };
  6198. reader.onload = function (e) {
  6199. //target doesn't have result from ts 1.3
  6200. callback(e.target['result']);
  6201. };
  6202. if (progressCallBack) {
  6203. reader.onprogress = progressCallBack;
  6204. }
  6205. if (!useArrayBuffer) {
  6206. // Asynchronous read
  6207. reader.readAsText(fileToLoad);
  6208. }
  6209. else {
  6210. reader.readAsArrayBuffer(fileToLoad);
  6211. }
  6212. };
  6213. //returns a downloadable url to a file content.
  6214. Tools.FileAsURL = function (content) {
  6215. var fileBlob = new Blob([content]);
  6216. var url = window.URL || window.webkitURL;
  6217. var link = url.createObjectURL(fileBlob);
  6218. return link;
  6219. };
  6220. // Misc.
  6221. Tools.Format = function (value, decimals) {
  6222. if (decimals === void 0) { decimals = 2; }
  6223. return value.toFixed(decimals);
  6224. };
  6225. Tools.CheckExtends = function (v, min, max) {
  6226. if (v.x < min.x)
  6227. min.x = v.x;
  6228. if (v.y < min.y)
  6229. min.y = v.y;
  6230. if (v.z < min.z)
  6231. min.z = v.z;
  6232. if (v.x > max.x)
  6233. max.x = v.x;
  6234. if (v.y > max.y)
  6235. max.y = v.y;
  6236. if (v.z > max.z)
  6237. max.z = v.z;
  6238. };
  6239. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6240. for (var prop in source) {
  6241. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6242. continue;
  6243. }
  6244. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6245. continue;
  6246. }
  6247. var sourceValue = source[prop];
  6248. var typeOfSourceValue = typeof sourceValue;
  6249. if (typeOfSourceValue === "function") {
  6250. continue;
  6251. }
  6252. if (typeOfSourceValue === "object") {
  6253. if (sourceValue instanceof Array) {
  6254. destination[prop] = [];
  6255. if (sourceValue.length > 0) {
  6256. if (typeof sourceValue[0] == "object") {
  6257. for (var index = 0; index < sourceValue.length; index++) {
  6258. var clonedValue = cloneValue(sourceValue[index], destination);
  6259. if (destination[prop].indexOf(clonedValue) === -1) {
  6260. destination[prop].push(clonedValue);
  6261. }
  6262. }
  6263. }
  6264. else {
  6265. destination[prop] = sourceValue.slice(0);
  6266. }
  6267. }
  6268. }
  6269. else {
  6270. destination[prop] = cloneValue(sourceValue, destination);
  6271. }
  6272. }
  6273. else {
  6274. destination[prop] = sourceValue;
  6275. }
  6276. }
  6277. };
  6278. Tools.IsEmpty = function (obj) {
  6279. for (var i in obj) {
  6280. if (obj.hasOwnProperty(i)) {
  6281. return false;
  6282. }
  6283. }
  6284. return true;
  6285. };
  6286. Tools.RegisterTopRootEvents = function (events) {
  6287. for (var index = 0; index < events.length; index++) {
  6288. var event = events[index];
  6289. window.addEventListener(event.name, event.handler, false);
  6290. try {
  6291. if (window.parent) {
  6292. window.parent.addEventListener(event.name, event.handler, false);
  6293. }
  6294. }
  6295. catch (e) {
  6296. // Silently fails...
  6297. }
  6298. }
  6299. };
  6300. Tools.UnregisterTopRootEvents = function (events) {
  6301. for (var index = 0; index < events.length; index++) {
  6302. var event = events[index];
  6303. window.removeEventListener(event.name, event.handler);
  6304. try {
  6305. if (window.parent) {
  6306. window.parent.removeEventListener(event.name, event.handler);
  6307. }
  6308. }
  6309. catch (e) {
  6310. // Silently fails...
  6311. }
  6312. }
  6313. };
  6314. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6315. if (mimeType === void 0) { mimeType = "image/png"; }
  6316. // Read the contents of the framebuffer
  6317. var numberOfChannelsByLine = width * 4;
  6318. var halfHeight = height / 2;
  6319. //Reading datas from WebGL
  6320. var data = engine.readPixels(0, 0, width, height);
  6321. //To flip image on Y axis.
  6322. for (var i = 0; i < halfHeight; i++) {
  6323. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6324. var currentCell = j + i * numberOfChannelsByLine;
  6325. var targetLine = height - i - 1;
  6326. var targetCell = j + targetLine * numberOfChannelsByLine;
  6327. var temp = data[currentCell];
  6328. data[currentCell] = data[targetCell];
  6329. data[targetCell] = temp;
  6330. }
  6331. }
  6332. // Create a 2D canvas to store the result
  6333. if (!screenshotCanvas) {
  6334. screenshotCanvas = document.createElement('canvas');
  6335. }
  6336. screenshotCanvas.width = width;
  6337. screenshotCanvas.height = height;
  6338. var context = screenshotCanvas.getContext('2d');
  6339. if (context) {
  6340. // Copy the pixels to a 2D canvas
  6341. var imageData = context.createImageData(width, height);
  6342. var castData = (imageData.data);
  6343. castData.set(data);
  6344. context.putImageData(imageData, 0, 0);
  6345. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6346. }
  6347. };
  6348. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6349. if (mimeType === void 0) { mimeType = "image/png"; }
  6350. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6351. if (successCallback) {
  6352. successCallback(base64Image);
  6353. }
  6354. else {
  6355. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6356. if (("download" in document.createElement("a"))) {
  6357. var a = window.document.createElement("a");
  6358. a.href = base64Image;
  6359. var date = new Date();
  6360. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6361. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6362. window.document.body.appendChild(a);
  6363. a.addEventListener("click", function () {
  6364. if (a.parentElement) {
  6365. a.parentElement.removeChild(a);
  6366. }
  6367. });
  6368. a.click();
  6369. //Or opening a new tab with the image if it is not possible to automatically start download.
  6370. }
  6371. else {
  6372. var newWindow = window.open("");
  6373. var img = newWindow.document.createElement("img");
  6374. img.src = base64Image;
  6375. newWindow.document.body.appendChild(img);
  6376. }
  6377. }
  6378. };
  6379. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6380. if (mimeType === void 0) { mimeType = "image/png"; }
  6381. var width;
  6382. var height;
  6383. // If a precision value is specified
  6384. if (size.precision) {
  6385. width = Math.round(engine.getRenderWidth() * size.precision);
  6386. height = Math.round(width / engine.getAspectRatio(camera));
  6387. }
  6388. else if (size.width && size.height) {
  6389. width = size.width;
  6390. height = size.height;
  6391. }
  6392. else if (size.width && !size.height) {
  6393. width = size.width;
  6394. height = Math.round(width / engine.getAspectRatio(camera));
  6395. }
  6396. else if (size.height && !size.width) {
  6397. height = size.height;
  6398. width = Math.round(height * engine.getAspectRatio(camera));
  6399. }
  6400. else if (!isNaN(size)) {
  6401. height = size;
  6402. width = size;
  6403. }
  6404. else {
  6405. Tools.Error("Invalid 'size' parameter !");
  6406. return;
  6407. }
  6408. if (!screenshotCanvas) {
  6409. screenshotCanvas = document.createElement('canvas');
  6410. }
  6411. screenshotCanvas.width = width;
  6412. screenshotCanvas.height = height;
  6413. var renderContext = screenshotCanvas.getContext("2d");
  6414. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6415. var newWidth = width;
  6416. var newHeight = newWidth / ratio;
  6417. if (newHeight > height) {
  6418. newHeight = height;
  6419. newWidth = newHeight * ratio;
  6420. }
  6421. var offsetX = Math.max(0, width - newWidth) / 2;
  6422. var offsetY = Math.max(0, height - newHeight) / 2;
  6423. var renderingCanvas = engine.getRenderingCanvas();
  6424. if (renderContext && renderingCanvas) {
  6425. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6426. }
  6427. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6428. };
  6429. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6430. if (mimeType === void 0) { mimeType = "image/png"; }
  6431. if (samples === void 0) { samples = 1; }
  6432. var width;
  6433. var height;
  6434. //If a precision value is specified
  6435. if (size.precision) {
  6436. width = Math.round(engine.getRenderWidth() * size.precision);
  6437. height = Math.round(width / engine.getAspectRatio(camera));
  6438. size = { width: width, height: height };
  6439. }
  6440. else if (size.width && size.height) {
  6441. width = size.width;
  6442. height = size.height;
  6443. }
  6444. else if (size.width && !size.height) {
  6445. width = size.width;
  6446. height = Math.round(width / engine.getAspectRatio(camera));
  6447. size = { width: width, height: height };
  6448. }
  6449. else if (size.height && !size.width) {
  6450. height = size.height;
  6451. width = Math.round(height * engine.getAspectRatio(camera));
  6452. size = { width: width, height: height };
  6453. }
  6454. else if (!isNaN(size)) {
  6455. height = size;
  6456. width = size;
  6457. }
  6458. else {
  6459. Tools.Error("Invalid 'size' parameter !");
  6460. return;
  6461. }
  6462. var scene = camera.getScene();
  6463. var previousCamera = null;
  6464. if (scene.activeCamera !== camera) {
  6465. previousCamera = scene.activeCamera;
  6466. scene.activeCamera = camera;
  6467. }
  6468. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6469. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6470. texture.renderList = null;
  6471. texture.samples = samples;
  6472. texture.onAfterRenderObservable.add(function () {
  6473. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6474. });
  6475. scene.incrementRenderId();
  6476. scene.resetCachedMaterial();
  6477. texture.render(true);
  6478. texture.dispose();
  6479. if (previousCamera) {
  6480. scene.activeCamera = previousCamera;
  6481. }
  6482. camera.getProjectionMatrix(true); // Force cache refresh;
  6483. };
  6484. // XHR response validator for local file scenario
  6485. Tools.ValidateXHRData = function (xhr, dataType) {
  6486. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6487. if (dataType === void 0) { dataType = 7; }
  6488. try {
  6489. if (dataType & 1) {
  6490. if (xhr.responseText && xhr.responseText.length > 0) {
  6491. return true;
  6492. }
  6493. else if (dataType === 1) {
  6494. return false;
  6495. }
  6496. }
  6497. if (dataType & 2) {
  6498. // Check header width and height since there is no "TGA" magic number
  6499. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6500. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6501. return true;
  6502. }
  6503. else if (dataType === 2) {
  6504. return false;
  6505. }
  6506. }
  6507. if (dataType & 4) {
  6508. // Check for the "DDS" magic number
  6509. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6510. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6511. return true;
  6512. }
  6513. else {
  6514. return false;
  6515. }
  6516. }
  6517. }
  6518. catch (e) {
  6519. // Global protection
  6520. }
  6521. return false;
  6522. };
  6523. /**
  6524. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6525. * Be aware Math.random() could cause collisions, but:
  6526. * "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"
  6527. */
  6528. Tools.RandomId = function () {
  6529. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6530. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6531. return v.toString(16);
  6532. });
  6533. };
  6534. Object.defineProperty(Tools, "NoneLogLevel", {
  6535. get: function () {
  6536. return Tools._NoneLogLevel;
  6537. },
  6538. enumerable: true,
  6539. configurable: true
  6540. });
  6541. Object.defineProperty(Tools, "MessageLogLevel", {
  6542. get: function () {
  6543. return Tools._MessageLogLevel;
  6544. },
  6545. enumerable: true,
  6546. configurable: true
  6547. });
  6548. Object.defineProperty(Tools, "WarningLogLevel", {
  6549. get: function () {
  6550. return Tools._WarningLogLevel;
  6551. },
  6552. enumerable: true,
  6553. configurable: true
  6554. });
  6555. Object.defineProperty(Tools, "ErrorLogLevel", {
  6556. get: function () {
  6557. return Tools._ErrorLogLevel;
  6558. },
  6559. enumerable: true,
  6560. configurable: true
  6561. });
  6562. Object.defineProperty(Tools, "AllLogLevel", {
  6563. get: function () {
  6564. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6565. },
  6566. enumerable: true,
  6567. configurable: true
  6568. });
  6569. Tools._AddLogEntry = function (entry) {
  6570. Tools._LogCache = entry + Tools._LogCache;
  6571. if (Tools.OnNewCacheEntry) {
  6572. Tools.OnNewCacheEntry(entry);
  6573. }
  6574. };
  6575. Tools._FormatMessage = function (message) {
  6576. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6577. var date = new Date();
  6578. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6579. };
  6580. Tools._LogDisabled = function (message) {
  6581. // nothing to do
  6582. };
  6583. Tools._LogEnabled = function (message) {
  6584. var formattedMessage = Tools._FormatMessage(message);
  6585. console.log("BJS - " + formattedMessage);
  6586. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6587. Tools._AddLogEntry(entry);
  6588. };
  6589. Tools._WarnDisabled = function (message) {
  6590. // nothing to do
  6591. };
  6592. Tools._WarnEnabled = function (message) {
  6593. var formattedMessage = Tools._FormatMessage(message);
  6594. console.warn("BJS - " + formattedMessage);
  6595. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6596. Tools._AddLogEntry(entry);
  6597. };
  6598. Tools._ErrorDisabled = function (message) {
  6599. // nothing to do
  6600. };
  6601. Tools._ErrorEnabled = function (message) {
  6602. Tools.errorsCount++;
  6603. var formattedMessage = Tools._FormatMessage(message);
  6604. console.error("BJS - " + formattedMessage);
  6605. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6606. Tools._AddLogEntry(entry);
  6607. };
  6608. Object.defineProperty(Tools, "LogCache", {
  6609. get: function () {
  6610. return Tools._LogCache;
  6611. },
  6612. enumerable: true,
  6613. configurable: true
  6614. });
  6615. Tools.ClearLogCache = function () {
  6616. Tools._LogCache = "";
  6617. Tools.errorsCount = 0;
  6618. };
  6619. Object.defineProperty(Tools, "LogLevels", {
  6620. set: function (level) {
  6621. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6622. Tools.Log = Tools._LogEnabled;
  6623. }
  6624. else {
  6625. Tools.Log = Tools._LogDisabled;
  6626. }
  6627. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6628. Tools.Warn = Tools._WarnEnabled;
  6629. }
  6630. else {
  6631. Tools.Warn = Tools._WarnDisabled;
  6632. }
  6633. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6634. Tools.Error = Tools._ErrorEnabled;
  6635. }
  6636. else {
  6637. Tools.Error = Tools._ErrorDisabled;
  6638. }
  6639. },
  6640. enumerable: true,
  6641. configurable: true
  6642. });
  6643. Tools.IsWindowObjectExist = function () {
  6644. return (typeof window) !== "undefined";
  6645. };
  6646. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6647. get: function () {
  6648. return Tools._PerformanceNoneLogLevel;
  6649. },
  6650. enumerable: true,
  6651. configurable: true
  6652. });
  6653. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6654. get: function () {
  6655. return Tools._PerformanceUserMarkLogLevel;
  6656. },
  6657. enumerable: true,
  6658. configurable: true
  6659. });
  6660. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6661. get: function () {
  6662. return Tools._PerformanceConsoleLogLevel;
  6663. },
  6664. enumerable: true,
  6665. configurable: true
  6666. });
  6667. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6668. set: function (level) {
  6669. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6670. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6671. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6672. return;
  6673. }
  6674. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6675. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6676. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6677. return;
  6678. }
  6679. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6680. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6681. },
  6682. enumerable: true,
  6683. configurable: true
  6684. });
  6685. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6686. };
  6687. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6688. };
  6689. Tools._StartUserMark = function (counterName, condition) {
  6690. if (condition === void 0) { condition = true; }
  6691. if (!Tools._performance) {
  6692. if (!Tools.IsWindowObjectExist()) {
  6693. return;
  6694. }
  6695. Tools._performance = window.performance;
  6696. }
  6697. if (!condition || !Tools._performance.mark) {
  6698. return;
  6699. }
  6700. Tools._performance.mark(counterName + "-Begin");
  6701. };
  6702. Tools._EndUserMark = function (counterName, condition) {
  6703. if (condition === void 0) { condition = true; }
  6704. if (!condition || !Tools._performance.mark) {
  6705. return;
  6706. }
  6707. Tools._performance.mark(counterName + "-End");
  6708. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6709. };
  6710. Tools._StartPerformanceConsole = function (counterName, condition) {
  6711. if (condition === void 0) { condition = true; }
  6712. if (!condition) {
  6713. return;
  6714. }
  6715. Tools._StartUserMark(counterName, condition);
  6716. if (console.time) {
  6717. console.time(counterName);
  6718. }
  6719. };
  6720. Tools._EndPerformanceConsole = function (counterName, condition) {
  6721. if (condition === void 0) { condition = true; }
  6722. if (!condition) {
  6723. return;
  6724. }
  6725. Tools._EndUserMark(counterName, condition);
  6726. if (console.time) {
  6727. console.timeEnd(counterName);
  6728. }
  6729. };
  6730. Object.defineProperty(Tools, "Now", {
  6731. get: function () {
  6732. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6733. return window.performance.now();
  6734. }
  6735. return new Date().getTime();
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. /**
  6741. * This method will return the name of the class used to create the instance of the given object.
  6742. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6743. * @param object the object to get the class name from
  6744. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6745. */
  6746. Tools.GetClassName = function (object, isType) {
  6747. if (isType === void 0) { isType = false; }
  6748. var name = null;
  6749. if (!isType && object.getClassName) {
  6750. name = object.getClassName();
  6751. }
  6752. else {
  6753. if (object instanceof Object) {
  6754. var classObj = isType ? object : Object.getPrototypeOf(object);
  6755. name = classObj.constructor["__bjsclassName__"];
  6756. }
  6757. if (!name) {
  6758. name = typeof object;
  6759. }
  6760. }
  6761. return name;
  6762. };
  6763. Tools.First = function (array, predicate) {
  6764. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6765. var el = array_1[_i];
  6766. if (predicate(el)) {
  6767. return el;
  6768. }
  6769. }
  6770. return null;
  6771. };
  6772. /**
  6773. * This method will return the name of the full name of the class, including its owning module (if any).
  6774. * 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).
  6775. * @param object the object to get the class name from
  6776. * @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.
  6777. */
  6778. Tools.getFullClassName = function (object, isType) {
  6779. if (isType === void 0) { isType = false; }
  6780. var className = null;
  6781. var moduleName = null;
  6782. if (!isType && object.getClassName) {
  6783. className = object.getClassName();
  6784. }
  6785. else {
  6786. if (object instanceof Object) {
  6787. var classObj = isType ? object : Object.getPrototypeOf(object);
  6788. className = classObj.constructor["__bjsclassName__"];
  6789. moduleName = classObj.constructor["__bjsmoduleName__"];
  6790. }
  6791. if (!className) {
  6792. className = typeof object;
  6793. }
  6794. }
  6795. if (!className) {
  6796. return null;
  6797. }
  6798. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6799. };
  6800. /**
  6801. * 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.
  6802. * @param array
  6803. */
  6804. Tools.arrayOrStringFeeder = function (array) {
  6805. return function (index) {
  6806. if (index >= array.length) {
  6807. return null;
  6808. }
  6809. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6810. if (val && val.getHashCode) {
  6811. val = val.getHashCode();
  6812. }
  6813. if (typeof val === "string") {
  6814. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6815. }
  6816. return val;
  6817. };
  6818. };
  6819. /**
  6820. * Compute the hashCode of a stream of number
  6821. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6822. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6823. * @return the hash code computed
  6824. */
  6825. Tools.hashCodeFromStream = function (feeder) {
  6826. // Based from here: http://stackoverflow.com/a/7616484/802124
  6827. var hash = 0;
  6828. var index = 0;
  6829. var chr = feeder(index++);
  6830. while (chr != null) {
  6831. hash = ((hash << 5) - hash) + chr;
  6832. hash |= 0; // Convert to 32bit integer
  6833. chr = feeder(index++);
  6834. }
  6835. return hash;
  6836. };
  6837. Tools.BaseUrl = "";
  6838. Tools.CorsBehavior = "anonymous";
  6839. Tools.UseFallbackTexture = true;
  6840. /**
  6841. * Use this object to register external classes like custom textures or material
  6842. * to allow the laoders to instantiate them
  6843. */
  6844. Tools.RegisteredExternalClasses = {};
  6845. // Used in case of a texture loading problem
  6846. 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";
  6847. Tools.PreprocessUrl = function (url) {
  6848. return url;
  6849. };
  6850. // Logs
  6851. Tools._NoneLogLevel = 0;
  6852. Tools._MessageLogLevel = 1;
  6853. Tools._WarningLogLevel = 2;
  6854. Tools._ErrorLogLevel = 4;
  6855. Tools._LogCache = "";
  6856. Tools.errorsCount = 0;
  6857. Tools.Log = Tools._LogEnabled;
  6858. Tools.Warn = Tools._WarnEnabled;
  6859. Tools.Error = Tools._ErrorEnabled;
  6860. // Performances
  6861. Tools._PerformanceNoneLogLevel = 0;
  6862. Tools._PerformanceUserMarkLogLevel = 1;
  6863. Tools._PerformanceConsoleLogLevel = 2;
  6864. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6865. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6866. return Tools;
  6867. }());
  6868. BABYLON.Tools = Tools;
  6869. /**
  6870. * This class is used to track a performance counter which is number based.
  6871. * The user has access to many properties which give statistics of different nature
  6872. *
  6873. * The implementer can track two kinds of Performance Counter: time and count
  6874. * 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.
  6875. * 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.
  6876. */
  6877. var PerfCounter = /** @class */ (function () {
  6878. function PerfCounter() {
  6879. this._startMonitoringTime = 0;
  6880. this._min = 0;
  6881. this._max = 0;
  6882. this._average = 0;
  6883. this._lastSecAverage = 0;
  6884. this._current = 0;
  6885. this._totalValueCount = 0;
  6886. this._totalAccumulated = 0;
  6887. this._lastSecAccumulated = 0;
  6888. this._lastSecTime = 0;
  6889. this._lastSecValueCount = 0;
  6890. }
  6891. Object.defineProperty(PerfCounter.prototype, "min", {
  6892. /**
  6893. * Returns the smallest value ever
  6894. */
  6895. get: function () {
  6896. return this._min;
  6897. },
  6898. enumerable: true,
  6899. configurable: true
  6900. });
  6901. Object.defineProperty(PerfCounter.prototype, "max", {
  6902. /**
  6903. * Returns the biggest value ever
  6904. */
  6905. get: function () {
  6906. return this._max;
  6907. },
  6908. enumerable: true,
  6909. configurable: true
  6910. });
  6911. Object.defineProperty(PerfCounter.prototype, "average", {
  6912. /**
  6913. * Returns the average value since the performance counter is running
  6914. */
  6915. get: function () {
  6916. return this._average;
  6917. },
  6918. enumerable: true,
  6919. configurable: true
  6920. });
  6921. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6922. /**
  6923. * Returns the average value of the last second the counter was monitored
  6924. */
  6925. get: function () {
  6926. return this._lastSecAverage;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(PerfCounter.prototype, "current", {
  6932. /**
  6933. * Returns the current value
  6934. */
  6935. get: function () {
  6936. return this._current;
  6937. },
  6938. enumerable: true,
  6939. configurable: true
  6940. });
  6941. Object.defineProperty(PerfCounter.prototype, "total", {
  6942. get: function () {
  6943. return this._totalAccumulated;
  6944. },
  6945. enumerable: true,
  6946. configurable: true
  6947. });
  6948. Object.defineProperty(PerfCounter.prototype, "count", {
  6949. get: function () {
  6950. return this._totalValueCount;
  6951. },
  6952. enumerable: true,
  6953. configurable: true
  6954. });
  6955. /**
  6956. * Call this method to start monitoring a new frame.
  6957. * 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.
  6958. */
  6959. PerfCounter.prototype.fetchNewFrame = function () {
  6960. this._totalValueCount++;
  6961. this._current = 0;
  6962. this._lastSecValueCount++;
  6963. };
  6964. /**
  6965. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6966. * @param newCount the count value to add to the monitored count
  6967. * @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.
  6968. */
  6969. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6970. if (!PerfCounter.Enabled) {
  6971. return;
  6972. }
  6973. this._current += newCount;
  6974. if (fetchResult) {
  6975. this._fetchResult();
  6976. }
  6977. };
  6978. /**
  6979. * Start monitoring this performance counter
  6980. */
  6981. PerfCounter.prototype.beginMonitoring = function () {
  6982. if (!PerfCounter.Enabled) {
  6983. return;
  6984. }
  6985. this._startMonitoringTime = Tools.Now;
  6986. };
  6987. /**
  6988. * Compute the time lapsed since the previous beginMonitoring() call.
  6989. * @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
  6990. */
  6991. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6992. if (newFrame === void 0) { newFrame = true; }
  6993. if (!PerfCounter.Enabled) {
  6994. return;
  6995. }
  6996. if (newFrame) {
  6997. this.fetchNewFrame();
  6998. }
  6999. var currentTime = Tools.Now;
  7000. this._current = currentTime - this._startMonitoringTime;
  7001. if (newFrame) {
  7002. this._fetchResult();
  7003. }
  7004. };
  7005. PerfCounter.prototype._fetchResult = function () {
  7006. this._totalAccumulated += this._current;
  7007. this._lastSecAccumulated += this._current;
  7008. // Min/Max update
  7009. this._min = Math.min(this._min, this._current);
  7010. this._max = Math.max(this._max, this._current);
  7011. this._average = this._totalAccumulated / this._totalValueCount;
  7012. // Reset last sec?
  7013. var now = Tools.Now;
  7014. if ((now - this._lastSecTime) > 1000) {
  7015. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7016. this._lastSecTime = now;
  7017. this._lastSecAccumulated = 0;
  7018. this._lastSecValueCount = 0;
  7019. }
  7020. };
  7021. PerfCounter.Enabled = true;
  7022. return PerfCounter;
  7023. }());
  7024. BABYLON.PerfCounter = PerfCounter;
  7025. /**
  7026. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7027. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7028. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7029. * @param name The name of the class, case should be preserved
  7030. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7031. */
  7032. function className(name, module) {
  7033. return function (target) {
  7034. target["__bjsclassName__"] = name;
  7035. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7036. };
  7037. }
  7038. BABYLON.className = className;
  7039. /**
  7040. * An implementation of a loop for asynchronous functions.
  7041. */
  7042. var AsyncLoop = /** @class */ (function () {
  7043. /**
  7044. * Constroctor.
  7045. * @param iterations the number of iterations.
  7046. * @param _fn the function to run each iteration
  7047. * @param _successCallback the callback that will be called upon succesful execution
  7048. * @param offset starting offset.
  7049. */
  7050. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7051. if (offset === void 0) { offset = 0; }
  7052. this.iterations = iterations;
  7053. this._fn = _fn;
  7054. this._successCallback = _successCallback;
  7055. this.index = offset - 1;
  7056. this._done = false;
  7057. }
  7058. /**
  7059. * Execute the next iteration. Must be called after the last iteration was finished.
  7060. */
  7061. AsyncLoop.prototype.executeNext = function () {
  7062. if (!this._done) {
  7063. if (this.index + 1 < this.iterations) {
  7064. ++this.index;
  7065. this._fn(this);
  7066. }
  7067. else {
  7068. this.breakLoop();
  7069. }
  7070. }
  7071. };
  7072. /**
  7073. * Break the loop and run the success callback.
  7074. */
  7075. AsyncLoop.prototype.breakLoop = function () {
  7076. this._done = true;
  7077. this._successCallback();
  7078. };
  7079. /**
  7080. * Helper function
  7081. */
  7082. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7083. if (offset === void 0) { offset = 0; }
  7084. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7085. loop.executeNext();
  7086. return loop;
  7087. };
  7088. /**
  7089. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7090. * @param iterations total number of iterations
  7091. * @param syncedIterations number of synchronous iterations in each async iteration.
  7092. * @param fn the function to call each iteration.
  7093. * @param callback a success call back that will be called when iterating stops.
  7094. * @param breakFunction a break condition (optional)
  7095. * @param timeout timeout settings for the setTimeout function. default - 0.
  7096. * @constructor
  7097. */
  7098. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7099. if (timeout === void 0) { timeout = 0; }
  7100. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7101. if (breakFunction && breakFunction())
  7102. loop.breakLoop();
  7103. else {
  7104. setTimeout(function () {
  7105. for (var i = 0; i < syncedIterations; ++i) {
  7106. var iteration = (loop.index * syncedIterations) + i;
  7107. if (iteration >= iterations)
  7108. break;
  7109. fn(iteration);
  7110. if (breakFunction && breakFunction()) {
  7111. loop.breakLoop();
  7112. break;
  7113. }
  7114. }
  7115. loop.executeNext();
  7116. }, timeout);
  7117. }
  7118. }, callback);
  7119. };
  7120. return AsyncLoop;
  7121. }());
  7122. BABYLON.AsyncLoop = AsyncLoop;
  7123. })(BABYLON || (BABYLON = {}));
  7124. //# sourceMappingURL=babylon.tools.js.map
  7125. var BABYLON;
  7126. (function (BABYLON) {
  7127. var Internals;
  7128. (function (Internals) {
  7129. var _AlphaState = /** @class */ (function () {
  7130. /**
  7131. * Initializes the state.
  7132. */
  7133. function _AlphaState() {
  7134. this._isAlphaBlendDirty = false;
  7135. this._isBlendFunctionParametersDirty = false;
  7136. this._isBlendEquationParametersDirty = false;
  7137. this._isBlendConstantsDirty = false;
  7138. this._alphaBlend = false;
  7139. this._blendFunctionParameters = new Array(4);
  7140. this._blendEquationParameters = new Array(2);
  7141. this._blendConstants = new Array(4);
  7142. this.reset();
  7143. }
  7144. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7145. get: function () {
  7146. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7147. },
  7148. enumerable: true,
  7149. configurable: true
  7150. });
  7151. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7152. get: function () {
  7153. return this._alphaBlend;
  7154. },
  7155. set: function (value) {
  7156. if (this._alphaBlend === value) {
  7157. return;
  7158. }
  7159. this._alphaBlend = value;
  7160. this._isAlphaBlendDirty = true;
  7161. },
  7162. enumerable: true,
  7163. configurable: true
  7164. });
  7165. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7166. if (this._blendConstants[0] === r &&
  7167. this._blendConstants[1] === g &&
  7168. this._blendConstants[2] === b &&
  7169. this._blendConstants[3] === a) {
  7170. return;
  7171. }
  7172. this._blendConstants[0] = r;
  7173. this._blendConstants[1] = g;
  7174. this._blendConstants[2] = b;
  7175. this._blendConstants[3] = a;
  7176. this._isBlendConstantsDirty = true;
  7177. };
  7178. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7179. if (this._blendFunctionParameters[0] === value0 &&
  7180. this._blendFunctionParameters[1] === value1 &&
  7181. this._blendFunctionParameters[2] === value2 &&
  7182. this._blendFunctionParameters[3] === value3) {
  7183. return;
  7184. }
  7185. this._blendFunctionParameters[0] = value0;
  7186. this._blendFunctionParameters[1] = value1;
  7187. this._blendFunctionParameters[2] = value2;
  7188. this._blendFunctionParameters[3] = value3;
  7189. this._isBlendFunctionParametersDirty = true;
  7190. };
  7191. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7192. if (this._blendEquationParameters[0] === rgb &&
  7193. this._blendEquationParameters[1] === alpha) {
  7194. return;
  7195. }
  7196. this._blendEquationParameters[0] = rgb;
  7197. this._blendEquationParameters[1] = alpha;
  7198. this._isBlendEquationParametersDirty = true;
  7199. };
  7200. _AlphaState.prototype.reset = function () {
  7201. this._alphaBlend = false;
  7202. this._blendFunctionParameters[0] = null;
  7203. this._blendFunctionParameters[1] = null;
  7204. this._blendFunctionParameters[2] = null;
  7205. this._blendFunctionParameters[3] = null;
  7206. this._blendEquationParameters[0] = null;
  7207. this._blendEquationParameters[1] = null;
  7208. this._blendConstants[0] = null;
  7209. this._blendConstants[1] = null;
  7210. this._blendConstants[2] = null;
  7211. this._blendConstants[3] = null;
  7212. this._isAlphaBlendDirty = true;
  7213. this._isBlendFunctionParametersDirty = false;
  7214. this._isBlendEquationParametersDirty = false;
  7215. this._isBlendConstantsDirty = false;
  7216. };
  7217. _AlphaState.prototype.apply = function (gl) {
  7218. if (!this.isDirty) {
  7219. return;
  7220. }
  7221. // Alpha blend
  7222. if (this._isAlphaBlendDirty) {
  7223. if (this._alphaBlend) {
  7224. gl.enable(gl.BLEND);
  7225. }
  7226. else {
  7227. gl.disable(gl.BLEND);
  7228. }
  7229. this._isAlphaBlendDirty = false;
  7230. }
  7231. // Alpha function
  7232. if (this._isBlendFunctionParametersDirty) {
  7233. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7234. this._isBlendFunctionParametersDirty = false;
  7235. }
  7236. // Alpha equation
  7237. if (this._isBlendEquationParametersDirty) {
  7238. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7239. this._isBlendEquationParametersDirty = false;
  7240. }
  7241. // Constants
  7242. if (this._isBlendConstantsDirty) {
  7243. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7244. this._isBlendConstantsDirty = false;
  7245. }
  7246. };
  7247. return _AlphaState;
  7248. }());
  7249. Internals._AlphaState = _AlphaState;
  7250. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7251. })(BABYLON || (BABYLON = {}));
  7252. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7253. var BABYLON;
  7254. (function (BABYLON) {
  7255. var Internals;
  7256. (function (Internals) {
  7257. var _DepthCullingState = /** @class */ (function () {
  7258. /**
  7259. * Initializes the state.
  7260. */
  7261. function _DepthCullingState() {
  7262. this._isDepthTestDirty = false;
  7263. this._isDepthMaskDirty = false;
  7264. this._isDepthFuncDirty = false;
  7265. this._isCullFaceDirty = false;
  7266. this._isCullDirty = false;
  7267. this._isZOffsetDirty = false;
  7268. this.reset();
  7269. }
  7270. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7271. get: function () {
  7272. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7273. },
  7274. enumerable: true,
  7275. configurable: true
  7276. });
  7277. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7278. get: function () {
  7279. return this._zOffset;
  7280. },
  7281. set: function (value) {
  7282. if (this._zOffset === value) {
  7283. return;
  7284. }
  7285. this._zOffset = value;
  7286. this._isZOffsetDirty = true;
  7287. },
  7288. enumerable: true,
  7289. configurable: true
  7290. });
  7291. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7292. get: function () {
  7293. return this._cullFace;
  7294. },
  7295. set: function (value) {
  7296. if (this._cullFace === value) {
  7297. return;
  7298. }
  7299. this._cullFace = value;
  7300. this._isCullFaceDirty = true;
  7301. },
  7302. enumerable: true,
  7303. configurable: true
  7304. });
  7305. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7306. get: function () {
  7307. return this._cull;
  7308. },
  7309. set: function (value) {
  7310. if (this._cull === value) {
  7311. return;
  7312. }
  7313. this._cull = value;
  7314. this._isCullDirty = true;
  7315. },
  7316. enumerable: true,
  7317. configurable: true
  7318. });
  7319. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7320. get: function () {
  7321. return this._depthFunc;
  7322. },
  7323. set: function (value) {
  7324. if (this._depthFunc === value) {
  7325. return;
  7326. }
  7327. this._depthFunc = value;
  7328. this._isDepthFuncDirty = true;
  7329. },
  7330. enumerable: true,
  7331. configurable: true
  7332. });
  7333. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7334. get: function () {
  7335. return this._depthMask;
  7336. },
  7337. set: function (value) {
  7338. if (this._depthMask === value) {
  7339. return;
  7340. }
  7341. this._depthMask = value;
  7342. this._isDepthMaskDirty = true;
  7343. },
  7344. enumerable: true,
  7345. configurable: true
  7346. });
  7347. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7348. get: function () {
  7349. return this._depthTest;
  7350. },
  7351. set: function (value) {
  7352. if (this._depthTest === value) {
  7353. return;
  7354. }
  7355. this._depthTest = value;
  7356. this._isDepthTestDirty = true;
  7357. },
  7358. enumerable: true,
  7359. configurable: true
  7360. });
  7361. _DepthCullingState.prototype.reset = function () {
  7362. this._depthMask = true;
  7363. this._depthTest = true;
  7364. this._depthFunc = null;
  7365. this._cullFace = null;
  7366. this._cull = null;
  7367. this._zOffset = 0;
  7368. this._isDepthTestDirty = true;
  7369. this._isDepthMaskDirty = true;
  7370. this._isDepthFuncDirty = false;
  7371. this._isCullFaceDirty = false;
  7372. this._isCullDirty = false;
  7373. this._isZOffsetDirty = false;
  7374. };
  7375. _DepthCullingState.prototype.apply = function (gl) {
  7376. if (!this.isDirty) {
  7377. return;
  7378. }
  7379. // Cull
  7380. if (this._isCullDirty) {
  7381. if (this.cull) {
  7382. gl.enable(gl.CULL_FACE);
  7383. }
  7384. else {
  7385. gl.disable(gl.CULL_FACE);
  7386. }
  7387. this._isCullDirty = false;
  7388. }
  7389. // Cull face
  7390. if (this._isCullFaceDirty) {
  7391. gl.cullFace(this.cullFace);
  7392. this._isCullFaceDirty = false;
  7393. }
  7394. // Depth mask
  7395. if (this._isDepthMaskDirty) {
  7396. gl.depthMask(this.depthMask);
  7397. this._isDepthMaskDirty = false;
  7398. }
  7399. // Depth test
  7400. if (this._isDepthTestDirty) {
  7401. if (this.depthTest) {
  7402. gl.enable(gl.DEPTH_TEST);
  7403. }
  7404. else {
  7405. gl.disable(gl.DEPTH_TEST);
  7406. }
  7407. this._isDepthTestDirty = false;
  7408. }
  7409. // Depth func
  7410. if (this._isDepthFuncDirty) {
  7411. gl.depthFunc(this.depthFunc);
  7412. this._isDepthFuncDirty = false;
  7413. }
  7414. // zOffset
  7415. if (this._isZOffsetDirty) {
  7416. if (this.zOffset) {
  7417. gl.enable(gl.POLYGON_OFFSET_FILL);
  7418. gl.polygonOffset(this.zOffset, 0);
  7419. }
  7420. else {
  7421. gl.disable(gl.POLYGON_OFFSET_FILL);
  7422. }
  7423. this._isZOffsetDirty = false;
  7424. }
  7425. };
  7426. return _DepthCullingState;
  7427. }());
  7428. Internals._DepthCullingState = _DepthCullingState;
  7429. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7430. })(BABYLON || (BABYLON = {}));
  7431. //# sourceMappingURL=babylon.depthCullingState.js.map
  7432. var BABYLON;
  7433. (function (BABYLON) {
  7434. var Internals;
  7435. (function (Internals) {
  7436. var _StencilState = /** @class */ (function () {
  7437. function _StencilState() {
  7438. this._isStencilTestDirty = false;
  7439. this._isStencilMaskDirty = false;
  7440. this._isStencilFuncDirty = false;
  7441. this._isStencilOpDirty = false;
  7442. this.reset();
  7443. }
  7444. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7445. get: function () {
  7446. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7447. },
  7448. enumerable: true,
  7449. configurable: true
  7450. });
  7451. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7452. get: function () {
  7453. return this._stencilFunc;
  7454. },
  7455. set: function (value) {
  7456. if (this._stencilFunc === value) {
  7457. return;
  7458. }
  7459. this._stencilFunc = value;
  7460. this._isStencilFuncDirty = true;
  7461. },
  7462. enumerable: true,
  7463. configurable: true
  7464. });
  7465. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7466. get: function () {
  7467. return this._stencilFuncRef;
  7468. },
  7469. set: function (value) {
  7470. if (this._stencilFuncRef === value) {
  7471. return;
  7472. }
  7473. this._stencilFuncRef = value;
  7474. this._isStencilFuncDirty = true;
  7475. },
  7476. enumerable: true,
  7477. configurable: true
  7478. });
  7479. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7480. get: function () {
  7481. return this._stencilFuncMask;
  7482. },
  7483. set: function (value) {
  7484. if (this._stencilFuncMask === value) {
  7485. return;
  7486. }
  7487. this._stencilFuncMask = value;
  7488. this._isStencilFuncDirty = true;
  7489. },
  7490. enumerable: true,
  7491. configurable: true
  7492. });
  7493. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7494. get: function () {
  7495. return this._stencilOpStencilFail;
  7496. },
  7497. set: function (value) {
  7498. if (this._stencilOpStencilFail === value) {
  7499. return;
  7500. }
  7501. this._stencilOpStencilFail = value;
  7502. this._isStencilOpDirty = true;
  7503. },
  7504. enumerable: true,
  7505. configurable: true
  7506. });
  7507. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7508. get: function () {
  7509. return this._stencilOpDepthFail;
  7510. },
  7511. set: function (value) {
  7512. if (this._stencilOpDepthFail === value) {
  7513. return;
  7514. }
  7515. this._stencilOpDepthFail = value;
  7516. this._isStencilOpDirty = true;
  7517. },
  7518. enumerable: true,
  7519. configurable: true
  7520. });
  7521. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7522. get: function () {
  7523. return this._stencilOpStencilDepthPass;
  7524. },
  7525. set: function (value) {
  7526. if (this._stencilOpStencilDepthPass === value) {
  7527. return;
  7528. }
  7529. this._stencilOpStencilDepthPass = value;
  7530. this._isStencilOpDirty = true;
  7531. },
  7532. enumerable: true,
  7533. configurable: true
  7534. });
  7535. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7536. get: function () {
  7537. return this._stencilMask;
  7538. },
  7539. set: function (value) {
  7540. if (this._stencilMask === value) {
  7541. return;
  7542. }
  7543. this._stencilMask = value;
  7544. this._isStencilMaskDirty = true;
  7545. },
  7546. enumerable: true,
  7547. configurable: true
  7548. });
  7549. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7550. get: function () {
  7551. return this._stencilTest;
  7552. },
  7553. set: function (value) {
  7554. if (this._stencilTest === value) {
  7555. return;
  7556. }
  7557. this._stencilTest = value;
  7558. this._isStencilTestDirty = true;
  7559. },
  7560. enumerable: true,
  7561. configurable: true
  7562. });
  7563. _StencilState.prototype.reset = function () {
  7564. this._stencilTest = false;
  7565. this._stencilMask = 0xFF;
  7566. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7567. this._stencilFuncRef = 1;
  7568. this._stencilFuncMask = 0xFF;
  7569. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7570. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7571. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7572. this._isStencilTestDirty = true;
  7573. this._isStencilMaskDirty = true;
  7574. this._isStencilFuncDirty = true;
  7575. this._isStencilOpDirty = true;
  7576. };
  7577. _StencilState.prototype.apply = function (gl) {
  7578. if (!this.isDirty) {
  7579. return;
  7580. }
  7581. // Stencil test
  7582. if (this._isStencilTestDirty) {
  7583. if (this.stencilTest) {
  7584. gl.enable(gl.STENCIL_TEST);
  7585. }
  7586. else {
  7587. gl.disable(gl.STENCIL_TEST);
  7588. }
  7589. this._isStencilTestDirty = false;
  7590. }
  7591. // Stencil mask
  7592. if (this._isStencilMaskDirty) {
  7593. gl.stencilMask(this.stencilMask);
  7594. this._isStencilMaskDirty = false;
  7595. }
  7596. // Stencil func
  7597. if (this._isStencilFuncDirty) {
  7598. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7599. this._isStencilFuncDirty = false;
  7600. }
  7601. // Stencil op
  7602. if (this._isStencilOpDirty) {
  7603. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7604. this._isStencilOpDirty = false;
  7605. }
  7606. };
  7607. return _StencilState;
  7608. }());
  7609. Internals._StencilState = _StencilState;
  7610. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7611. })(BABYLON || (BABYLON = {}));
  7612. //# sourceMappingURL=babylon.stencilState.js.map
  7613. var BABYLON;
  7614. (function (BABYLON) {
  7615. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7616. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7617. };
  7618. var compileRawShader = function (gl, source, type) {
  7619. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7620. gl.shaderSource(shader, source);
  7621. gl.compileShader(shader);
  7622. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7623. var log = gl.getShaderInfoLog(shader);
  7624. if (log) {
  7625. throw new Error(log);
  7626. }
  7627. }
  7628. if (!shader) {
  7629. throw new Error("Something went wrong while compile the shader.");
  7630. }
  7631. return shader;
  7632. };
  7633. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7634. var magFilter = gl.NEAREST;
  7635. var minFilter = gl.NEAREST;
  7636. switch (samplingMode) {
  7637. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7638. magFilter = gl.LINEAR;
  7639. if (generateMipMaps) {
  7640. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7641. }
  7642. else {
  7643. minFilter = gl.LINEAR;
  7644. }
  7645. break;
  7646. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7647. magFilter = gl.LINEAR;
  7648. if (generateMipMaps) {
  7649. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7650. }
  7651. else {
  7652. minFilter = gl.LINEAR;
  7653. }
  7654. break;
  7655. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7656. magFilter = gl.NEAREST;
  7657. if (generateMipMaps) {
  7658. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7659. }
  7660. else {
  7661. minFilter = gl.NEAREST;
  7662. }
  7663. break;
  7664. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7665. magFilter = gl.NEAREST;
  7666. if (generateMipMaps) {
  7667. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7668. }
  7669. else {
  7670. minFilter = gl.NEAREST;
  7671. }
  7672. break;
  7673. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7674. magFilter = gl.NEAREST;
  7675. if (generateMipMaps) {
  7676. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7677. }
  7678. else {
  7679. minFilter = gl.LINEAR;
  7680. }
  7681. break;
  7682. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7683. magFilter = gl.NEAREST;
  7684. if (generateMipMaps) {
  7685. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7686. }
  7687. else {
  7688. minFilter = gl.LINEAR;
  7689. }
  7690. break;
  7691. case BABYLON.Texture.NEAREST_LINEAR:
  7692. magFilter = gl.NEAREST;
  7693. minFilter = gl.LINEAR;
  7694. break;
  7695. case BABYLON.Texture.NEAREST_NEAREST:
  7696. magFilter = gl.NEAREST;
  7697. minFilter = gl.NEAREST;
  7698. break;
  7699. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7700. magFilter = gl.LINEAR;
  7701. if (generateMipMaps) {
  7702. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7703. }
  7704. else {
  7705. minFilter = gl.NEAREST;
  7706. }
  7707. break;
  7708. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7709. magFilter = gl.LINEAR;
  7710. if (generateMipMaps) {
  7711. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7712. }
  7713. else {
  7714. minFilter = gl.NEAREST;
  7715. }
  7716. break;
  7717. case BABYLON.Texture.LINEAR_LINEAR:
  7718. magFilter = gl.LINEAR;
  7719. minFilter = gl.LINEAR;
  7720. break;
  7721. case BABYLON.Texture.LINEAR_NEAREST:
  7722. magFilter = gl.LINEAR;
  7723. minFilter = gl.NEAREST;
  7724. break;
  7725. }
  7726. return {
  7727. min: minFilter,
  7728. mag: magFilter
  7729. };
  7730. };
  7731. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7732. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7733. var img;
  7734. var onload = function () {
  7735. loadedImages[index] = img;
  7736. loadedImages._internalCount++;
  7737. if (scene) {
  7738. scene._removePendingData(img);
  7739. }
  7740. if (loadedImages._internalCount === 6) {
  7741. onfinish(loadedImages);
  7742. }
  7743. };
  7744. var onerror = function (message, exception) {
  7745. if (scene) {
  7746. scene._removePendingData(img);
  7747. }
  7748. if (onErrorCallBack) {
  7749. onErrorCallBack(message, exception);
  7750. }
  7751. };
  7752. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7753. if (scene) {
  7754. scene._addPendingData(img);
  7755. }
  7756. };
  7757. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7758. if (onError === void 0) { onError = null; }
  7759. var loadedImages = [];
  7760. loadedImages._internalCount = 0;
  7761. for (var index = 0; index < 6; index++) {
  7762. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7763. }
  7764. };
  7765. var BufferPointer = /** @class */ (function () {
  7766. function BufferPointer() {
  7767. }
  7768. return BufferPointer;
  7769. }());
  7770. var InstancingAttributeInfo = /** @class */ (function () {
  7771. function InstancingAttributeInfo() {
  7772. }
  7773. return InstancingAttributeInfo;
  7774. }());
  7775. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7776. /**
  7777. * Define options used to create a render target texture
  7778. */
  7779. var RenderTargetCreationOptions = /** @class */ (function () {
  7780. function RenderTargetCreationOptions() {
  7781. }
  7782. return RenderTargetCreationOptions;
  7783. }());
  7784. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7785. /**
  7786. * Regroup several parameters relative to the browser in use
  7787. */
  7788. var EngineCapabilities = /** @class */ (function () {
  7789. function EngineCapabilities() {
  7790. }
  7791. return EngineCapabilities;
  7792. }());
  7793. BABYLON.EngineCapabilities = EngineCapabilities;
  7794. /**
  7795. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7796. */
  7797. var Engine = /** @class */ (function () {
  7798. /**
  7799. * @constructor
  7800. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7801. * @param {boolean} [antialias] - enable antialias
  7802. * @param options - further options to be sent to the getContext function
  7803. */
  7804. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7805. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7806. var _this = this;
  7807. // Public members
  7808. this.forcePOTTextures = false;
  7809. this.isFullscreen = false;
  7810. this.isPointerLock = false;
  7811. this.cullBackFaces = true;
  7812. this.renderEvenInBackground = true;
  7813. this.preventCacheWipeBetweenFrames = false;
  7814. // To enable/disable IDB support and avoid XHR on .manifest
  7815. this.enableOfflineSupport = false;
  7816. this.scenes = new Array();
  7817. this.postProcesses = new Array();
  7818. // Observables
  7819. /**
  7820. * Observable event triggered each time the rendering canvas is resized
  7821. */
  7822. this.onResizeObservable = new BABYLON.Observable();
  7823. /**
  7824. * Observable event triggered each time the canvas loses focus
  7825. */
  7826. this.onCanvasBlurObservable = new BABYLON.Observable();
  7827. /**
  7828. * Observable event triggered each time the canvas gains focus
  7829. */
  7830. this.onCanvasFocusObservable = new BABYLON.Observable();
  7831. /**
  7832. * Observable event triggered each time the canvas receives pointerout event
  7833. */
  7834. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7835. /**
  7836. * Observable event triggered before each texture is initialized
  7837. */
  7838. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7839. //WebVR
  7840. this._vrDisplay = undefined;
  7841. this._vrSupported = false;
  7842. this._vrExclusivePointerMode = false;
  7843. // Uniform buffers list
  7844. this.disableUniformBuffers = false;
  7845. this._uniformBuffers = new Array();
  7846. // Observables
  7847. /**
  7848. * Observable raised when the engine begins a new frame
  7849. */
  7850. this.onBeginFrameObservable = new BABYLON.Observable();
  7851. /**
  7852. * Observable raised when the engine ends the current frame
  7853. */
  7854. this.onEndFrameObservable = new BABYLON.Observable();
  7855. /**
  7856. * Observable raised when the engine is about to compile a shader
  7857. */
  7858. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7859. /**
  7860. * Observable raised when the engine has jsut compiled a shader
  7861. */
  7862. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7863. this._windowIsBackground = false;
  7864. this._webGLVersion = 1.0;
  7865. this._badOS = false;
  7866. this._badDesktopOS = false;
  7867. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7868. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7869. this.onVRRequestPresentStart = new BABYLON.Observable();
  7870. this._colorWrite = true;
  7871. this._drawCalls = new BABYLON.PerfCounter();
  7872. this._renderingQueueLaunched = false;
  7873. this._activeRenderLoops = new Array();
  7874. // Deterministic lockstepMaxSteps
  7875. this._deterministicLockstep = false;
  7876. this._lockstepMaxSteps = 4;
  7877. // Lost context
  7878. this.onContextLostObservable = new BABYLON.Observable();
  7879. this.onContextRestoredObservable = new BABYLON.Observable();
  7880. this._contextWasLost = false;
  7881. this._doNotHandleContextLost = false;
  7882. // FPS
  7883. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7884. this._fps = 60;
  7885. this._deltaTime = 0;
  7886. /**
  7887. * Turn this value on if you want to pause FPS computation when in background
  7888. */
  7889. this.disablePerformanceMonitorInBackground = false;
  7890. // States
  7891. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7892. this._stencilState = new BABYLON.Internals._StencilState();
  7893. this._alphaState = new BABYLON.Internals._AlphaState();
  7894. this._alphaMode = Engine.ALPHA_DISABLE;
  7895. // Cache
  7896. this._internalTexturesCache = new Array();
  7897. this._activeTexturesCache = {};
  7898. this._compiledEffects = {};
  7899. this._vertexAttribArraysEnabled = [];
  7900. this._uintIndicesCurrentlySet = false;
  7901. this._currentBoundBuffer = new Array();
  7902. this._currentBufferPointers = new Array();
  7903. this._currentInstanceLocations = new Array();
  7904. this._currentInstanceBuffers = new Array();
  7905. this._vaoRecordInProgress = false;
  7906. this._mustWipeVertexAttributes = false;
  7907. // Hardware supported Compressed Textures
  7908. this._texturesSupported = new Array();
  7909. this._onVRFullScreenTriggered = function () {
  7910. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7911. //get the old size before we change
  7912. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7913. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7914. //get the width and height, change the render size
  7915. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7916. _this.setHardwareScalingLevel(1);
  7917. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7918. }
  7919. else {
  7920. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7921. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7922. }
  7923. };
  7924. var canvas = null;
  7925. Engine.Instances.push(this);
  7926. if (!canvasOrContext) {
  7927. return;
  7928. }
  7929. options = options || {};
  7930. if (canvasOrContext.getContext) {
  7931. canvas = canvasOrContext;
  7932. this._renderingCanvas = canvas;
  7933. if (antialias != null) {
  7934. options.antialias = antialias;
  7935. }
  7936. if (options.deterministicLockstep === undefined) {
  7937. options.deterministicLockstep = false;
  7938. }
  7939. if (options.lockstepMaxSteps === undefined) {
  7940. options.lockstepMaxSteps = 4;
  7941. }
  7942. if (options.preserveDrawingBuffer === undefined) {
  7943. options.preserveDrawingBuffer = false;
  7944. }
  7945. if (options.audioEngine === undefined) {
  7946. options.audioEngine = true;
  7947. }
  7948. if (options.stencil === undefined) {
  7949. options.stencil = true;
  7950. }
  7951. this._deterministicLockstep = options.deterministicLockstep;
  7952. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7953. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  7954. // GL
  7955. if (!options.disableWebGL2Support) {
  7956. try {
  7957. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7958. if (this._gl) {
  7959. this._webGLVersion = 2.0;
  7960. }
  7961. }
  7962. catch (e) {
  7963. // Do nothing
  7964. }
  7965. }
  7966. if (!this._gl) {
  7967. if (!canvas) {
  7968. throw new Error("The provided canvas is null or undefined.");
  7969. }
  7970. try {
  7971. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7972. }
  7973. catch (e) {
  7974. throw new Error("WebGL not supported");
  7975. }
  7976. }
  7977. if (!this._gl) {
  7978. throw new Error("WebGL not supported");
  7979. }
  7980. this._onCanvasFocus = function () {
  7981. _this.onCanvasFocusObservable.notifyObservers(_this);
  7982. };
  7983. this._onCanvasBlur = function () {
  7984. _this.onCanvasBlurObservable.notifyObservers(_this);
  7985. };
  7986. canvas.addEventListener("focus", this._onCanvasFocus);
  7987. canvas.addEventListener("blur", this._onCanvasBlur);
  7988. this._onBlur = function () {
  7989. if (_this.disablePerformanceMonitorInBackground) {
  7990. _this._performanceMonitor.disable();
  7991. }
  7992. _this._windowIsBackground = true;
  7993. };
  7994. this._onFocus = function () {
  7995. if (_this.disablePerformanceMonitorInBackground) {
  7996. _this._performanceMonitor.enable();
  7997. }
  7998. _this._windowIsBackground = false;
  7999. };
  8000. this._onCanvasPointerOut = function () {
  8001. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8002. };
  8003. window.addEventListener("blur", this._onBlur);
  8004. window.addEventListener("focus", this._onFocus);
  8005. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8006. // Context lost
  8007. if (!this._doNotHandleContextLost) {
  8008. this._onContextLost = function (evt) {
  8009. evt.preventDefault();
  8010. _this._contextWasLost = true;
  8011. BABYLON.Tools.Warn("WebGL context lost.");
  8012. _this.onContextLostObservable.notifyObservers(_this);
  8013. };
  8014. this._onContextRestored = function (evt) {
  8015. // Adding a timeout to avoid race condition at browser level
  8016. setTimeout(function () {
  8017. // Rebuild gl context
  8018. _this._initGLContext();
  8019. // Rebuild effects
  8020. _this._rebuildEffects();
  8021. // Rebuild textures
  8022. _this._rebuildInternalTextures();
  8023. // Rebuild buffers
  8024. _this._rebuildBuffers();
  8025. // Cache
  8026. _this.wipeCaches(true);
  8027. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8028. _this.onContextRestoredObservable.notifyObservers(_this);
  8029. _this._contextWasLost = false;
  8030. }, 0);
  8031. };
  8032. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8033. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8034. }
  8035. }
  8036. else {
  8037. this._gl = canvasOrContext;
  8038. this._renderingCanvas = this._gl.canvas;
  8039. if (this._gl.renderbufferStorageMultisample) {
  8040. this._webGLVersion = 2.0;
  8041. }
  8042. options.stencil = this._gl.getContextAttributes().stencil;
  8043. }
  8044. // Viewport
  8045. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8046. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8047. this.resize();
  8048. this._isStencilEnable = options.stencil ? true : false;
  8049. this._initGLContext();
  8050. if (canvas) {
  8051. // Fullscreen
  8052. this._onFullscreenChange = function () {
  8053. if (document.fullscreen !== undefined) {
  8054. _this.isFullscreen = document.fullscreen;
  8055. }
  8056. else if (document.mozFullScreen !== undefined) {
  8057. _this.isFullscreen = document.mozFullScreen;
  8058. }
  8059. else if (document.webkitIsFullScreen !== undefined) {
  8060. _this.isFullscreen = document.webkitIsFullScreen;
  8061. }
  8062. else if (document.msIsFullScreen !== undefined) {
  8063. _this.isFullscreen = document.msIsFullScreen;
  8064. }
  8065. // Pointer lock
  8066. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8067. canvas.requestPointerLock = canvas.requestPointerLock ||
  8068. canvas.msRequestPointerLock ||
  8069. canvas.mozRequestPointerLock ||
  8070. canvas.webkitRequestPointerLock;
  8071. if (canvas.requestPointerLock) {
  8072. canvas.requestPointerLock();
  8073. }
  8074. }
  8075. };
  8076. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8077. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8078. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8079. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8080. // Pointer lock
  8081. this._onPointerLockChange = function () {
  8082. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8083. document.webkitPointerLockElement === canvas ||
  8084. document.msPointerLockElement === canvas ||
  8085. document.pointerLockElement === canvas);
  8086. };
  8087. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8088. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8089. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8090. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8091. this._onVRDisplayPointerRestricted = function () {
  8092. if (canvas) {
  8093. canvas.requestPointerLock();
  8094. }
  8095. };
  8096. this._onVRDisplayPointerUnrestricted = function () {
  8097. document.exitPointerLock();
  8098. };
  8099. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8100. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8101. }
  8102. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8103. Engine.audioEngine = new BABYLON.AudioEngine();
  8104. }
  8105. // Prepare buffer pointers
  8106. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8107. this._currentBufferPointers[i] = new BufferPointer();
  8108. }
  8109. // Load WebVR Devices
  8110. if (options.autoEnableWebVR) {
  8111. this.initWebVR();
  8112. }
  8113. // Detect if we are running on a faulty buggy OS.
  8114. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8115. // Detect if we are running on a faulty buggy desktop OS.
  8116. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8117. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8118. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8119. }
  8120. Object.defineProperty(Engine, "LastCreatedEngine", {
  8121. get: function () {
  8122. if (Engine.Instances.length === 0) {
  8123. return null;
  8124. }
  8125. return Engine.Instances[Engine.Instances.length - 1];
  8126. },
  8127. enumerable: true,
  8128. configurable: true
  8129. });
  8130. Object.defineProperty(Engine, "LastCreatedScene", {
  8131. get: function () {
  8132. var lastCreatedEngine = Engine.LastCreatedEngine;
  8133. if (!lastCreatedEngine) {
  8134. return null;
  8135. }
  8136. if (lastCreatedEngine.scenes.length === 0) {
  8137. return null;
  8138. }
  8139. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8140. },
  8141. enumerable: true,
  8142. configurable: true
  8143. });
  8144. /**
  8145. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8146. */
  8147. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8148. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8149. var engine = Engine.Instances[engineIndex];
  8150. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8151. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8152. }
  8153. }
  8154. };
  8155. Object.defineProperty(Engine, "NEVER", {
  8156. get: function () {
  8157. return Engine._NEVER;
  8158. },
  8159. enumerable: true,
  8160. configurable: true
  8161. });
  8162. Object.defineProperty(Engine, "ALWAYS", {
  8163. get: function () {
  8164. return Engine._ALWAYS;
  8165. },
  8166. enumerable: true,
  8167. configurable: true
  8168. });
  8169. Object.defineProperty(Engine, "LESS", {
  8170. get: function () {
  8171. return Engine._LESS;
  8172. },
  8173. enumerable: true,
  8174. configurable: true
  8175. });
  8176. Object.defineProperty(Engine, "EQUAL", {
  8177. get: function () {
  8178. return Engine._EQUAL;
  8179. },
  8180. enumerable: true,
  8181. configurable: true
  8182. });
  8183. Object.defineProperty(Engine, "LEQUAL", {
  8184. get: function () {
  8185. return Engine._LEQUAL;
  8186. },
  8187. enumerable: true,
  8188. configurable: true
  8189. });
  8190. Object.defineProperty(Engine, "GREATER", {
  8191. get: function () {
  8192. return Engine._GREATER;
  8193. },
  8194. enumerable: true,
  8195. configurable: true
  8196. });
  8197. Object.defineProperty(Engine, "GEQUAL", {
  8198. get: function () {
  8199. return Engine._GEQUAL;
  8200. },
  8201. enumerable: true,
  8202. configurable: true
  8203. });
  8204. Object.defineProperty(Engine, "NOTEQUAL", {
  8205. get: function () {
  8206. return Engine._NOTEQUAL;
  8207. },
  8208. enumerable: true,
  8209. configurable: true
  8210. });
  8211. Object.defineProperty(Engine, "KEEP", {
  8212. get: function () {
  8213. return Engine._KEEP;
  8214. },
  8215. enumerable: true,
  8216. configurable: true
  8217. });
  8218. Object.defineProperty(Engine, "REPLACE", {
  8219. get: function () {
  8220. return Engine._REPLACE;
  8221. },
  8222. enumerable: true,
  8223. configurable: true
  8224. });
  8225. Object.defineProperty(Engine, "INCR", {
  8226. get: function () {
  8227. return Engine._INCR;
  8228. },
  8229. enumerable: true,
  8230. configurable: true
  8231. });
  8232. Object.defineProperty(Engine, "DECR", {
  8233. get: function () {
  8234. return Engine._DECR;
  8235. },
  8236. enumerable: true,
  8237. configurable: true
  8238. });
  8239. Object.defineProperty(Engine, "INVERT", {
  8240. get: function () {
  8241. return Engine._INVERT;
  8242. },
  8243. enumerable: true,
  8244. configurable: true
  8245. });
  8246. Object.defineProperty(Engine, "INCR_WRAP", {
  8247. get: function () {
  8248. return Engine._INCR_WRAP;
  8249. },
  8250. enumerable: true,
  8251. configurable: true
  8252. });
  8253. Object.defineProperty(Engine, "DECR_WRAP", {
  8254. get: function () {
  8255. return Engine._DECR_WRAP;
  8256. },
  8257. enumerable: true,
  8258. configurable: true
  8259. });
  8260. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8261. get: function () {
  8262. return Engine._ALPHA_DISABLE;
  8263. },
  8264. enumerable: true,
  8265. configurable: true
  8266. });
  8267. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8268. get: function () {
  8269. return Engine._ALPHA_ONEONE;
  8270. },
  8271. enumerable: true,
  8272. configurable: true
  8273. });
  8274. Object.defineProperty(Engine, "ALPHA_ADD", {
  8275. get: function () {
  8276. return Engine._ALPHA_ADD;
  8277. },
  8278. enumerable: true,
  8279. configurable: true
  8280. });
  8281. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8282. get: function () {
  8283. return Engine._ALPHA_COMBINE;
  8284. },
  8285. enumerable: true,
  8286. configurable: true
  8287. });
  8288. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8289. get: function () {
  8290. return Engine._ALPHA_SUBTRACT;
  8291. },
  8292. enumerable: true,
  8293. configurable: true
  8294. });
  8295. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8296. get: function () {
  8297. return Engine._ALPHA_MULTIPLY;
  8298. },
  8299. enumerable: true,
  8300. configurable: true
  8301. });
  8302. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8303. get: function () {
  8304. return Engine._ALPHA_MAXIMIZED;
  8305. },
  8306. enumerable: true,
  8307. configurable: true
  8308. });
  8309. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8310. get: function () {
  8311. return Engine._ALPHA_PREMULTIPLIED;
  8312. },
  8313. enumerable: true,
  8314. configurable: true
  8315. });
  8316. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8317. get: function () {
  8318. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8319. },
  8320. enumerable: true,
  8321. configurable: true
  8322. });
  8323. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8324. get: function () {
  8325. return Engine._ALPHA_INTERPOLATE;
  8326. },
  8327. enumerable: true,
  8328. configurable: true
  8329. });
  8330. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8331. get: function () {
  8332. return Engine._ALPHA_SCREENMODE;
  8333. },
  8334. enumerable: true,
  8335. configurable: true
  8336. });
  8337. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8338. get: function () {
  8339. return Engine._DELAYLOADSTATE_NONE;
  8340. },
  8341. enumerable: true,
  8342. configurable: true
  8343. });
  8344. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8345. get: function () {
  8346. return Engine._DELAYLOADSTATE_LOADED;
  8347. },
  8348. enumerable: true,
  8349. configurable: true
  8350. });
  8351. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8352. get: function () {
  8353. return Engine._DELAYLOADSTATE_LOADING;
  8354. },
  8355. enumerable: true,
  8356. configurable: true
  8357. });
  8358. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8359. get: function () {
  8360. return Engine._DELAYLOADSTATE_NOTLOADED;
  8361. },
  8362. enumerable: true,
  8363. configurable: true
  8364. });
  8365. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8366. get: function () {
  8367. return Engine._TEXTUREFORMAT_ALPHA;
  8368. },
  8369. enumerable: true,
  8370. configurable: true
  8371. });
  8372. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8373. get: function () {
  8374. return Engine._TEXTUREFORMAT_LUMINANCE;
  8375. },
  8376. enumerable: true,
  8377. configurable: true
  8378. });
  8379. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8380. get: function () {
  8381. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8382. },
  8383. enumerable: true,
  8384. configurable: true
  8385. });
  8386. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8387. get: function () {
  8388. return Engine._TEXTUREFORMAT_RGB;
  8389. },
  8390. enumerable: true,
  8391. configurable: true
  8392. });
  8393. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8394. get: function () {
  8395. return Engine._TEXTUREFORMAT_RGBA;
  8396. },
  8397. enumerable: true,
  8398. configurable: true
  8399. });
  8400. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8401. get: function () {
  8402. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8403. },
  8404. enumerable: true,
  8405. configurable: true
  8406. });
  8407. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8408. get: function () {
  8409. return Engine._TEXTURETYPE_FLOAT;
  8410. },
  8411. enumerable: true,
  8412. configurable: true
  8413. });
  8414. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8415. get: function () {
  8416. return Engine._TEXTURETYPE_HALF_FLOAT;
  8417. },
  8418. enumerable: true,
  8419. configurable: true
  8420. });
  8421. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8422. get: function () {
  8423. return Engine._SCALEMODE_FLOOR;
  8424. },
  8425. enumerable: true,
  8426. configurable: true
  8427. });
  8428. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8429. get: function () {
  8430. return Engine._SCALEMODE_NEAREST;
  8431. },
  8432. enumerable: true,
  8433. configurable: true
  8434. });
  8435. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8436. get: function () {
  8437. return Engine._SCALEMODE_CEILING;
  8438. },
  8439. enumerable: true,
  8440. configurable: true
  8441. });
  8442. Object.defineProperty(Engine, "Version", {
  8443. get: function () {
  8444. return "3.1-beta";
  8445. },
  8446. enumerable: true,
  8447. configurable: true
  8448. });
  8449. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8450. get: function () {
  8451. return this._vrExclusivePointerMode;
  8452. },
  8453. enumerable: true,
  8454. configurable: true
  8455. });
  8456. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8457. get: function () {
  8458. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8459. },
  8460. enumerable: true,
  8461. configurable: true
  8462. });
  8463. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8464. get: function () {
  8465. return this._webGLVersion < 2 || this.forcePOTTextures;
  8466. },
  8467. enumerable: true,
  8468. configurable: true
  8469. });
  8470. Object.defineProperty(Engine.prototype, "badOS", {
  8471. get: function () {
  8472. return this._badOS;
  8473. },
  8474. enumerable: true,
  8475. configurable: true
  8476. });
  8477. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8478. get: function () {
  8479. return this._badDesktopOS;
  8480. },
  8481. enumerable: true,
  8482. configurable: true
  8483. });
  8484. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8485. get: function () {
  8486. return this._performanceMonitor;
  8487. },
  8488. enumerable: true,
  8489. configurable: true
  8490. });
  8491. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8492. get: function () {
  8493. return this._texturesSupported;
  8494. },
  8495. enumerable: true,
  8496. configurable: true
  8497. });
  8498. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8499. get: function () {
  8500. return this._textureFormatInUse;
  8501. },
  8502. enumerable: true,
  8503. configurable: true
  8504. });
  8505. Object.defineProperty(Engine.prototype, "currentViewport", {
  8506. get: function () {
  8507. return this._cachedViewport;
  8508. },
  8509. enumerable: true,
  8510. configurable: true
  8511. });
  8512. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8513. // Empty texture
  8514. get: function () {
  8515. if (!this._emptyTexture) {
  8516. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8517. }
  8518. return this._emptyTexture;
  8519. },
  8520. enumerable: true,
  8521. configurable: true
  8522. });
  8523. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8524. get: function () {
  8525. if (!this._emptyTexture3D) {
  8526. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8527. }
  8528. return this._emptyTexture3D;
  8529. },
  8530. enumerable: true,
  8531. configurable: true
  8532. });
  8533. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8534. get: function () {
  8535. if (!this._emptyCubeTexture) {
  8536. var faceData = new Uint8Array(4);
  8537. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8538. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8539. }
  8540. return this._emptyCubeTexture;
  8541. },
  8542. enumerable: true,
  8543. configurable: true
  8544. });
  8545. Engine.prototype._rebuildInternalTextures = function () {
  8546. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8547. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8548. var internalTexture = currentState_1[_i];
  8549. internalTexture._rebuild();
  8550. }
  8551. };
  8552. Engine.prototype._rebuildEffects = function () {
  8553. for (var key in this._compiledEffects) {
  8554. var effect = this._compiledEffects[key];
  8555. effect._prepareEffect();
  8556. }
  8557. BABYLON.Effect.ResetCache();
  8558. };
  8559. Engine.prototype._rebuildBuffers = function () {
  8560. // Index / Vertex
  8561. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8562. var scene = _a[_i];
  8563. scene.resetCachedMaterial();
  8564. scene._rebuildGeometries();
  8565. scene._rebuildTextures();
  8566. }
  8567. // Uniforms
  8568. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8569. var uniformBuffer = _c[_b];
  8570. uniformBuffer._rebuild();
  8571. }
  8572. };
  8573. Engine.prototype._initGLContext = function () {
  8574. // Caps
  8575. this._caps = new EngineCapabilities();
  8576. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8577. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8578. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8579. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8580. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8581. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8582. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8583. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8584. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8585. // Infos
  8586. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8587. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8588. if (rendererInfo != null) {
  8589. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8590. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8591. }
  8592. if (!this._glVendor) {
  8593. this._glVendor = "Unknown vendor";
  8594. }
  8595. if (!this._glRenderer) {
  8596. this._glRenderer = "Unknown renderer";
  8597. }
  8598. // Constants
  8599. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8600. if (this._gl.RGBA16F !== 0x881A) {
  8601. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8602. }
  8603. if (this._gl.RGBA32F !== 0x8814) {
  8604. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8605. }
  8606. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8607. this._gl.DEPTH24_STENCIL8 = 35056;
  8608. }
  8609. // Extensions
  8610. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8611. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8612. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8613. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8614. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8615. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8616. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8617. 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');
  8618. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8619. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8620. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8621. this._caps.highPrecisionShaderSupported = true;
  8622. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8623. if (this._caps.timerQuery) {
  8624. if (this._webGLVersion === 1) {
  8625. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8626. }
  8627. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8628. }
  8629. // Checks if some of the format renders first to allow the use of webgl inspector.
  8630. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8631. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8632. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8633. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8634. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8635. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8636. if (this._webGLVersion > 1) {
  8637. this._gl.HALF_FLOAT_OES = 0x140B;
  8638. }
  8639. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8640. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8641. // Draw buffers
  8642. if (this._webGLVersion > 1) {
  8643. this._caps.drawBuffersExtension = true;
  8644. }
  8645. else {
  8646. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8647. if (drawBuffersExtension !== null) {
  8648. this._caps.drawBuffersExtension = true;
  8649. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8650. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8651. for (var i = 0; i < 16; i++) {
  8652. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8653. }
  8654. }
  8655. else {
  8656. this._caps.drawBuffersExtension = false;
  8657. }
  8658. }
  8659. // Depth Texture
  8660. if (this._webGLVersion > 1) {
  8661. this._caps.depthTextureExtension = true;
  8662. }
  8663. else {
  8664. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8665. if (depthTextureExtension != null) {
  8666. this._caps.depthTextureExtension = true;
  8667. }
  8668. }
  8669. // Vertex array object
  8670. if (this._webGLVersion > 1) {
  8671. this._caps.vertexArrayObject = true;
  8672. }
  8673. else {
  8674. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8675. if (vertexArrayObjectExtension != null) {
  8676. this._caps.vertexArrayObject = true;
  8677. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8678. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8679. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8680. }
  8681. else {
  8682. this._caps.vertexArrayObject = false;
  8683. }
  8684. }
  8685. // Instances count
  8686. if (this._webGLVersion > 1) {
  8687. this._caps.instancedArrays = true;
  8688. }
  8689. else {
  8690. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8691. if (instanceExtension != null) {
  8692. this._caps.instancedArrays = true;
  8693. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8694. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8695. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8696. }
  8697. else {
  8698. this._caps.instancedArrays = false;
  8699. }
  8700. }
  8701. // Intelligently add supported compressed formats in order to check for.
  8702. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8703. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8704. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8705. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8706. if (this._caps.astc)
  8707. this.texturesSupported.push('-astc.ktx');
  8708. if (this._caps.s3tc)
  8709. this.texturesSupported.push('-dxt.ktx');
  8710. if (this._caps.pvrtc)
  8711. this.texturesSupported.push('-pvrtc.ktx');
  8712. if (this._caps.etc2)
  8713. this.texturesSupported.push('-etc2.ktx');
  8714. if (this._caps.etc1)
  8715. this.texturesSupported.push('-etc1.ktx');
  8716. if (this._gl.getShaderPrecisionFormat) {
  8717. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8718. if (highp) {
  8719. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8720. }
  8721. }
  8722. // Depth buffer
  8723. this.setDepthBuffer(true);
  8724. this.setDepthFunctionToLessOrEqual();
  8725. this.setDepthWrite(true);
  8726. };
  8727. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8728. get: function () {
  8729. return this._webGLVersion;
  8730. },
  8731. enumerable: true,
  8732. configurable: true
  8733. });
  8734. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8735. /**
  8736. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8737. */
  8738. get: function () {
  8739. return this._isStencilEnable;
  8740. },
  8741. enumerable: true,
  8742. configurable: true
  8743. });
  8744. Engine.prototype._prepareWorkingCanvas = function () {
  8745. if (this._workingCanvas) {
  8746. return;
  8747. }
  8748. this._workingCanvas = document.createElement("canvas");
  8749. var context = this._workingCanvas.getContext("2d");
  8750. if (context) {
  8751. this._workingContext = context;
  8752. }
  8753. };
  8754. Engine.prototype.resetTextureCache = function () {
  8755. for (var key in this._activeTexturesCache) {
  8756. this._activeTexturesCache[key] = null;
  8757. }
  8758. };
  8759. Engine.prototype.isDeterministicLockStep = function () {
  8760. return this._deterministicLockstep;
  8761. };
  8762. Engine.prototype.getLockstepMaxSteps = function () {
  8763. return this._lockstepMaxSteps;
  8764. };
  8765. Engine.prototype.getGlInfo = function () {
  8766. return {
  8767. vendor: this._glVendor,
  8768. renderer: this._glRenderer,
  8769. version: this._glVersion
  8770. };
  8771. };
  8772. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8773. if (useScreen === void 0) { useScreen = false; }
  8774. var viewport = camera.viewport;
  8775. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8776. };
  8777. Engine.prototype.getRenderWidth = function (useScreen) {
  8778. if (useScreen === void 0) { useScreen = false; }
  8779. if (!useScreen && this._currentRenderTarget) {
  8780. return this._currentRenderTarget.width;
  8781. }
  8782. return this._gl.drawingBufferWidth;
  8783. };
  8784. Engine.prototype.getRenderHeight = function (useScreen) {
  8785. if (useScreen === void 0) { useScreen = false; }
  8786. if (!useScreen && this._currentRenderTarget) {
  8787. return this._currentRenderTarget.height;
  8788. }
  8789. return this._gl.drawingBufferHeight;
  8790. };
  8791. Engine.prototype.getRenderingCanvas = function () {
  8792. return this._renderingCanvas;
  8793. };
  8794. Engine.prototype.getRenderingCanvasClientRect = function () {
  8795. if (!this._renderingCanvas) {
  8796. return null;
  8797. }
  8798. return this._renderingCanvas.getBoundingClientRect();
  8799. };
  8800. Engine.prototype.setHardwareScalingLevel = function (level) {
  8801. this._hardwareScalingLevel = level;
  8802. this.resize();
  8803. };
  8804. Engine.prototype.getHardwareScalingLevel = function () {
  8805. return this._hardwareScalingLevel;
  8806. };
  8807. Engine.prototype.getLoadedTexturesCache = function () {
  8808. return this._internalTexturesCache;
  8809. };
  8810. Engine.prototype.getCaps = function () {
  8811. return this._caps;
  8812. };
  8813. Object.defineProperty(Engine.prototype, "drawCalls", {
  8814. /** The number of draw calls submitted last frame */
  8815. get: function () {
  8816. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8817. return 0;
  8818. },
  8819. enumerable: true,
  8820. configurable: true
  8821. });
  8822. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8823. get: function () {
  8824. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8825. return null;
  8826. },
  8827. enumerable: true,
  8828. configurable: true
  8829. });
  8830. Engine.prototype.getDepthFunction = function () {
  8831. return this._depthCullingState.depthFunc;
  8832. };
  8833. Engine.prototype.setDepthFunction = function (depthFunc) {
  8834. this._depthCullingState.depthFunc = depthFunc;
  8835. };
  8836. Engine.prototype.setDepthFunctionToGreater = function () {
  8837. this._depthCullingState.depthFunc = this._gl.GREATER;
  8838. };
  8839. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8840. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8841. };
  8842. Engine.prototype.setDepthFunctionToLess = function () {
  8843. this._depthCullingState.depthFunc = this._gl.LESS;
  8844. };
  8845. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8846. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8847. };
  8848. Engine.prototype.getStencilBuffer = function () {
  8849. return this._stencilState.stencilTest;
  8850. };
  8851. Engine.prototype.setStencilBuffer = function (enable) {
  8852. this._stencilState.stencilTest = enable;
  8853. };
  8854. Engine.prototype.getStencilMask = function () {
  8855. return this._stencilState.stencilMask;
  8856. };
  8857. Engine.prototype.setStencilMask = function (mask) {
  8858. this._stencilState.stencilMask = mask;
  8859. };
  8860. Engine.prototype.getStencilFunction = function () {
  8861. return this._stencilState.stencilFunc;
  8862. };
  8863. Engine.prototype.getStencilFunctionReference = function () {
  8864. return this._stencilState.stencilFuncRef;
  8865. };
  8866. Engine.prototype.getStencilFunctionMask = function () {
  8867. return this._stencilState.stencilFuncMask;
  8868. };
  8869. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8870. this._stencilState.stencilFunc = stencilFunc;
  8871. };
  8872. Engine.prototype.setStencilFunctionReference = function (reference) {
  8873. this._stencilState.stencilFuncRef = reference;
  8874. };
  8875. Engine.prototype.setStencilFunctionMask = function (mask) {
  8876. this._stencilState.stencilFuncMask = mask;
  8877. };
  8878. Engine.prototype.getStencilOperationFail = function () {
  8879. return this._stencilState.stencilOpStencilFail;
  8880. };
  8881. Engine.prototype.getStencilOperationDepthFail = function () {
  8882. return this._stencilState.stencilOpDepthFail;
  8883. };
  8884. Engine.prototype.getStencilOperationPass = function () {
  8885. return this._stencilState.stencilOpStencilDepthPass;
  8886. };
  8887. Engine.prototype.setStencilOperationFail = function (operation) {
  8888. this._stencilState.stencilOpStencilFail = operation;
  8889. };
  8890. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8891. this._stencilState.stencilOpDepthFail = operation;
  8892. };
  8893. Engine.prototype.setStencilOperationPass = function (operation) {
  8894. this._stencilState.stencilOpStencilDepthPass = operation;
  8895. };
  8896. Engine.prototype.setDitheringState = function (value) {
  8897. if (value) {
  8898. this._gl.enable(this._gl.DITHER);
  8899. }
  8900. else {
  8901. this._gl.disable(this._gl.DITHER);
  8902. }
  8903. };
  8904. Engine.prototype.setRasterizerState = function (value) {
  8905. if (value) {
  8906. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  8907. }
  8908. else {
  8909. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  8910. }
  8911. };
  8912. /**
  8913. * stop executing a render loop function and remove it from the execution array
  8914. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8915. */
  8916. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8917. if (!renderFunction) {
  8918. this._activeRenderLoops = [];
  8919. return;
  8920. }
  8921. var index = this._activeRenderLoops.indexOf(renderFunction);
  8922. if (index >= 0) {
  8923. this._activeRenderLoops.splice(index, 1);
  8924. }
  8925. };
  8926. Engine.prototype._renderLoop = function () {
  8927. if (!this._contextWasLost) {
  8928. var shouldRender = true;
  8929. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8930. shouldRender = false;
  8931. }
  8932. if (shouldRender) {
  8933. // Start new frame
  8934. this.beginFrame();
  8935. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8936. var renderFunction = this._activeRenderLoops[index];
  8937. renderFunction();
  8938. }
  8939. // Present
  8940. this.endFrame();
  8941. }
  8942. }
  8943. if (this._activeRenderLoops.length > 0) {
  8944. // Register new frame
  8945. var requester = null;
  8946. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8947. requester = this._vrDisplay;
  8948. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8949. }
  8950. else {
  8951. this._renderingQueueLaunched = false;
  8952. }
  8953. };
  8954. /**
  8955. * Register and execute a render loop. The engine can have more than one render function.
  8956. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8957. * @example
  8958. * engine.runRenderLoop(function () {
  8959. * scene.render()
  8960. * })
  8961. */
  8962. Engine.prototype.runRenderLoop = function (renderFunction) {
  8963. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8964. return;
  8965. }
  8966. this._activeRenderLoops.push(renderFunction);
  8967. if (!this._renderingQueueLaunched) {
  8968. this._renderingQueueLaunched = true;
  8969. this._bindedRenderFunction = this._renderLoop.bind(this);
  8970. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8971. }
  8972. };
  8973. /**
  8974. * Toggle full screen mode.
  8975. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8976. * @param {any} options - an options object to be sent to the requestFullscreen function
  8977. */
  8978. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8979. if (this.isFullscreen) {
  8980. BABYLON.Tools.ExitFullscreen();
  8981. }
  8982. else {
  8983. this._pointerLockRequested = requestPointerLock;
  8984. if (this._renderingCanvas) {
  8985. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8986. }
  8987. }
  8988. };
  8989. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8990. if (stencil === void 0) { stencil = false; }
  8991. this.applyStates();
  8992. var mode = 0;
  8993. if (backBuffer && color) {
  8994. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8995. mode |= this._gl.COLOR_BUFFER_BIT;
  8996. }
  8997. if (depth) {
  8998. this._gl.clearDepth(1.0);
  8999. mode |= this._gl.DEPTH_BUFFER_BIT;
  9000. }
  9001. if (stencil) {
  9002. this._gl.clearStencil(0);
  9003. mode |= this._gl.STENCIL_BUFFER_BIT;
  9004. }
  9005. this._gl.clear(mode);
  9006. };
  9007. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9008. var gl = this._gl;
  9009. // Save state
  9010. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9011. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9012. // Change state
  9013. gl.enable(gl.SCISSOR_TEST);
  9014. gl.scissor(x, y, width, height);
  9015. // Clear
  9016. this.clear(clearColor, true, true, true);
  9017. // Restore state
  9018. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9019. if (curScissor === true) {
  9020. gl.enable(gl.SCISSOR_TEST);
  9021. }
  9022. else {
  9023. gl.disable(gl.SCISSOR_TEST);
  9024. }
  9025. };
  9026. /**
  9027. * Set the WebGL's viewport
  9028. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9029. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9030. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9031. */
  9032. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9033. var width = requiredWidth || this.getRenderWidth();
  9034. var height = requiredHeight || this.getRenderHeight();
  9035. var x = viewport.x || 0;
  9036. var y = viewport.y || 0;
  9037. this._cachedViewport = viewport;
  9038. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9039. };
  9040. /**
  9041. * Directly set the WebGL Viewport
  9042. * The x, y, width & height are directly passed to the WebGL call
  9043. * @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.
  9044. */
  9045. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9046. var currentViewport = this._cachedViewport;
  9047. this._cachedViewport = null;
  9048. this._gl.viewport(x, y, width, height);
  9049. return currentViewport;
  9050. };
  9051. Engine.prototype.beginFrame = function () {
  9052. this.onBeginFrameObservable.notifyObservers(this);
  9053. this._measureFps();
  9054. };
  9055. Engine.prototype.endFrame = function () {
  9056. //force a flush in case we are using a bad OS.
  9057. if (this._badOS) {
  9058. this.flushFramebuffer();
  9059. }
  9060. //submit frame to the vr device, if enabled
  9061. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9062. // TODO: We should only submit the frame if we read frameData successfully.
  9063. this._vrDisplay.submitFrame();
  9064. }
  9065. this.onEndFrameObservable.notifyObservers(this);
  9066. };
  9067. /**
  9068. * resize the view according to the canvas' size.
  9069. * @example
  9070. * window.addEventListener("resize", function () {
  9071. * engine.resize();
  9072. * });
  9073. */
  9074. Engine.prototype.resize = function () {
  9075. // We're not resizing the size of the canvas while in VR mode & presenting
  9076. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9077. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9078. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9079. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9080. }
  9081. };
  9082. /**
  9083. * force a specific size of the canvas
  9084. * @param {number} width - the new canvas' width
  9085. * @param {number} height - the new canvas' height
  9086. */
  9087. Engine.prototype.setSize = function (width, height) {
  9088. if (!this._renderingCanvas) {
  9089. return;
  9090. }
  9091. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9092. return;
  9093. }
  9094. this._renderingCanvas.width = width;
  9095. this._renderingCanvas.height = height;
  9096. for (var index = 0; index < this.scenes.length; index++) {
  9097. var scene = this.scenes[index];
  9098. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9099. var cam = scene.cameras[camIndex];
  9100. cam._currentRenderId = 0;
  9101. }
  9102. }
  9103. if (this.onResizeObservable.hasObservers) {
  9104. this.onResizeObservable.notifyObservers(this);
  9105. }
  9106. };
  9107. // WebVR functions
  9108. Engine.prototype.isVRDevicePresent = function () {
  9109. return !!this._vrDisplay;
  9110. };
  9111. Engine.prototype.getVRDevice = function () {
  9112. return this._vrDisplay;
  9113. };
  9114. Engine.prototype.initWebVR = function () {
  9115. var _this = this;
  9116. var notifyObservers = function () {
  9117. var eventArgs = {
  9118. vrDisplay: _this._vrDisplay,
  9119. vrSupported: _this._vrSupported
  9120. };
  9121. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9122. };
  9123. if (!this._onVrDisplayConnect) {
  9124. this._onVrDisplayConnect = function (event) {
  9125. _this._vrDisplay = event.display;
  9126. notifyObservers();
  9127. };
  9128. this._onVrDisplayDisconnect = function () {
  9129. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9130. _this._vrDisplay = undefined;
  9131. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9132. notifyObservers();
  9133. };
  9134. this._onVrDisplayPresentChange = function () {
  9135. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9136. };
  9137. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9138. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9139. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9140. }
  9141. this._getVRDisplays(notifyObservers);
  9142. return this.onVRDisplayChangedObservable;
  9143. };
  9144. Engine.prototype.enableVR = function () {
  9145. var _this = this;
  9146. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9147. var onResolved = function () {
  9148. _this.onVRRequestPresentComplete.notifyObservers(true);
  9149. _this._onVRFullScreenTriggered();
  9150. };
  9151. var onRejected = function () {
  9152. _this.onVRRequestPresentComplete.notifyObservers(false);
  9153. };
  9154. this.onVRRequestPresentStart.notifyObservers(this);
  9155. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9156. }
  9157. };
  9158. Engine.prototype.disableVR = function () {
  9159. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9160. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9161. }
  9162. };
  9163. Engine.prototype._getVRDisplays = function (callback) {
  9164. var _this = this;
  9165. var getWebVRDevices = function (devices) {
  9166. _this._vrSupported = true;
  9167. // note that devices may actually be an empty array. This is fine;
  9168. // we expect this._vrDisplay to be undefined in this case.
  9169. return _this._vrDisplay = devices[0];
  9170. };
  9171. if (navigator.getVRDisplays) {
  9172. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9173. // TODO: System CANNOT support WebVR, despite API presence.
  9174. _this._vrSupported = false;
  9175. callback();
  9176. });
  9177. }
  9178. else {
  9179. // TODO: Browser does not support WebVR
  9180. this._vrDisplay = undefined;
  9181. this._vrSupported = false;
  9182. callback();
  9183. }
  9184. };
  9185. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9186. if (this._currentRenderTarget) {
  9187. this.unBindFramebuffer(this._currentRenderTarget);
  9188. }
  9189. this._currentRenderTarget = texture;
  9190. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9191. var gl = this._gl;
  9192. if (texture.isCube) {
  9193. if (faceIndex === undefined) {
  9194. faceIndex = 0;
  9195. }
  9196. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9197. }
  9198. if (this._cachedViewport && !forceFullscreenViewport) {
  9199. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9200. }
  9201. else {
  9202. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9203. }
  9204. this.wipeCaches();
  9205. };
  9206. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9207. if (this._currentFramebuffer !== framebuffer) {
  9208. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9209. this._currentFramebuffer = framebuffer;
  9210. }
  9211. };
  9212. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9213. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9214. this._currentRenderTarget = null;
  9215. // If MSAA, we need to bitblt back to main texture
  9216. var gl = this._gl;
  9217. if (texture._MSAAFramebuffer) {
  9218. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9219. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9220. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9221. }
  9222. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9223. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9224. gl.generateMipmap(gl.TEXTURE_2D);
  9225. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9226. }
  9227. if (onBeforeUnbind) {
  9228. if (texture._MSAAFramebuffer) {
  9229. // Bind the correct framebuffer
  9230. this.bindUnboundFramebuffer(texture._framebuffer);
  9231. }
  9232. onBeforeUnbind();
  9233. }
  9234. this.bindUnboundFramebuffer(null);
  9235. };
  9236. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9237. if (texture.generateMipMaps) {
  9238. var gl = this._gl;
  9239. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9240. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9241. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9242. }
  9243. };
  9244. Engine.prototype.flushFramebuffer = function () {
  9245. this._gl.flush();
  9246. };
  9247. Engine.prototype.restoreDefaultFramebuffer = function () {
  9248. if (this._currentRenderTarget) {
  9249. this.unBindFramebuffer(this._currentRenderTarget);
  9250. }
  9251. else {
  9252. this.bindUnboundFramebuffer(null);
  9253. }
  9254. if (this._cachedViewport) {
  9255. this.setViewport(this._cachedViewport);
  9256. }
  9257. this.wipeCaches();
  9258. };
  9259. // UBOs
  9260. Engine.prototype.createUniformBuffer = function (elements) {
  9261. var ubo = this._gl.createBuffer();
  9262. if (!ubo) {
  9263. throw new Error("Unable to create uniform buffer");
  9264. }
  9265. this.bindUniformBuffer(ubo);
  9266. if (elements instanceof Float32Array) {
  9267. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9268. }
  9269. else {
  9270. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9271. }
  9272. this.bindUniformBuffer(null);
  9273. ubo.references = 1;
  9274. return ubo;
  9275. };
  9276. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9277. var ubo = this._gl.createBuffer();
  9278. if (!ubo) {
  9279. throw new Error("Unable to create dynamic uniform buffer");
  9280. }
  9281. this.bindUniformBuffer(ubo);
  9282. if (elements instanceof Float32Array) {
  9283. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9284. }
  9285. else {
  9286. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9287. }
  9288. this.bindUniformBuffer(null);
  9289. ubo.references = 1;
  9290. return ubo;
  9291. };
  9292. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9293. this.bindUniformBuffer(uniformBuffer);
  9294. if (offset === undefined) {
  9295. offset = 0;
  9296. }
  9297. if (count === undefined) {
  9298. if (elements instanceof Float32Array) {
  9299. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9300. }
  9301. else {
  9302. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9303. }
  9304. }
  9305. else {
  9306. if (elements instanceof Float32Array) {
  9307. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9308. }
  9309. else {
  9310. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9311. }
  9312. }
  9313. this.bindUniformBuffer(null);
  9314. };
  9315. // VBOs
  9316. Engine.prototype._resetVertexBufferBinding = function () {
  9317. this.bindArrayBuffer(null);
  9318. this._cachedVertexBuffers = null;
  9319. };
  9320. Engine.prototype.createVertexBuffer = function (vertices) {
  9321. var vbo = this._gl.createBuffer();
  9322. if (!vbo) {
  9323. throw new Error("Unable to create vertex buffer");
  9324. }
  9325. this.bindArrayBuffer(vbo);
  9326. if (vertices instanceof Float32Array) {
  9327. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9328. }
  9329. else {
  9330. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9331. }
  9332. this._resetVertexBufferBinding();
  9333. vbo.references = 1;
  9334. return vbo;
  9335. };
  9336. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9337. var vbo = this._gl.createBuffer();
  9338. if (!vbo) {
  9339. throw new Error("Unable to create dynamic vertex buffer");
  9340. }
  9341. this.bindArrayBuffer(vbo);
  9342. if (vertices instanceof Float32Array) {
  9343. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9344. }
  9345. else {
  9346. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9347. }
  9348. this._resetVertexBufferBinding();
  9349. vbo.references = 1;
  9350. return vbo;
  9351. };
  9352. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9353. if (offset === void 0) { offset = 0; }
  9354. // Force cache update
  9355. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9356. this.bindIndexBuffer(indexBuffer);
  9357. var arrayBuffer;
  9358. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9359. arrayBuffer = indices;
  9360. }
  9361. else {
  9362. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9363. }
  9364. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9365. this._resetIndexBufferBinding();
  9366. };
  9367. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9368. this.bindArrayBuffer(vertexBuffer);
  9369. if (offset === undefined) {
  9370. offset = 0;
  9371. }
  9372. if (count === undefined) {
  9373. if (vertices instanceof Float32Array) {
  9374. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9375. }
  9376. else {
  9377. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9378. }
  9379. }
  9380. else {
  9381. if (vertices instanceof Float32Array) {
  9382. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9383. }
  9384. else {
  9385. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9386. }
  9387. }
  9388. this._resetVertexBufferBinding();
  9389. };
  9390. Engine.prototype._resetIndexBufferBinding = function () {
  9391. this.bindIndexBuffer(null);
  9392. this._cachedIndexBuffer = null;
  9393. };
  9394. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9395. var vbo = this._gl.createBuffer();
  9396. if (!vbo) {
  9397. throw new Error("Unable to create index buffer");
  9398. }
  9399. this.bindIndexBuffer(vbo);
  9400. // Check for 32 bits indices
  9401. var arrayBuffer;
  9402. var need32Bits = false;
  9403. if (indices instanceof Uint16Array) {
  9404. arrayBuffer = indices;
  9405. }
  9406. else {
  9407. //check 32 bit support
  9408. if (this._caps.uintIndices) {
  9409. if (indices instanceof Uint32Array) {
  9410. arrayBuffer = indices;
  9411. need32Bits = true;
  9412. }
  9413. else {
  9414. //number[] or Int32Array, check if 32 bit is necessary
  9415. for (var index = 0; index < indices.length; index++) {
  9416. if (indices[index] > 65535) {
  9417. need32Bits = true;
  9418. break;
  9419. }
  9420. }
  9421. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9422. }
  9423. }
  9424. else {
  9425. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9426. arrayBuffer = new Uint16Array(indices);
  9427. }
  9428. }
  9429. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9430. this._resetIndexBufferBinding();
  9431. vbo.references = 1;
  9432. vbo.is32Bits = need32Bits;
  9433. return vbo;
  9434. };
  9435. Engine.prototype.bindArrayBuffer = function (buffer) {
  9436. if (!this._vaoRecordInProgress) {
  9437. this._unbindVertexArrayObject();
  9438. }
  9439. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9440. };
  9441. Engine.prototype.bindUniformBuffer = function (buffer) {
  9442. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9443. };
  9444. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9445. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9446. };
  9447. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9448. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9449. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9450. };
  9451. ;
  9452. Engine.prototype.bindIndexBuffer = function (buffer) {
  9453. if (!this._vaoRecordInProgress) {
  9454. this._unbindVertexArrayObject();
  9455. }
  9456. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9457. };
  9458. Engine.prototype.bindBuffer = function (buffer, target) {
  9459. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9460. this._gl.bindBuffer(target, buffer);
  9461. this._currentBoundBuffer[target] = buffer;
  9462. }
  9463. };
  9464. Engine.prototype.updateArrayBuffer = function (data) {
  9465. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9466. };
  9467. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9468. var pointer = this._currentBufferPointers[indx];
  9469. var changed = false;
  9470. if (!pointer.active) {
  9471. changed = true;
  9472. pointer.active = true;
  9473. pointer.index = indx;
  9474. pointer.size = size;
  9475. pointer.type = type;
  9476. pointer.normalized = normalized;
  9477. pointer.stride = stride;
  9478. pointer.offset = offset;
  9479. pointer.buffer = buffer;
  9480. }
  9481. else {
  9482. if (pointer.buffer !== buffer) {
  9483. pointer.buffer = buffer;
  9484. changed = true;
  9485. }
  9486. if (pointer.size !== size) {
  9487. pointer.size = size;
  9488. changed = true;
  9489. }
  9490. if (pointer.type !== type) {
  9491. pointer.type = type;
  9492. changed = true;
  9493. }
  9494. if (pointer.normalized !== normalized) {
  9495. pointer.normalized = normalized;
  9496. changed = true;
  9497. }
  9498. if (pointer.stride !== stride) {
  9499. pointer.stride = stride;
  9500. changed = true;
  9501. }
  9502. if (pointer.offset !== offset) {
  9503. pointer.offset = offset;
  9504. changed = true;
  9505. }
  9506. }
  9507. if (changed || this._vaoRecordInProgress) {
  9508. this.bindArrayBuffer(buffer);
  9509. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9510. }
  9511. };
  9512. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9513. if (indexBuffer == null) {
  9514. return;
  9515. }
  9516. if (this._cachedIndexBuffer !== indexBuffer) {
  9517. this._cachedIndexBuffer = indexBuffer;
  9518. this.bindIndexBuffer(indexBuffer);
  9519. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9520. }
  9521. };
  9522. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9523. var attributes = effect.getAttributesNames();
  9524. if (!this._vaoRecordInProgress) {
  9525. this._unbindVertexArrayObject();
  9526. }
  9527. this.unbindAllAttributes();
  9528. for (var index = 0; index < attributes.length; index++) {
  9529. var order = effect.getAttributeLocation(index);
  9530. if (order >= 0) {
  9531. var vertexBuffer = vertexBuffers[attributes[index]];
  9532. if (!vertexBuffer) {
  9533. continue;
  9534. }
  9535. this._gl.enableVertexAttribArray(order);
  9536. if (!this._vaoRecordInProgress) {
  9537. this._vertexAttribArraysEnabled[order] = true;
  9538. }
  9539. var buffer = vertexBuffer.getBuffer();
  9540. if (buffer) {
  9541. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9542. if (vertexBuffer.getIsInstanced()) {
  9543. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9544. if (!this._vaoRecordInProgress) {
  9545. this._currentInstanceLocations.push(order);
  9546. this._currentInstanceBuffers.push(buffer);
  9547. }
  9548. }
  9549. }
  9550. }
  9551. }
  9552. };
  9553. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9554. var vao = this._gl.createVertexArray();
  9555. this._vaoRecordInProgress = true;
  9556. this._gl.bindVertexArray(vao);
  9557. this._mustWipeVertexAttributes = true;
  9558. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9559. this.bindIndexBuffer(indexBuffer);
  9560. this._vaoRecordInProgress = false;
  9561. this._gl.bindVertexArray(null);
  9562. return vao;
  9563. };
  9564. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9565. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9566. this._cachedVertexArrayObject = vertexArrayObject;
  9567. this._gl.bindVertexArray(vertexArrayObject);
  9568. this._cachedVertexBuffers = null;
  9569. this._cachedIndexBuffer = null;
  9570. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9571. this._mustWipeVertexAttributes = true;
  9572. }
  9573. };
  9574. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9575. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9576. this._cachedVertexBuffers = vertexBuffer;
  9577. this._cachedEffectForVertexBuffers = effect;
  9578. var attributesCount = effect.getAttributesCount();
  9579. this._unbindVertexArrayObject();
  9580. this.unbindAllAttributes();
  9581. var offset = 0;
  9582. for (var index = 0; index < attributesCount; index++) {
  9583. if (index < vertexDeclaration.length) {
  9584. var order = effect.getAttributeLocation(index);
  9585. if (order >= 0) {
  9586. this._gl.enableVertexAttribArray(order);
  9587. this._vertexAttribArraysEnabled[order] = true;
  9588. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9589. }
  9590. offset += vertexDeclaration[index] * 4;
  9591. }
  9592. }
  9593. }
  9594. this._bindIndexBufferWithCache(indexBuffer);
  9595. };
  9596. Engine.prototype._unbindVertexArrayObject = function () {
  9597. if (!this._cachedVertexArrayObject) {
  9598. return;
  9599. }
  9600. this._cachedVertexArrayObject = null;
  9601. this._gl.bindVertexArray(null);
  9602. };
  9603. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9604. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9605. this._cachedVertexBuffers = vertexBuffers;
  9606. this._cachedEffectForVertexBuffers = effect;
  9607. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9608. }
  9609. this._bindIndexBufferWithCache(indexBuffer);
  9610. };
  9611. Engine.prototype.unbindInstanceAttributes = function () {
  9612. var boundBuffer;
  9613. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9614. var instancesBuffer = this._currentInstanceBuffers[i];
  9615. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9616. boundBuffer = instancesBuffer;
  9617. this.bindArrayBuffer(instancesBuffer);
  9618. }
  9619. var offsetLocation = this._currentInstanceLocations[i];
  9620. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9621. }
  9622. this._currentInstanceBuffers.length = 0;
  9623. this._currentInstanceLocations.length = 0;
  9624. };
  9625. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9626. this._gl.deleteVertexArray(vao);
  9627. };
  9628. Engine.prototype._releaseBuffer = function (buffer) {
  9629. buffer.references--;
  9630. if (buffer.references === 0) {
  9631. this._gl.deleteBuffer(buffer);
  9632. return true;
  9633. }
  9634. return false;
  9635. };
  9636. Engine.prototype.createInstancesBuffer = function (capacity) {
  9637. var buffer = this._gl.createBuffer();
  9638. if (!buffer) {
  9639. throw new Error("Unable to create instance buffer");
  9640. }
  9641. buffer.capacity = capacity;
  9642. this.bindArrayBuffer(buffer);
  9643. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9644. return buffer;
  9645. };
  9646. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9647. this._gl.deleteBuffer(buffer);
  9648. };
  9649. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9650. this.bindArrayBuffer(instancesBuffer);
  9651. if (data) {
  9652. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9653. }
  9654. if (offsetLocations[0].index !== undefined) {
  9655. var stride = 0;
  9656. for (var i = 0; i < offsetLocations.length; i++) {
  9657. var ai = offsetLocations[i];
  9658. stride += ai.attributeSize * 4;
  9659. }
  9660. for (var i = 0; i < offsetLocations.length; i++) {
  9661. var ai = offsetLocations[i];
  9662. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9663. this._gl.enableVertexAttribArray(ai.index);
  9664. this._vertexAttribArraysEnabled[ai.index] = true;
  9665. }
  9666. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9667. this._gl.vertexAttribDivisor(ai.index, 1);
  9668. this._currentInstanceLocations.push(ai.index);
  9669. this._currentInstanceBuffers.push(instancesBuffer);
  9670. }
  9671. }
  9672. else {
  9673. for (var index = 0; index < 4; index++) {
  9674. var offsetLocation = offsetLocations[index];
  9675. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9676. this._gl.enableVertexAttribArray(offsetLocation);
  9677. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9678. }
  9679. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9680. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9681. this._currentInstanceLocations.push(offsetLocation);
  9682. this._currentInstanceBuffers.push(instancesBuffer);
  9683. }
  9684. }
  9685. };
  9686. Engine.prototype.applyStates = function () {
  9687. this._depthCullingState.apply(this._gl);
  9688. this._stencilState.apply(this._gl);
  9689. this._alphaState.apply(this._gl);
  9690. };
  9691. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9692. // Apply states
  9693. this.applyStates();
  9694. this._drawCalls.addCount(1, false);
  9695. // Render
  9696. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9697. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9698. if (instancesCount) {
  9699. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9700. return;
  9701. }
  9702. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9703. };
  9704. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9705. // Apply states
  9706. this.applyStates();
  9707. this._drawCalls.addCount(1, false);
  9708. if (instancesCount) {
  9709. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9710. return;
  9711. }
  9712. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9713. };
  9714. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9715. // Apply states
  9716. this.applyStates();
  9717. this._drawCalls.addCount(1, false);
  9718. if (instancesCount) {
  9719. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9720. return;
  9721. }
  9722. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9723. };
  9724. // Shaders
  9725. Engine.prototype._releaseEffect = function (effect) {
  9726. if (this._compiledEffects[effect._key]) {
  9727. delete this._compiledEffects[effect._key];
  9728. this._deleteProgram(effect.getProgram());
  9729. }
  9730. };
  9731. Engine.prototype._deleteProgram = function (program) {
  9732. if (program) {
  9733. program.__SPECTOR_rebuildProgram = null;
  9734. if (program.transformFeedback) {
  9735. this.deleteTransformFeedback(program.transformFeedback);
  9736. program.transformFeedback = null;
  9737. }
  9738. this._gl.deleteProgram(program);
  9739. }
  9740. };
  9741. /**
  9742. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9743. * @param samplers An array of string used to represent textures
  9744. */
  9745. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9746. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9747. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9748. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9749. if (this._compiledEffects[name]) {
  9750. var compiledEffect = this._compiledEffects[name];
  9751. if (onCompiled && compiledEffect.isReady()) {
  9752. onCompiled(compiledEffect);
  9753. }
  9754. return compiledEffect;
  9755. }
  9756. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9757. effect._key = name;
  9758. this._compiledEffects[name] = effect;
  9759. return effect;
  9760. };
  9761. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9762. if (uniformsNames === void 0) { uniformsNames = []; }
  9763. if (samplers === void 0) { samplers = []; }
  9764. if (defines === void 0) { defines = ""; }
  9765. return this.createEffect({
  9766. vertex: "particles",
  9767. fragmentElement: fragmentName
  9768. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9769. };
  9770. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9771. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9772. context = context || this._gl;
  9773. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9774. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9775. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9776. };
  9777. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9778. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9779. context = context || this._gl;
  9780. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9781. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9782. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9783. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9784. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9785. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9786. return program;
  9787. };
  9788. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9789. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9790. var shaderProgram = context.createProgram();
  9791. if (!shaderProgram) {
  9792. throw new Error("Unable to create program");
  9793. }
  9794. context.attachShader(shaderProgram, vertexShader);
  9795. context.attachShader(shaderProgram, fragmentShader);
  9796. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9797. var transformFeedback = this.createTransformFeedback();
  9798. this.bindTransformFeedback(transformFeedback);
  9799. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9800. shaderProgram.transformFeedback = transformFeedback;
  9801. }
  9802. context.linkProgram(shaderProgram);
  9803. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9804. this.bindTransformFeedback(null);
  9805. }
  9806. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9807. if (!linked) {
  9808. context.validateProgram(shaderProgram);
  9809. var error = context.getProgramInfoLog(shaderProgram);
  9810. if (error) {
  9811. throw new Error(error);
  9812. }
  9813. }
  9814. context.deleteShader(vertexShader);
  9815. context.deleteShader(fragmentShader);
  9816. return shaderProgram;
  9817. };
  9818. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9819. var results = new Array();
  9820. for (var index = 0; index < uniformsNames.length; index++) {
  9821. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9822. }
  9823. return results;
  9824. };
  9825. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9826. var results = [];
  9827. for (var index = 0; index < attributesNames.length; index++) {
  9828. try {
  9829. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9830. }
  9831. catch (e) {
  9832. results.push(-1);
  9833. }
  9834. }
  9835. return results;
  9836. };
  9837. Engine.prototype.enableEffect = function (effect) {
  9838. if (!effect) {
  9839. return;
  9840. }
  9841. // Use program
  9842. this.setProgram(effect.getProgram());
  9843. this._currentEffect = effect;
  9844. if (effect.onBind) {
  9845. effect.onBind(effect);
  9846. }
  9847. effect.onBindObservable.notifyObservers(effect);
  9848. };
  9849. Engine.prototype.setIntArray = function (uniform, array) {
  9850. if (!uniform)
  9851. return;
  9852. this._gl.uniform1iv(uniform, array);
  9853. };
  9854. Engine.prototype.setIntArray2 = function (uniform, array) {
  9855. if (!uniform || array.length % 2 !== 0)
  9856. return;
  9857. this._gl.uniform2iv(uniform, array);
  9858. };
  9859. Engine.prototype.setIntArray3 = function (uniform, array) {
  9860. if (!uniform || array.length % 3 !== 0)
  9861. return;
  9862. this._gl.uniform3iv(uniform, array);
  9863. };
  9864. Engine.prototype.setIntArray4 = function (uniform, array) {
  9865. if (!uniform || array.length % 4 !== 0)
  9866. return;
  9867. this._gl.uniform4iv(uniform, array);
  9868. };
  9869. Engine.prototype.setFloatArray = function (uniform, array) {
  9870. if (!uniform)
  9871. return;
  9872. this._gl.uniform1fv(uniform, array);
  9873. };
  9874. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9875. if (!uniform || array.length % 2 !== 0)
  9876. return;
  9877. this._gl.uniform2fv(uniform, array);
  9878. };
  9879. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9880. if (!uniform || array.length % 3 !== 0)
  9881. return;
  9882. this._gl.uniform3fv(uniform, array);
  9883. };
  9884. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9885. if (!uniform || array.length % 4 !== 0)
  9886. return;
  9887. this._gl.uniform4fv(uniform, array);
  9888. };
  9889. Engine.prototype.setArray = function (uniform, array) {
  9890. if (!uniform)
  9891. return;
  9892. this._gl.uniform1fv(uniform, array);
  9893. };
  9894. Engine.prototype.setArray2 = function (uniform, array) {
  9895. if (!uniform || array.length % 2 !== 0)
  9896. return;
  9897. this._gl.uniform2fv(uniform, array);
  9898. };
  9899. Engine.prototype.setArray3 = function (uniform, array) {
  9900. if (!uniform || array.length % 3 !== 0)
  9901. return;
  9902. this._gl.uniform3fv(uniform, array);
  9903. };
  9904. Engine.prototype.setArray4 = function (uniform, array) {
  9905. if (!uniform || array.length % 4 !== 0)
  9906. return;
  9907. this._gl.uniform4fv(uniform, array);
  9908. };
  9909. Engine.prototype.setMatrices = function (uniform, matrices) {
  9910. if (!uniform)
  9911. return;
  9912. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9913. };
  9914. Engine.prototype.setMatrix = function (uniform, matrix) {
  9915. if (!uniform)
  9916. return;
  9917. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9918. };
  9919. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9920. if (!uniform)
  9921. return;
  9922. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9923. };
  9924. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9925. if (!uniform)
  9926. return;
  9927. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9928. };
  9929. Engine.prototype.setFloat = function (uniform, value) {
  9930. if (!uniform)
  9931. return;
  9932. this._gl.uniform1f(uniform, value);
  9933. };
  9934. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9935. if (!uniform)
  9936. return;
  9937. this._gl.uniform2f(uniform, x, y);
  9938. };
  9939. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9940. if (!uniform)
  9941. return;
  9942. this._gl.uniform3f(uniform, x, y, z);
  9943. };
  9944. Engine.prototype.setBool = function (uniform, bool) {
  9945. if (!uniform)
  9946. return;
  9947. this._gl.uniform1i(uniform, bool);
  9948. };
  9949. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9950. if (!uniform)
  9951. return;
  9952. this._gl.uniform4f(uniform, x, y, z, w);
  9953. };
  9954. Engine.prototype.setColor3 = function (uniform, color3) {
  9955. if (!uniform)
  9956. return;
  9957. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9958. };
  9959. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9960. if (!uniform)
  9961. return;
  9962. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9963. };
  9964. // States
  9965. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9966. if (zOffset === void 0) { zOffset = 0; }
  9967. if (reverseSide === void 0) { reverseSide = false; }
  9968. // Culling
  9969. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9970. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9971. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9972. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9973. if (culling) {
  9974. this._depthCullingState.cullFace = cullFace;
  9975. this._depthCullingState.cull = true;
  9976. }
  9977. else {
  9978. this._depthCullingState.cull = false;
  9979. }
  9980. }
  9981. // Z offset
  9982. this.setZOffset(zOffset);
  9983. };
  9984. Engine.prototype.setZOffset = function (value) {
  9985. this._depthCullingState.zOffset = value;
  9986. };
  9987. Engine.prototype.getZOffset = function () {
  9988. return this._depthCullingState.zOffset;
  9989. };
  9990. Engine.prototype.setDepthBuffer = function (enable) {
  9991. this._depthCullingState.depthTest = enable;
  9992. };
  9993. Engine.prototype.getDepthWrite = function () {
  9994. return this._depthCullingState.depthMask;
  9995. };
  9996. Engine.prototype.setDepthWrite = function (enable) {
  9997. this._depthCullingState.depthMask = enable;
  9998. };
  9999. Engine.prototype.setColorWrite = function (enable) {
  10000. this._gl.colorMask(enable, enable, enable, enable);
  10001. this._colorWrite = enable;
  10002. };
  10003. Engine.prototype.getColorWrite = function () {
  10004. return this._colorWrite;
  10005. };
  10006. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10007. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10008. };
  10009. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10010. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10011. if (this._alphaMode === mode) {
  10012. return;
  10013. }
  10014. switch (mode) {
  10015. case Engine.ALPHA_DISABLE:
  10016. this._alphaState.alphaBlend = false;
  10017. break;
  10018. case Engine.ALPHA_PREMULTIPLIED:
  10019. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10020. this._alphaState.alphaBlend = true;
  10021. break;
  10022. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10023. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10024. this._alphaState.alphaBlend = true;
  10025. break;
  10026. case Engine.ALPHA_COMBINE:
  10027. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10028. this._alphaState.alphaBlend = true;
  10029. break;
  10030. case Engine.ALPHA_ONEONE:
  10031. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10032. this._alphaState.alphaBlend = true;
  10033. break;
  10034. case Engine.ALPHA_ADD:
  10035. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10036. this._alphaState.alphaBlend = true;
  10037. break;
  10038. case Engine.ALPHA_SUBTRACT:
  10039. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10040. this._alphaState.alphaBlend = true;
  10041. break;
  10042. case Engine.ALPHA_MULTIPLY:
  10043. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10044. this._alphaState.alphaBlend = true;
  10045. break;
  10046. case Engine.ALPHA_MAXIMIZED:
  10047. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10048. this._alphaState.alphaBlend = true;
  10049. break;
  10050. case Engine.ALPHA_INTERPOLATE:
  10051. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10052. this._alphaState.alphaBlend = true;
  10053. break;
  10054. case Engine.ALPHA_SCREENMODE:
  10055. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10056. this._alphaState.alphaBlend = true;
  10057. break;
  10058. }
  10059. if (!noDepthWriteChange) {
  10060. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10061. }
  10062. this._alphaMode = mode;
  10063. };
  10064. Engine.prototype.getAlphaMode = function () {
  10065. return this._alphaMode;
  10066. };
  10067. Engine.prototype.setAlphaTesting = function (enable) {
  10068. this._alphaTest = enable;
  10069. };
  10070. Engine.prototype.getAlphaTesting = function () {
  10071. return !!this._alphaTest;
  10072. };
  10073. // Textures
  10074. Engine.prototype.wipeCaches = function (bruteForce) {
  10075. if (this.preventCacheWipeBetweenFrames) {
  10076. return;
  10077. }
  10078. this.resetTextureCache();
  10079. this._currentEffect = null;
  10080. // 6/8/2017: deltakosh: Should not be required anymore.
  10081. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10082. if (bruteForce) {
  10083. this._currentProgram = null;
  10084. this._stencilState.reset();
  10085. this._depthCullingState.reset();
  10086. this.setDepthFunctionToLessOrEqual();
  10087. this._alphaState.reset();
  10088. }
  10089. this._cachedVertexBuffers = null;
  10090. this._cachedIndexBuffer = null;
  10091. this._cachedEffectForVertexBuffers = null;
  10092. this._unbindVertexArrayObject();
  10093. this.bindIndexBuffer(null);
  10094. this.bindArrayBuffer(null);
  10095. };
  10096. /**
  10097. * Set the compressed texture format to use, based on the formats you have, and the formats
  10098. * supported by the hardware / browser.
  10099. *
  10100. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10101. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10102. * to API arguments needed to compressed textures. This puts the burden on the container
  10103. * generator to house the arcane code for determining these for current & future formats.
  10104. *
  10105. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10106. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10107. *
  10108. * Note: The result of this call is not taken into account when a texture is base64.
  10109. *
  10110. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10111. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10112. *
  10113. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10114. * @returns The extension selected.
  10115. */
  10116. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10117. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10118. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10119. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10120. return this._textureFormatInUse = this._texturesSupported[i];
  10121. }
  10122. }
  10123. }
  10124. // actively set format to nothing, to allow this to be called more than once
  10125. // and possibly fail the 2nd time
  10126. this._textureFormatInUse = null;
  10127. return null;
  10128. };
  10129. Engine.prototype._createTexture = function () {
  10130. var texture = this._gl.createTexture();
  10131. if (!texture) {
  10132. throw new Error("Unable to create texture");
  10133. }
  10134. return texture;
  10135. };
  10136. /**
  10137. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10138. * @param {string} urlArg- This contains one of the following:
  10139. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10140. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10141. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10142. *
  10143. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10144. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10145. * @param {Scene} scene- Needed for loading to the correct scene.
  10146. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10147. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10148. * @param {callback} onError- Optional callback to be called upon failure.
  10149. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10150. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10151. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10152. *
  10153. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10154. */
  10155. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10156. var _this = this;
  10157. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10158. if (onLoad === void 0) { onLoad = null; }
  10159. if (onError === void 0) { onError = null; }
  10160. if (buffer === void 0) { buffer = null; }
  10161. if (fallBack === void 0) { fallBack = null; }
  10162. if (format === void 0) { format = null; }
  10163. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10164. var fromData = url.substr(0, 5) === "data:";
  10165. var fromBlob = url.substr(0, 5) === "blob:";
  10166. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10167. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10168. // establish the file extension, if possible
  10169. var lastDot = url.lastIndexOf('.');
  10170. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10171. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10172. var isTGA = (extension === ".tga");
  10173. // determine if a ktx file should be substituted
  10174. var isKTX = false;
  10175. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10176. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10177. isKTX = true;
  10178. }
  10179. if (scene) {
  10180. scene._addPendingData(texture);
  10181. }
  10182. texture.url = url;
  10183. texture.generateMipMaps = !noMipmap;
  10184. texture.samplingMode = samplingMode;
  10185. texture.invertY = invertY;
  10186. if (!this._doNotHandleContextLost) {
  10187. // Keep a link to the buffer only if we plan to handle context lost
  10188. texture._buffer = buffer;
  10189. }
  10190. if (onLoad) {
  10191. texture.onLoadedObservable.add(onLoad);
  10192. }
  10193. if (!fallBack)
  10194. this._internalTexturesCache.push(texture);
  10195. var onerror = function () {
  10196. if (scene) {
  10197. scene._removePendingData(texture);
  10198. }
  10199. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10200. if (isKTX) {
  10201. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10202. }
  10203. else if ((isTGA || isDDS) && BABYLON.Tools.UseFallbackTexture) {
  10204. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10205. }
  10206. else if (onError) {
  10207. onError();
  10208. }
  10209. };
  10210. var callback = null;
  10211. // processing for non-image formats
  10212. if (isKTX || isTGA || isDDS) {
  10213. if (isKTX) {
  10214. callback = function (data) {
  10215. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10216. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10217. ktx.uploadLevels(_this._gl, !noMipmap);
  10218. return false;
  10219. }, samplingMode);
  10220. };
  10221. }
  10222. else if (isTGA) {
  10223. callback = function (arrayBuffer) {
  10224. var data = new Uint8Array(arrayBuffer);
  10225. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10226. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10227. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10228. return false;
  10229. }, samplingMode);
  10230. };
  10231. }
  10232. else if (isDDS) {
  10233. callback = function (data) {
  10234. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10235. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10236. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10237. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10238. return false;
  10239. }, samplingMode);
  10240. };
  10241. }
  10242. if (!buffer) {
  10243. BABYLON.Tools.LoadFile(url, function (data) {
  10244. if (callback) {
  10245. callback(data);
  10246. }
  10247. }, undefined, scene ? scene.database : undefined, true, onerror);
  10248. }
  10249. else {
  10250. if (callback) {
  10251. callback(buffer);
  10252. }
  10253. }
  10254. // image format processing
  10255. }
  10256. else {
  10257. var onload = function (img) {
  10258. if (fromBlob && !_this._doNotHandleContextLost) {
  10259. // We need to store the image if we need to rebuild the texture
  10260. // in case of a webgl context lost
  10261. texture._buffer = img;
  10262. }
  10263. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10264. var gl = _this._gl;
  10265. var isPot = (img.width === potWidth && img.height === potHeight);
  10266. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10267. if (isPot) {
  10268. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10269. return false;
  10270. }
  10271. // Using shaders to rescale because canvas.drawImage is lossy
  10272. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10273. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10274. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10275. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10276. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10277. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10278. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10279. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10280. _this._releaseTexture(source);
  10281. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10282. continuationCallback();
  10283. });
  10284. return true;
  10285. }, samplingMode);
  10286. };
  10287. if (!fromData || isBase64)
  10288. if (buffer instanceof HTMLImageElement) {
  10289. onload(buffer);
  10290. }
  10291. else {
  10292. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10293. }
  10294. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10295. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10296. else
  10297. onload(buffer);
  10298. }
  10299. return texture;
  10300. };
  10301. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10302. var _this = this;
  10303. var rtt = this.createRenderTargetTexture({
  10304. width: destination.width,
  10305. height: destination.height,
  10306. }, {
  10307. generateMipMaps: false,
  10308. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10309. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10310. generateDepthBuffer: false,
  10311. generateStencilBuffer: false
  10312. });
  10313. if (!this._rescalePostProcess) {
  10314. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10315. }
  10316. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10317. _this._rescalePostProcess.onApply = function (effect) {
  10318. effect._bindTexture("textureSampler", source);
  10319. };
  10320. var hostingScene = scene;
  10321. if (!hostingScene) {
  10322. hostingScene = _this.scenes[_this.scenes.length - 1];
  10323. }
  10324. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10325. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10326. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10327. _this.unBindFramebuffer(rtt);
  10328. _this._releaseTexture(rtt);
  10329. if (onComplete) {
  10330. onComplete();
  10331. }
  10332. });
  10333. };
  10334. Engine.prototype._getInternalFormat = function (format) {
  10335. var internalFormat = this._gl.RGBA;
  10336. switch (format) {
  10337. case Engine.TEXTUREFORMAT_ALPHA:
  10338. internalFormat = this._gl.ALPHA;
  10339. break;
  10340. case Engine.TEXTUREFORMAT_LUMINANCE:
  10341. internalFormat = this._gl.LUMINANCE;
  10342. break;
  10343. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10344. internalFormat = this._gl.LUMINANCE_ALPHA;
  10345. break;
  10346. case Engine.TEXTUREFORMAT_RGB:
  10347. internalFormat = this._gl.RGB;
  10348. break;
  10349. case Engine.TEXTUREFORMAT_RGBA:
  10350. internalFormat = this._gl.RGBA;
  10351. break;
  10352. }
  10353. return internalFormat;
  10354. };
  10355. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10356. if (compression === void 0) { compression = null; }
  10357. if (!texture) {
  10358. return;
  10359. }
  10360. var internalFormat = this._getInternalFormat(format);
  10361. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10362. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10363. if (!this._doNotHandleContextLost) {
  10364. texture._bufferView = data;
  10365. texture.format = format;
  10366. texture.invertY = invertY;
  10367. texture._compression = compression;
  10368. }
  10369. if (texture.width % 4 !== 0) {
  10370. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10371. }
  10372. if (compression && data) {
  10373. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10374. }
  10375. else {
  10376. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10377. }
  10378. if (texture.generateMipMaps) {
  10379. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10380. }
  10381. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10382. this.resetTextureCache();
  10383. texture.isReady = true;
  10384. };
  10385. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10386. if (compression === void 0) { compression = null; }
  10387. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10388. texture.baseWidth = width;
  10389. texture.baseHeight = height;
  10390. texture.width = width;
  10391. texture.height = height;
  10392. texture.format = format;
  10393. texture.generateMipMaps = generateMipMaps;
  10394. texture.samplingMode = samplingMode;
  10395. texture.invertY = invertY;
  10396. texture._compression = compression;
  10397. if (!this._doNotHandleContextLost) {
  10398. texture._bufferView = data;
  10399. }
  10400. this.updateRawTexture(texture, data, format, invertY, compression);
  10401. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10402. // Filters
  10403. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10404. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10405. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10406. if (generateMipMaps) {
  10407. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10408. }
  10409. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10410. this._internalTexturesCache.push(texture);
  10411. return texture;
  10412. };
  10413. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10414. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10415. texture.baseWidth = width;
  10416. texture.baseHeight = height;
  10417. if (generateMipMaps) {
  10418. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10419. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10420. }
  10421. this.resetTextureCache();
  10422. texture.width = width;
  10423. texture.height = height;
  10424. texture.isReady = false;
  10425. texture.generateMipMaps = generateMipMaps;
  10426. texture.samplingMode = samplingMode;
  10427. this.updateTextureSamplingMode(samplingMode, texture);
  10428. this._internalTexturesCache.push(texture);
  10429. return texture;
  10430. };
  10431. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10432. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10433. if (texture.isCube) {
  10434. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10435. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10436. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10437. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10438. }
  10439. else if (texture.is3D) {
  10440. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10441. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10442. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10443. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10444. }
  10445. else {
  10446. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10447. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10448. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10449. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10450. }
  10451. texture.samplingMode = samplingMode;
  10452. };
  10453. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10454. if (premulAlpha === void 0) { premulAlpha = false; }
  10455. if (!texture) {
  10456. return;
  10457. }
  10458. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10459. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10460. if (premulAlpha) {
  10461. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10462. }
  10463. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10464. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10465. if (texture.generateMipMaps) {
  10466. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10467. }
  10468. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10469. if (premulAlpha) {
  10470. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10471. }
  10472. this.resetTextureCache();
  10473. texture.isReady = true;
  10474. };
  10475. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10476. if (!texture || texture._isDisabled) {
  10477. return;
  10478. }
  10479. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10480. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10481. try {
  10482. // Testing video texture support
  10483. if (this._videoTextureSupported === undefined) {
  10484. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10485. if (this._gl.getError() !== 0) {
  10486. this._videoTextureSupported = false;
  10487. }
  10488. else {
  10489. this._videoTextureSupported = true;
  10490. }
  10491. }
  10492. // Copy video through the current working canvas if video texture is not supported
  10493. if (!this._videoTextureSupported) {
  10494. if (!texture._workingCanvas) {
  10495. texture._workingCanvas = document.createElement("canvas");
  10496. var context = texture._workingCanvas.getContext("2d");
  10497. if (!context) {
  10498. throw new Error("Unable to get 2d context");
  10499. }
  10500. texture._workingContext = context;
  10501. texture._workingCanvas.width = texture.width;
  10502. texture._workingCanvas.height = texture.height;
  10503. }
  10504. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10505. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10506. }
  10507. else {
  10508. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10509. }
  10510. if (texture.generateMipMaps) {
  10511. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10512. }
  10513. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10514. this.resetTextureCache();
  10515. texture.isReady = true;
  10516. }
  10517. catch (ex) {
  10518. // Something unexpected
  10519. // Let's disable the texture
  10520. texture._isDisabled = true;
  10521. }
  10522. };
  10523. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10524. var fullOptions = new RenderTargetCreationOptions();
  10525. if (options !== undefined && typeof options === "object") {
  10526. fullOptions.generateMipMaps = options.generateMipMaps;
  10527. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10528. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10529. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10530. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10531. }
  10532. else {
  10533. fullOptions.generateMipMaps = options;
  10534. fullOptions.generateDepthBuffer = true;
  10535. fullOptions.generateStencilBuffer = false;
  10536. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10537. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10538. }
  10539. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10540. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10541. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10542. }
  10543. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10544. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10545. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10546. }
  10547. var gl = this._gl;
  10548. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10549. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10550. var width = size.width || size;
  10551. var height = size.height || size;
  10552. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10553. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10554. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10555. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10556. }
  10557. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10558. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10559. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10560. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10561. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10562. // Create the framebuffer
  10563. var framebuffer = gl.createFramebuffer();
  10564. this.bindUnboundFramebuffer(framebuffer);
  10565. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10566. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10567. if (fullOptions.generateMipMaps) {
  10568. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10569. }
  10570. // Unbind
  10571. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10572. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10573. this.bindUnboundFramebuffer(null);
  10574. texture._framebuffer = framebuffer;
  10575. texture.baseWidth = width;
  10576. texture.baseHeight = height;
  10577. texture.width = width;
  10578. texture.height = height;
  10579. texture.isReady = true;
  10580. texture.samples = 1;
  10581. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10582. texture.samplingMode = fullOptions.samplingMode;
  10583. texture.type = fullOptions.type;
  10584. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10585. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10586. this.resetTextureCache();
  10587. this._internalTexturesCache.push(texture);
  10588. return texture;
  10589. };
  10590. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10591. var generateMipMaps = false;
  10592. var generateDepthBuffer = true;
  10593. var generateStencilBuffer = false;
  10594. var generateDepthTexture = false;
  10595. var textureCount = 1;
  10596. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10597. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10598. var types = [], samplingModes = [];
  10599. if (options !== undefined) {
  10600. generateMipMaps = options.generateMipMaps;
  10601. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10602. generateStencilBuffer = options.generateStencilBuffer;
  10603. generateDepthTexture = options.generateDepthTexture;
  10604. textureCount = options.textureCount || 1;
  10605. if (options.types) {
  10606. types = options.types;
  10607. }
  10608. if (options.samplingModes) {
  10609. samplingModes = options.samplingModes;
  10610. }
  10611. }
  10612. var gl = this._gl;
  10613. // Create the framebuffer
  10614. var framebuffer = gl.createFramebuffer();
  10615. this.bindUnboundFramebuffer(framebuffer);
  10616. var width = size.width || size;
  10617. var height = size.height || size;
  10618. var textures = [];
  10619. var attachments = [];
  10620. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10621. for (var i = 0; i < textureCount; i++) {
  10622. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10623. var type = types[i] || defaultType;
  10624. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10625. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10626. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10627. }
  10628. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10629. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10630. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10631. }
  10632. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10633. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10634. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10635. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10636. }
  10637. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10638. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10639. textures.push(texture);
  10640. attachments.push(attachment);
  10641. gl.activeTexture(gl["TEXTURE" + i]);
  10642. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10643. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10644. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10647. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10648. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10649. if (generateMipMaps) {
  10650. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10651. }
  10652. // Unbind
  10653. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10654. texture._framebuffer = framebuffer;
  10655. texture._depthStencilBuffer = depthStencilBuffer;
  10656. texture.baseWidth = width;
  10657. texture.baseHeight = height;
  10658. texture.width = width;
  10659. texture.height = height;
  10660. texture.isReady = true;
  10661. texture.samples = 1;
  10662. texture.generateMipMaps = generateMipMaps;
  10663. texture.samplingMode = samplingMode;
  10664. texture.type = type;
  10665. texture._generateDepthBuffer = generateDepthBuffer;
  10666. texture._generateStencilBuffer = generateStencilBuffer;
  10667. this._internalTexturesCache.push(texture);
  10668. }
  10669. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10670. // Depth texture
  10671. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10672. gl.activeTexture(gl.TEXTURE0);
  10673. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10674. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10675. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10676. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10677. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10678. 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);
  10679. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10680. depthTexture._framebuffer = framebuffer;
  10681. depthTexture.baseWidth = width;
  10682. depthTexture.baseHeight = height;
  10683. depthTexture.width = width;
  10684. depthTexture.height = height;
  10685. depthTexture.isReady = true;
  10686. depthTexture.samples = 1;
  10687. depthTexture.generateMipMaps = generateMipMaps;
  10688. depthTexture.samplingMode = gl.NEAREST;
  10689. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10690. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10691. textures.push(depthTexture);
  10692. this._internalTexturesCache.push(depthTexture);
  10693. }
  10694. gl.drawBuffers(attachments);
  10695. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10696. this.bindUnboundFramebuffer(null);
  10697. this.resetTextureCache();
  10698. return textures;
  10699. };
  10700. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10701. if (samples === void 0) { samples = 1; }
  10702. var depthStencilBuffer = null;
  10703. var gl = this._gl;
  10704. // Create the depth/stencil buffer
  10705. if (generateStencilBuffer) {
  10706. depthStencilBuffer = gl.createRenderbuffer();
  10707. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10708. if (samples > 1) {
  10709. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10710. }
  10711. else {
  10712. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10713. }
  10714. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10715. }
  10716. else if (generateDepthBuffer) {
  10717. depthStencilBuffer = gl.createRenderbuffer();
  10718. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10719. if (samples > 1) {
  10720. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10721. }
  10722. else {
  10723. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10724. }
  10725. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10726. }
  10727. return depthStencilBuffer;
  10728. };
  10729. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10730. if (this.webGLVersion < 2 || !texture) {
  10731. return 1;
  10732. }
  10733. if (texture.samples === samples) {
  10734. return samples;
  10735. }
  10736. var gl = this._gl;
  10737. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10738. // Dispose previous render buffers
  10739. if (texture._depthStencilBuffer) {
  10740. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10741. }
  10742. if (texture._MSAAFramebuffer) {
  10743. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10744. }
  10745. if (texture._MSAARenderBuffer) {
  10746. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10747. }
  10748. if (samples > 1) {
  10749. var framebuffer = gl.createFramebuffer();
  10750. if (!framebuffer) {
  10751. throw new Error("Unable to create multi sampled framebuffer");
  10752. }
  10753. texture._MSAAFramebuffer = framebuffer;
  10754. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10755. var colorRenderbuffer = gl.createRenderbuffer();
  10756. if (!colorRenderbuffer) {
  10757. throw new Error("Unable to create multi sampled framebuffer");
  10758. }
  10759. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10760. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10761. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10762. texture._MSAARenderBuffer = colorRenderbuffer;
  10763. }
  10764. else {
  10765. this.bindUnboundFramebuffer(texture._framebuffer);
  10766. }
  10767. texture.samples = samples;
  10768. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10769. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10770. this.bindUnboundFramebuffer(null);
  10771. return samples;
  10772. };
  10773. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10774. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10775. };
  10776. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10777. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10778. };
  10779. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10780. var gl = this._gl;
  10781. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10782. var generateMipMaps = true;
  10783. var generateDepthBuffer = true;
  10784. var generateStencilBuffer = false;
  10785. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10786. if (options !== undefined) {
  10787. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10788. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10789. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10790. if (options.samplingMode !== undefined) {
  10791. samplingMode = options.samplingMode;
  10792. }
  10793. }
  10794. texture.isCube = true;
  10795. texture.generateMipMaps = generateMipMaps;
  10796. texture.samples = 1;
  10797. texture.samplingMode = samplingMode;
  10798. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10799. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10800. for (var face = 0; face < 6; face++) {
  10801. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10802. }
  10803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10807. // Create the framebuffer
  10808. var framebuffer = gl.createFramebuffer();
  10809. this.bindUnboundFramebuffer(framebuffer);
  10810. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10811. // Mipmaps
  10812. if (texture.generateMipMaps) {
  10813. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10814. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10815. }
  10816. // Unbind
  10817. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10818. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10819. this.bindUnboundFramebuffer(null);
  10820. texture._framebuffer = framebuffer;
  10821. texture.width = size;
  10822. texture.height = size;
  10823. texture.isReady = true;
  10824. this.resetTextureCache();
  10825. this._internalTexturesCache.push(texture);
  10826. return texture;
  10827. };
  10828. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10829. var _this = this;
  10830. if (onLoad === void 0) { onLoad = null; }
  10831. if (onError === void 0) { onError = null; }
  10832. if (forcedExtension === void 0) { forcedExtension = null; }
  10833. var callback = function (loadData) {
  10834. if (!loadData) {
  10835. if (onLoad) {
  10836. onLoad(null);
  10837. }
  10838. return;
  10839. }
  10840. var texture = loadData.texture;
  10841. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10842. texture._lodGenerationScale = scale;
  10843. texture._lodGenerationOffset = offset;
  10844. if (_this._caps.textureLOD) {
  10845. // Do not add extra process if texture lod is supported.
  10846. if (onLoad) {
  10847. onLoad(texture);
  10848. }
  10849. return;
  10850. }
  10851. var mipSlices = 3;
  10852. var gl = _this._gl;
  10853. var width = loadData.width;
  10854. if (!width) {
  10855. return;
  10856. }
  10857. var textures = [];
  10858. for (var i = 0; i < mipSlices; i++) {
  10859. //compute LOD from even spacing in smoothness (matching shader calculation)
  10860. var smoothness = i / (mipSlices - 1);
  10861. var roughness = 1 - smoothness;
  10862. var minLODIndex = offset; // roughness = 0
  10863. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10864. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10865. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10866. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10867. glTextureFromLod.isCube = true;
  10868. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10869. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10871. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10873. if (loadData.isDDS) {
  10874. var info = loadData.info;
  10875. var data = loadData.data;
  10876. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10877. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10878. }
  10879. else {
  10880. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10881. }
  10882. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10883. // Wrap in a base texture for easy binding.
  10884. var lodTexture = new BABYLON.BaseTexture(scene);
  10885. lodTexture.isCube = true;
  10886. lodTexture._texture = glTextureFromLod;
  10887. glTextureFromLod.isReady = true;
  10888. textures.push(lodTexture);
  10889. }
  10890. texture._lodTextureHigh = textures[2];
  10891. texture._lodTextureMid = textures[1];
  10892. texture._lodTextureLow = textures[0];
  10893. if (onLoad) {
  10894. onLoad(texture);
  10895. }
  10896. };
  10897. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10898. };
  10899. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10900. var _this = this;
  10901. if (onLoad === void 0) { onLoad = null; }
  10902. if (onError === void 0) { onError = null; }
  10903. if (forcedExtension === void 0) { forcedExtension = null; }
  10904. var gl = this._gl;
  10905. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10906. texture.isCube = true;
  10907. texture.url = rootUrl;
  10908. texture.generateMipMaps = !noMipmap;
  10909. if (!this._doNotHandleContextLost) {
  10910. texture._extension = forcedExtension;
  10911. texture._files = files;
  10912. }
  10913. var isKTX = false;
  10914. var isDDS = false;
  10915. var lastDot = rootUrl.lastIndexOf('.');
  10916. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  10917. if (this._textureFormatInUse) {
  10918. extension = this._textureFormatInUse;
  10919. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  10920. isKTX = true;
  10921. }
  10922. else {
  10923. isDDS = (extension === ".dds");
  10924. }
  10925. var onerror = function (request, exception) {
  10926. if (onError) {
  10927. onError(request.status + " " + request.statusText, exception);
  10928. }
  10929. };
  10930. if (isKTX) {
  10931. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10932. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10933. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10934. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10935. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10936. ktx.uploadLevels(_this._gl, !noMipmap);
  10937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10938. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10939. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10940. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10941. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10942. _this.resetTextureCache();
  10943. texture.width = ktx.pixelWidth;
  10944. texture.height = ktx.pixelHeight;
  10945. texture.isReady = true;
  10946. }, undefined, undefined, true, onerror);
  10947. }
  10948. else if (isDDS) {
  10949. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10950. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10951. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10952. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10953. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10954. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10955. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10956. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10957. }
  10958. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10959. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10962. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10963. _this.resetTextureCache();
  10964. texture.width = info.width;
  10965. texture.height = info.height;
  10966. texture.isReady = true;
  10967. texture.type = info.textureType;
  10968. if (onLoad) {
  10969. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10970. }
  10971. }, undefined, undefined, true, onerror);
  10972. }
  10973. else {
  10974. if (!files) {
  10975. throw new Error("Cannot load cubemap because files were not defined");
  10976. }
  10977. cascadeLoad(rootUrl, scene, function (imgs) {
  10978. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10979. var height = width;
  10980. _this._prepareWorkingCanvas();
  10981. if (!_this._workingCanvas || !_this._workingContext) {
  10982. return;
  10983. }
  10984. _this._workingCanvas.width = width;
  10985. _this._workingCanvas.height = height;
  10986. var faces = [
  10987. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10988. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10989. ];
  10990. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10991. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10992. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10993. for (var index = 0; index < faces.length; index++) {
  10994. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10995. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10996. }
  10997. if (!noMipmap) {
  10998. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10999. }
  11000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  11002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11004. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11005. _this.resetTextureCache();
  11006. texture.width = width;
  11007. texture.height = height;
  11008. texture.isReady = true;
  11009. if (format) {
  11010. texture.format = format;
  11011. }
  11012. texture.onLoadedObservable.notifyObservers(texture);
  11013. texture.onLoadedObservable.clear();
  11014. if (onLoad) {
  11015. onLoad();
  11016. }
  11017. }, files, onError);
  11018. }
  11019. this._internalTexturesCache.push(texture);
  11020. return texture;
  11021. };
  11022. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11023. if (compression === void 0) { compression = null; }
  11024. if (level === void 0) { level = 0; }
  11025. texture._bufferViewArray = data;
  11026. texture.format = format;
  11027. texture.type = type;
  11028. texture.invertY = invertY;
  11029. texture._compression = compression;
  11030. var gl = this._gl;
  11031. var textureType = this._getWebGLTextureType(type);
  11032. var internalFormat = this._getInternalFormat(format);
  11033. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11034. var needConversion = false;
  11035. if (internalFormat === gl.RGB) {
  11036. internalFormat = gl.RGBA;
  11037. needConversion = true;
  11038. }
  11039. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11040. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11041. if (texture.width % 4 !== 0) {
  11042. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11043. }
  11044. // Data are known to be in +X +Y +Z -X -Y -Z
  11045. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11046. var faceData = data[faceIndex];
  11047. if (compression) {
  11048. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11049. }
  11050. else {
  11051. if (needConversion) {
  11052. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11053. }
  11054. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11055. }
  11056. }
  11057. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11058. if (isPot && texture.generateMipMaps && level === 0) {
  11059. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11060. }
  11061. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11062. this.resetTextureCache();
  11063. texture.isReady = true;
  11064. };
  11065. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11066. if (compression === void 0) { compression = null; }
  11067. var gl = this._gl;
  11068. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11069. texture.isCube = true;
  11070. texture.generateMipMaps = generateMipMaps;
  11071. texture.format = format;
  11072. texture.type = type;
  11073. if (!this._doNotHandleContextLost) {
  11074. texture._bufferViewArray = data;
  11075. }
  11076. var textureType = this._getWebGLTextureType(type);
  11077. var internalFormat = this._getInternalFormat(format);
  11078. var needConversion = false;
  11079. if (internalFormat === gl.RGB) {
  11080. internalFormat = gl.RGBA;
  11081. needConversion = true;
  11082. }
  11083. var width = size;
  11084. var height = width;
  11085. texture.width = width;
  11086. texture.height = height;
  11087. // Double check on POT to generate Mips.
  11088. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11089. if (!isPot) {
  11090. generateMipMaps = false;
  11091. }
  11092. // Upload data if needed. The texture won't be ready until then.
  11093. if (data) {
  11094. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11095. }
  11096. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11097. // Filters
  11098. if (data && generateMipMaps) {
  11099. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11100. }
  11101. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11102. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11104. }
  11105. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11106. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11107. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11108. }
  11109. else {
  11110. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11111. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11113. }
  11114. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11115. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11116. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11117. return texture;
  11118. };
  11119. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11120. var _this = this;
  11121. if (onLoad === void 0) { onLoad = null; }
  11122. if (onError === void 0) { onError = null; }
  11123. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11124. if (invertY === void 0) { invertY = false; }
  11125. var gl = this._gl;
  11126. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11127. scene._addPendingData(texture);
  11128. texture.url = url;
  11129. this._internalTexturesCache.push(texture);
  11130. var onerror = function (request, exception) {
  11131. scene._removePendingData(texture);
  11132. if (onError) {
  11133. onError(request.status + " " + request.statusText, exception);
  11134. }
  11135. };
  11136. var internalCallback = function (data) {
  11137. var width = texture.width;
  11138. var faceDataArrays = callback(data);
  11139. if (!faceDataArrays) {
  11140. return;
  11141. }
  11142. if (mipmmapGenerator) {
  11143. var textureType = _this._getWebGLTextureType(type);
  11144. var internalFormat = _this._getInternalFormat(format);
  11145. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11146. var needConversion = false;
  11147. if (internalFormat === gl.RGB) {
  11148. internalFormat = gl.RGBA;
  11149. needConversion = true;
  11150. }
  11151. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11152. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11153. var mipData = mipmmapGenerator(faceDataArrays);
  11154. for (var level = 0; level < mipData.length; level++) {
  11155. var mipSize = width >> level;
  11156. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11157. var mipFaceData = mipData[level][faceIndex];
  11158. if (needConversion) {
  11159. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11160. }
  11161. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11162. }
  11163. }
  11164. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11165. }
  11166. else {
  11167. texture.generateMipMaps = !noMipmap;
  11168. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11169. }
  11170. texture.isReady = true;
  11171. _this.resetTextureCache();
  11172. scene._removePendingData(texture);
  11173. if (onLoad) {
  11174. onLoad();
  11175. }
  11176. };
  11177. BABYLON.Tools.LoadFile(url, function (data) {
  11178. internalCallback(data);
  11179. }, undefined, scene.database, true, onerror);
  11180. return texture;
  11181. };
  11182. ;
  11183. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11184. if (compression === void 0) { compression = null; }
  11185. var internalFormat = this._getInternalFormat(format);
  11186. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11187. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11188. if (!this._doNotHandleContextLost) {
  11189. texture._bufferView = data;
  11190. texture.format = format;
  11191. texture.invertY = invertY;
  11192. texture._compression = compression;
  11193. }
  11194. if (texture.width % 4 !== 0) {
  11195. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11196. }
  11197. if (compression && data) {
  11198. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11199. }
  11200. else {
  11201. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11202. }
  11203. if (texture.generateMipMaps) {
  11204. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11205. }
  11206. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11207. this.resetTextureCache();
  11208. texture.isReady = true;
  11209. };
  11210. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11211. if (compression === void 0) { compression = null; }
  11212. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11213. texture.baseWidth = width;
  11214. texture.baseHeight = height;
  11215. texture.baseDepth = depth;
  11216. texture.width = width;
  11217. texture.height = height;
  11218. texture.depth = depth;
  11219. texture.format = format;
  11220. texture.generateMipMaps = generateMipMaps;
  11221. texture.samplingMode = samplingMode;
  11222. texture.is3D = true;
  11223. if (!this._doNotHandleContextLost) {
  11224. texture._bufferView = data;
  11225. }
  11226. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11227. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11228. // Filters
  11229. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11230. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11231. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11232. if (generateMipMaps) {
  11233. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11234. }
  11235. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11236. this._internalTexturesCache.push(texture);
  11237. return texture;
  11238. };
  11239. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11240. var gl = this._gl;
  11241. if (!gl) {
  11242. return;
  11243. }
  11244. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11245. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11246. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11247. if (!noMipmap && !isCompressed) {
  11248. gl.generateMipmap(gl.TEXTURE_2D);
  11249. }
  11250. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11251. this.resetTextureCache();
  11252. if (scene) {
  11253. scene._removePendingData(texture);
  11254. }
  11255. texture.onLoadedObservable.notifyObservers(texture);
  11256. texture.onLoadedObservable.clear();
  11257. };
  11258. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11259. var _this = this;
  11260. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11261. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11262. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11263. var gl = this._gl;
  11264. if (!gl) {
  11265. return;
  11266. }
  11267. if (!texture._webGLTexture) {
  11268. this.resetTextureCache();
  11269. if (scene) {
  11270. scene._removePendingData(texture);
  11271. }
  11272. return;
  11273. }
  11274. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11275. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11276. texture.baseWidth = width;
  11277. texture.baseHeight = height;
  11278. texture.width = potWidth;
  11279. texture.height = potHeight;
  11280. texture.isReady = true;
  11281. if (processFunction(potWidth, potHeight, function () {
  11282. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11283. })) {
  11284. // Returning as texture needs extra async steps
  11285. return;
  11286. }
  11287. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11288. };
  11289. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11290. // Create new RGBA data container.
  11291. var rgbaData;
  11292. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11293. rgbaData = new Float32Array(width * height * 4);
  11294. }
  11295. else {
  11296. rgbaData = new Uint32Array(width * height * 4);
  11297. }
  11298. // Convert each pixel.
  11299. for (var x = 0; x < width; x++) {
  11300. for (var y = 0; y < height; y++) {
  11301. var index = (y * width + x) * 3;
  11302. var newIndex = (y * width + x) * 4;
  11303. // Map Old Value to new value.
  11304. rgbaData[newIndex + 0] = rgbData[index + 0];
  11305. rgbaData[newIndex + 1] = rgbData[index + 1];
  11306. rgbaData[newIndex + 2] = rgbData[index + 2];
  11307. // Add fully opaque alpha channel.
  11308. rgbaData[newIndex + 3] = 1;
  11309. }
  11310. }
  11311. return rgbaData;
  11312. };
  11313. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11314. var gl = this._gl;
  11315. if (texture._framebuffer) {
  11316. gl.deleteFramebuffer(texture._framebuffer);
  11317. texture._framebuffer = null;
  11318. }
  11319. if (texture._depthStencilBuffer) {
  11320. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11321. texture._depthStencilBuffer = null;
  11322. }
  11323. if (texture._MSAAFramebuffer) {
  11324. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11325. texture._MSAAFramebuffer = null;
  11326. }
  11327. if (texture._MSAARenderBuffer) {
  11328. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11329. texture._MSAARenderBuffer = null;
  11330. }
  11331. };
  11332. Engine.prototype._releaseTexture = function (texture) {
  11333. var gl = this._gl;
  11334. this._releaseFramebufferObjects(texture);
  11335. gl.deleteTexture(texture._webGLTexture);
  11336. // Unbind channels
  11337. this.unbindAllTextures();
  11338. var index = this._internalTexturesCache.indexOf(texture);
  11339. if (index !== -1) {
  11340. this._internalTexturesCache.splice(index, 1);
  11341. }
  11342. // Integrated fixed lod samplers.
  11343. if (texture._lodTextureHigh) {
  11344. texture._lodTextureHigh.dispose();
  11345. }
  11346. if (texture._lodTextureMid) {
  11347. texture._lodTextureMid.dispose();
  11348. }
  11349. if (texture._lodTextureLow) {
  11350. texture._lodTextureLow.dispose();
  11351. }
  11352. };
  11353. Engine.prototype.setProgram = function (program) {
  11354. if (this._currentProgram !== program) {
  11355. this._gl.useProgram(program);
  11356. this._currentProgram = program;
  11357. }
  11358. };
  11359. Engine.prototype.bindSamplers = function (effect) {
  11360. this.setProgram(effect.getProgram());
  11361. var samplers = effect.getSamplers();
  11362. for (var index = 0; index < samplers.length; index++) {
  11363. var uniform = effect.getUniform(samplers[index]);
  11364. this._gl.uniform1i(uniform, index);
  11365. }
  11366. this._currentEffect = null;
  11367. };
  11368. Engine.prototype.activateTexture = function (texture) {
  11369. if (this._activeTexture !== texture) {
  11370. this._gl.activeTexture(texture);
  11371. this._activeTexture = texture;
  11372. }
  11373. };
  11374. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11375. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  11376. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11377. this._activeTexturesCache[this._activeTexture] = texture;
  11378. }
  11379. };
  11380. Engine.prototype._bindTexture = function (channel, texture) {
  11381. if (channel < 0) {
  11382. return;
  11383. }
  11384. this.activateTexture(this._gl.TEXTURE0 + channel);
  11385. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11386. };
  11387. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11388. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11389. };
  11390. Engine.prototype.unbindAllTextures = function () {
  11391. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11392. this.activateTexture(this._gl["TEXTURE" + channel]);
  11393. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11394. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11395. if (this.webGLVersion > 1) {
  11396. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11397. }
  11398. }
  11399. };
  11400. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11401. if (channel < 0) {
  11402. return;
  11403. }
  11404. this._gl.uniform1i(uniform, channel);
  11405. this._setTexture(channel, texture);
  11406. };
  11407. Engine.prototype._setTexture = function (channel, texture) {
  11408. // Not ready?
  11409. if (!texture) {
  11410. if (this._activeTexturesCache[channel] != null) {
  11411. this.activateTexture(this._gl["TEXTURE" + channel]);
  11412. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11413. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11414. if (this.webGLVersion > 1) {
  11415. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11416. }
  11417. }
  11418. return;
  11419. }
  11420. // Video
  11421. var alreadyActivated = false;
  11422. if (texture.video) {
  11423. this.activateTexture(this._gl["TEXTURE" + channel]);
  11424. alreadyActivated = true;
  11425. texture.update();
  11426. }
  11427. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11428. texture.delayLoad();
  11429. return;
  11430. }
  11431. var internalTexture;
  11432. if (texture.isReady()) {
  11433. internalTexture = texture.getInternalTexture();
  11434. }
  11435. else if (texture.isCube) {
  11436. internalTexture = this.emptyCubeTexture;
  11437. }
  11438. else if (texture.is3D) {
  11439. internalTexture = this.emptyTexture3D;
  11440. }
  11441. else {
  11442. internalTexture = this.emptyTexture;
  11443. }
  11444. if (this._activeTexturesCache[channel] === internalTexture) {
  11445. return;
  11446. }
  11447. if (!alreadyActivated) {
  11448. this.activateTexture(this._gl["TEXTURE" + channel]);
  11449. }
  11450. if (internalTexture && internalTexture.is3D) {
  11451. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11452. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11453. internalTexture._cachedWrapU = texture.wrapU;
  11454. switch (texture.wrapU) {
  11455. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11456. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11457. break;
  11458. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11459. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11460. break;
  11461. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11462. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11463. break;
  11464. }
  11465. }
  11466. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11467. internalTexture._cachedWrapV = texture.wrapV;
  11468. switch (texture.wrapV) {
  11469. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11470. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11471. break;
  11472. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11473. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11474. break;
  11475. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11476. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11477. break;
  11478. }
  11479. }
  11480. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11481. internalTexture._cachedWrapR = texture.wrapR;
  11482. switch (texture.wrapV) {
  11483. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11484. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11485. break;
  11486. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11487. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11488. break;
  11489. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11490. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11491. break;
  11492. }
  11493. }
  11494. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11495. }
  11496. else if (internalTexture && internalTexture.isCube) {
  11497. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11498. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11499. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11500. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11501. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11502. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11503. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11504. }
  11505. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11506. }
  11507. else {
  11508. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11509. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11510. internalTexture._cachedWrapU = texture.wrapU;
  11511. switch (texture.wrapU) {
  11512. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11513. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11514. break;
  11515. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11516. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11517. break;
  11518. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11519. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11520. break;
  11521. }
  11522. }
  11523. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11524. internalTexture._cachedWrapV = texture.wrapV;
  11525. switch (texture.wrapV) {
  11526. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11527. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11528. break;
  11529. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11530. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11531. break;
  11532. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11533. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11534. break;
  11535. }
  11536. }
  11537. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11538. }
  11539. };
  11540. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11541. if (channel < 0 || !uniform) {
  11542. return;
  11543. }
  11544. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11545. this._textureUnits = new Int32Array(textures.length);
  11546. }
  11547. for (var i = 0; i < textures.length; i++) {
  11548. this._textureUnits[i] = channel + i;
  11549. }
  11550. this._gl.uniform1iv(uniform, this._textureUnits);
  11551. for (var index = 0; index < textures.length; index++) {
  11552. this._setTexture(channel + index, textures[index]);
  11553. }
  11554. };
  11555. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11556. var internalTexture = texture.getInternalTexture();
  11557. if (!internalTexture) {
  11558. return;
  11559. }
  11560. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11561. var value = texture.anisotropicFilteringLevel;
  11562. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11563. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11564. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11565. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11566. }
  11567. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11568. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11569. internalTexture._cachedAnisotropicFilteringLevel = value;
  11570. }
  11571. };
  11572. Engine.prototype.readPixels = function (x, y, width, height) {
  11573. var data = new Uint8Array(height * width * 4);
  11574. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11575. return data;
  11576. };
  11577. /**
  11578. * Add an externaly attached data from its key.
  11579. * This method call will fail and return false, if such key already exists.
  11580. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11581. * @param key the unique key that identifies the data
  11582. * @param data the data object to associate to the key for this Engine instance
  11583. * @return true if no such key were already present and the data was added successfully, false otherwise
  11584. */
  11585. Engine.prototype.addExternalData = function (key, data) {
  11586. if (!this._externalData) {
  11587. this._externalData = new BABYLON.StringDictionary();
  11588. }
  11589. return this._externalData.add(key, data);
  11590. };
  11591. /**
  11592. * Get an externaly attached data from its key
  11593. * @param key the unique key that identifies the data
  11594. * @return the associated data, if present (can be null), or undefined if not present
  11595. */
  11596. Engine.prototype.getExternalData = function (key) {
  11597. if (!this._externalData) {
  11598. this._externalData = new BABYLON.StringDictionary();
  11599. }
  11600. return this._externalData.get(key);
  11601. };
  11602. /**
  11603. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11604. * @param key the unique key that identifies the data
  11605. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11606. * @return the associated data, can be null if the factory returned null.
  11607. */
  11608. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11609. if (!this._externalData) {
  11610. this._externalData = new BABYLON.StringDictionary();
  11611. }
  11612. return this._externalData.getOrAddWithFactory(key, factory);
  11613. };
  11614. /**
  11615. * Remove an externaly attached data from the Engine instance
  11616. * @param key the unique key that identifies the data
  11617. * @return true if the data was successfully removed, false if it doesn't exist
  11618. */
  11619. Engine.prototype.removeExternalData = function (key) {
  11620. if (!this._externalData) {
  11621. this._externalData = new BABYLON.StringDictionary();
  11622. }
  11623. return this._externalData.remove(key);
  11624. };
  11625. Engine.prototype.unbindAllAttributes = function () {
  11626. if (this._mustWipeVertexAttributes) {
  11627. this._mustWipeVertexAttributes = false;
  11628. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11629. this._gl.disableVertexAttribArray(i);
  11630. this._vertexAttribArraysEnabled[i] = false;
  11631. this._currentBufferPointers[i].active = false;
  11632. }
  11633. return;
  11634. }
  11635. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11636. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11637. continue;
  11638. }
  11639. this._gl.disableVertexAttribArray(i);
  11640. this._vertexAttribArraysEnabled[i] = false;
  11641. this._currentBufferPointers[i].active = false;
  11642. }
  11643. };
  11644. Engine.prototype.releaseEffects = function () {
  11645. for (var name in this._compiledEffects) {
  11646. this._deleteProgram(this._compiledEffects[name]._program);
  11647. }
  11648. this._compiledEffects = {};
  11649. };
  11650. // Dispose
  11651. Engine.prototype.dispose = function () {
  11652. this.hideLoadingUI();
  11653. this.stopRenderLoop();
  11654. // Release postProcesses
  11655. while (this.postProcesses.length) {
  11656. this.postProcesses[0].dispose();
  11657. }
  11658. // Empty texture
  11659. if (this._emptyTexture) {
  11660. this._releaseTexture(this._emptyTexture);
  11661. this._emptyTexture = null;
  11662. }
  11663. if (this._emptyCubeTexture) {
  11664. this._releaseTexture(this._emptyCubeTexture);
  11665. this._emptyCubeTexture = null;
  11666. }
  11667. // Rescale PP
  11668. if (this._rescalePostProcess) {
  11669. this._rescalePostProcess.dispose();
  11670. }
  11671. // Release scenes
  11672. while (this.scenes.length) {
  11673. this.scenes[0].dispose();
  11674. }
  11675. // Release audio engine
  11676. if (Engine.audioEngine) {
  11677. Engine.audioEngine.dispose();
  11678. }
  11679. // Release effects
  11680. this.releaseEffects();
  11681. // Unbind
  11682. this.unbindAllAttributes();
  11683. if (this._dummyFramebuffer) {
  11684. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11685. }
  11686. //WebVR
  11687. this.disableVR();
  11688. // Events
  11689. window.removeEventListener("blur", this._onBlur);
  11690. window.removeEventListener("focus", this._onFocus);
  11691. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11692. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11693. if (this._renderingCanvas) {
  11694. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11695. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11696. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11697. if (!this._doNotHandleContextLost) {
  11698. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11699. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11700. }
  11701. }
  11702. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11703. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11704. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11705. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11706. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11707. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11708. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11709. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11710. if (this._onVrDisplayConnect) {
  11711. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11712. if (this._onVrDisplayDisconnect) {
  11713. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11714. }
  11715. if (this._onVrDisplayPresentChange) {
  11716. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11717. }
  11718. this._onVrDisplayConnect = null;
  11719. this._onVrDisplayDisconnect = null;
  11720. }
  11721. // Remove from Instances
  11722. var index = Engine.Instances.indexOf(this);
  11723. if (index >= 0) {
  11724. Engine.Instances.splice(index, 1);
  11725. }
  11726. this._workingCanvas = null;
  11727. this._workingContext = null;
  11728. this._currentBufferPointers = [];
  11729. this._renderingCanvas = null;
  11730. this._currentProgram = null;
  11731. this.onResizeObservable.clear();
  11732. this.onCanvasBlurObservable.clear();
  11733. this.onCanvasFocusObservable.clear();
  11734. this.onCanvasPointerOutObservable.clear();
  11735. this.onBeginFrameObservable.clear();
  11736. this.onEndFrameObservable.clear();
  11737. BABYLON.Effect.ResetCache();
  11738. };
  11739. // Loading screen
  11740. Engine.prototype.displayLoadingUI = function () {
  11741. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11742. return;
  11743. }
  11744. var loadingScreen = this.loadingScreen;
  11745. if (loadingScreen) {
  11746. loadingScreen.displayLoadingUI();
  11747. }
  11748. };
  11749. Engine.prototype.hideLoadingUI = function () {
  11750. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11751. return;
  11752. }
  11753. var loadingScreen = this.loadingScreen;
  11754. if (loadingScreen) {
  11755. loadingScreen.hideLoadingUI();
  11756. }
  11757. };
  11758. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11759. get: function () {
  11760. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11761. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11762. return this._loadingScreen;
  11763. },
  11764. set: function (loadingScreen) {
  11765. this._loadingScreen = loadingScreen;
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11771. set: function (text) {
  11772. this.loadingScreen.loadingUIText = text;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11778. set: function (color) {
  11779. this.loadingScreen.loadingUIBackgroundColor = color;
  11780. },
  11781. enumerable: true,
  11782. configurable: true
  11783. });
  11784. Engine.prototype.attachContextLostEvent = function (callback) {
  11785. if (this._renderingCanvas) {
  11786. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11787. }
  11788. };
  11789. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11790. if (this._renderingCanvas) {
  11791. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11792. }
  11793. };
  11794. Engine.prototype.getVertexShaderSource = function (program) {
  11795. var shaders = this._gl.getAttachedShaders(program);
  11796. if (!shaders) {
  11797. return null;
  11798. }
  11799. return this._gl.getShaderSource(shaders[0]);
  11800. };
  11801. Engine.prototype.getFragmentShaderSource = function (program) {
  11802. var shaders = this._gl.getAttachedShaders(program);
  11803. if (!shaders) {
  11804. return null;
  11805. }
  11806. return this._gl.getShaderSource(shaders[1]);
  11807. };
  11808. Engine.prototype.getError = function () {
  11809. return this._gl.getError();
  11810. };
  11811. // FPS
  11812. Engine.prototype.getFps = function () {
  11813. return this._fps;
  11814. };
  11815. Engine.prototype.getDeltaTime = function () {
  11816. return this._deltaTime;
  11817. };
  11818. Engine.prototype._measureFps = function () {
  11819. this._performanceMonitor.sampleFrame();
  11820. this._fps = this._performanceMonitor.averageFPS;
  11821. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11822. };
  11823. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11824. if (faceIndex === void 0) { faceIndex = -1; }
  11825. var gl = this._gl;
  11826. if (!this._dummyFramebuffer) {
  11827. var dummy = gl.createFramebuffer();
  11828. if (!dummy) {
  11829. throw new Error("Unable to create dummy framebuffer");
  11830. }
  11831. this._dummyFramebuffer = dummy;
  11832. }
  11833. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11834. if (faceIndex > -1) {
  11835. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11836. }
  11837. else {
  11838. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11839. }
  11840. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11841. var buffer;
  11842. switch (readType) {
  11843. case gl.UNSIGNED_BYTE:
  11844. buffer = new Uint8Array(4 * width * height);
  11845. readType = gl.UNSIGNED_BYTE;
  11846. break;
  11847. default:
  11848. buffer = new Float32Array(4 * width * height);
  11849. readType = gl.FLOAT;
  11850. break;
  11851. }
  11852. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11853. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11854. return buffer;
  11855. };
  11856. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11857. if (this._webGLVersion > 1) {
  11858. return this._caps.colorBufferFloat;
  11859. }
  11860. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11861. };
  11862. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11863. if (this._webGLVersion > 1) {
  11864. return this._caps.colorBufferFloat;
  11865. }
  11866. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11867. };
  11868. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11869. Engine.prototype._canRenderToFramebuffer = function (type) {
  11870. var gl = this._gl;
  11871. //clear existing errors
  11872. while (gl.getError() !== gl.NO_ERROR) { }
  11873. var successful = true;
  11874. var texture = gl.createTexture();
  11875. gl.bindTexture(gl.TEXTURE_2D, texture);
  11876. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11877. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11878. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11879. var fb = gl.createFramebuffer();
  11880. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11881. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11882. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11883. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11884. successful = successful && (gl.getError() === gl.NO_ERROR);
  11885. //try render by clearing frame buffer's color buffer
  11886. if (successful) {
  11887. gl.clear(gl.COLOR_BUFFER_BIT);
  11888. successful = successful && (gl.getError() === gl.NO_ERROR);
  11889. }
  11890. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11891. if (successful) {
  11892. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11893. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11894. var readFormat = gl.RGBA;
  11895. var readType = gl.UNSIGNED_BYTE;
  11896. var buffer = new Uint8Array(4);
  11897. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11898. successful = successful && (gl.getError() === gl.NO_ERROR);
  11899. }
  11900. //clean up
  11901. gl.deleteTexture(texture);
  11902. gl.deleteFramebuffer(fb);
  11903. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11904. //clear accumulated errors
  11905. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11906. return successful;
  11907. };
  11908. Engine.prototype._getWebGLTextureType = function (type) {
  11909. if (type === Engine.TEXTURETYPE_FLOAT) {
  11910. return this._gl.FLOAT;
  11911. }
  11912. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11913. // Add Half Float Constant.
  11914. return this._gl.HALF_FLOAT_OES;
  11915. }
  11916. return this._gl.UNSIGNED_BYTE;
  11917. };
  11918. ;
  11919. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11920. if (this._webGLVersion === 1) {
  11921. return this._gl.RGBA;
  11922. }
  11923. if (type === Engine.TEXTURETYPE_FLOAT) {
  11924. return this._gl.RGBA32F;
  11925. }
  11926. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11927. return this._gl.RGBA16F;
  11928. }
  11929. return this._gl.RGBA;
  11930. };
  11931. ;
  11932. Engine.prototype.createQuery = function () {
  11933. return this._gl.createQuery();
  11934. };
  11935. Engine.prototype.deleteQuery = function (query) {
  11936. this._gl.deleteQuery(query);
  11937. return this;
  11938. };
  11939. Engine.prototype.isQueryResultAvailable = function (query) {
  11940. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11941. };
  11942. Engine.prototype.getQueryResult = function (query) {
  11943. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11944. };
  11945. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  11946. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11947. this._gl.beginQuery(glAlgorithm, query);
  11948. return this;
  11949. };
  11950. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  11951. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11952. this._gl.endQuery(glAlgorithm);
  11953. return this;
  11954. };
  11955. /* Time queries */
  11956. Engine.prototype._createTimeQuery = function () {
  11957. var timerQuery = this._caps.timerQuery;
  11958. if (timerQuery.createQueryEXT) {
  11959. return timerQuery.createQueryEXT();
  11960. }
  11961. return this.createQuery();
  11962. };
  11963. Engine.prototype._deleteTimeQuery = function (query) {
  11964. var timerQuery = this._caps.timerQuery;
  11965. if (timerQuery.deleteQueryEXT) {
  11966. timerQuery.deleteQueryEXT(query);
  11967. return;
  11968. }
  11969. this.deleteQuery(query);
  11970. };
  11971. Engine.prototype._getTimeQueryResult = function (query) {
  11972. var timerQuery = this._caps.timerQuery;
  11973. if (timerQuery.getQueryObjectEXT) {
  11974. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  11975. }
  11976. return this.getQueryResult(query);
  11977. };
  11978. Engine.prototype._getTimeQueryAvailability = function (query) {
  11979. var timerQuery = this._caps.timerQuery;
  11980. if (timerQuery.getQueryObjectEXT) {
  11981. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  11982. }
  11983. return this.isQueryResultAvailable(query);
  11984. };
  11985. Engine.prototype.startTimeQuery = function () {
  11986. var timerQuery = this._caps.timerQuery;
  11987. if (!timerQuery) {
  11988. return null;
  11989. }
  11990. var token = new BABYLON._TimeToken();
  11991. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  11992. if (this._caps.canUseTimestampForTimerQuery) {
  11993. token._startTimeQuery = this._createTimeQuery();
  11994. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  11995. }
  11996. else {
  11997. if (this._currentNonTimestampToken) {
  11998. return this._currentNonTimestampToken;
  11999. }
  12000. token._timeElapsedQuery = this._createTimeQuery();
  12001. if (timerQuery.beginQueryEXT) {
  12002. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12003. }
  12004. else {
  12005. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12006. }
  12007. this._currentNonTimestampToken = token;
  12008. }
  12009. return token;
  12010. };
  12011. Engine.prototype.endTimeQuery = function (token) {
  12012. var timerQuery = this._caps.timerQuery;
  12013. if (!timerQuery || !token) {
  12014. return -1;
  12015. }
  12016. if (this._caps.canUseTimestampForTimerQuery) {
  12017. if (!token._startTimeQuery) {
  12018. return -1;
  12019. }
  12020. if (!token._endTimeQuery) {
  12021. token._endTimeQuery = this._createTimeQuery();
  12022. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12023. }
  12024. }
  12025. else if (!token._timeElapsedQueryEnded) {
  12026. if (!token._timeElapsedQuery) {
  12027. return -1;
  12028. }
  12029. if (timerQuery.endQueryEXT) {
  12030. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12031. }
  12032. else {
  12033. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12034. }
  12035. token._timeElapsedQueryEnded = true;
  12036. }
  12037. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12038. var available = false;
  12039. if (token._endTimeQuery) {
  12040. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12041. }
  12042. else if (token._timeElapsedQuery) {
  12043. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12044. }
  12045. if (available && !disjoint) {
  12046. var result = 0;
  12047. if (this._caps.canUseTimestampForTimerQuery) {
  12048. if (!token._startTimeQuery || !token._endTimeQuery) {
  12049. return -1;
  12050. }
  12051. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12052. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12053. result = timeEnd - timeStart;
  12054. this._deleteTimeQuery(token._startTimeQuery);
  12055. this._deleteTimeQuery(token._endTimeQuery);
  12056. token._startTimeQuery = null;
  12057. token._endTimeQuery = null;
  12058. }
  12059. else {
  12060. if (!token._timeElapsedQuery) {
  12061. return -1;
  12062. }
  12063. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12064. this._deleteTimeQuery(token._timeElapsedQuery);
  12065. token._timeElapsedQuery = null;
  12066. token._timeElapsedQueryEnded = false;
  12067. this._currentNonTimestampToken = null;
  12068. }
  12069. return result;
  12070. }
  12071. return -1;
  12072. };
  12073. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12074. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12075. };
  12076. // Transform feedback
  12077. Engine.prototype.createTransformFeedback = function () {
  12078. return this._gl.createTransformFeedback();
  12079. };
  12080. Engine.prototype.deleteTransformFeedback = function (value) {
  12081. this._gl.deleteTransformFeedback(value);
  12082. };
  12083. Engine.prototype.bindTransformFeedback = function (value) {
  12084. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12085. };
  12086. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12087. if (usePoints === void 0) { usePoints = true; }
  12088. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12089. };
  12090. Engine.prototype.endTransformFeedback = function () {
  12091. this._gl.endTransformFeedback();
  12092. };
  12093. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12094. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12095. };
  12096. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12097. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12098. };
  12099. // Statics
  12100. Engine.isSupported = function () {
  12101. try {
  12102. var tempcanvas = document.createElement("canvas");
  12103. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12104. return gl != null && !!window.WebGLRenderingContext;
  12105. }
  12106. catch (e) {
  12107. return false;
  12108. }
  12109. };
  12110. Engine.Instances = new Array();
  12111. // Const statics
  12112. Engine._ALPHA_DISABLE = 0;
  12113. Engine._ALPHA_ADD = 1;
  12114. Engine._ALPHA_COMBINE = 2;
  12115. Engine._ALPHA_SUBTRACT = 3;
  12116. Engine._ALPHA_MULTIPLY = 4;
  12117. Engine._ALPHA_MAXIMIZED = 5;
  12118. Engine._ALPHA_ONEONE = 6;
  12119. Engine._ALPHA_PREMULTIPLIED = 7;
  12120. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12121. Engine._ALPHA_INTERPOLATE = 9;
  12122. Engine._ALPHA_SCREENMODE = 10;
  12123. Engine._DELAYLOADSTATE_NONE = 0;
  12124. Engine._DELAYLOADSTATE_LOADED = 1;
  12125. Engine._DELAYLOADSTATE_LOADING = 2;
  12126. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12127. Engine._TEXTUREFORMAT_ALPHA = 0;
  12128. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12129. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12130. Engine._TEXTUREFORMAT_RGB = 4;
  12131. Engine._TEXTUREFORMAT_RGBA = 5;
  12132. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12133. Engine._TEXTURETYPE_FLOAT = 1;
  12134. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12135. // Depht or Stencil test Constants.
  12136. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12137. 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.
  12138. 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.
  12139. 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.
  12140. 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.
  12141. 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.
  12142. 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.
  12143. 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.
  12144. // Stencil Actions Constants.
  12145. Engine._KEEP = 0x1E00;
  12146. Engine._REPLACE = 0x1E01;
  12147. Engine._INCR = 0x1E02;
  12148. Engine._DECR = 0x1E03;
  12149. Engine._INVERT = 0x150A;
  12150. Engine._INCR_WRAP = 0x8507;
  12151. Engine._DECR_WRAP = 0x8508;
  12152. // Texture rescaling mode
  12153. Engine._SCALEMODE_FLOOR = 1;
  12154. Engine._SCALEMODE_NEAREST = 2;
  12155. Engine._SCALEMODE_CEILING = 3;
  12156. // Updatable statics so stick with vars here
  12157. Engine.CollisionsEpsilon = 0.001;
  12158. Engine.CodeRepository = "src/";
  12159. Engine.ShadersRepository = "src/Shaders/";
  12160. return Engine;
  12161. }());
  12162. BABYLON.Engine = Engine;
  12163. })(BABYLON || (BABYLON = {}));
  12164. //# sourceMappingURL=babylon.engine.js.map
  12165. var BABYLON;
  12166. (function (BABYLON) {
  12167. /**
  12168. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12169. */
  12170. var Node = /** @class */ (function () {
  12171. /**
  12172. * @constructor
  12173. * @param {string} name - the name and id to be given to this node
  12174. * @param {BABYLON.Scene} the scene this node will be added to
  12175. */
  12176. function Node(name, scene) {
  12177. if (scene === void 0) { scene = null; }
  12178. this.state = "";
  12179. this.metadata = null;
  12180. this.doNotSerialize = false;
  12181. this.animations = new Array();
  12182. this._ranges = {};
  12183. this._isEnabled = true;
  12184. this._isReady = true;
  12185. this._currentRenderId = -1;
  12186. this._parentRenderId = -1;
  12187. /**
  12188. * An event triggered when the mesh is disposed.
  12189. * @type {BABYLON.Observable}
  12190. */
  12191. this.onDisposeObservable = new BABYLON.Observable();
  12192. // Behaviors
  12193. this._behaviors = new Array();
  12194. this.name = name;
  12195. this.id = name;
  12196. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12197. this.uniqueId = this._scene.getUniqueId();
  12198. this._initCache();
  12199. }
  12200. Object.defineProperty(Node.prototype, "parent", {
  12201. get: function () {
  12202. return this._parentNode;
  12203. },
  12204. set: function (parent) {
  12205. if (this._parentNode === parent) {
  12206. return;
  12207. }
  12208. if (this._parentNode) {
  12209. var index = this._parentNode._children.indexOf(this);
  12210. if (index !== -1) {
  12211. this._parentNode._children.splice(index, 1);
  12212. }
  12213. }
  12214. this._parentNode = parent;
  12215. if (this._parentNode) {
  12216. if (!this._parentNode._children) {
  12217. this._parentNode._children = new Array();
  12218. }
  12219. this._parentNode._children.push(this);
  12220. }
  12221. },
  12222. enumerable: true,
  12223. configurable: true
  12224. });
  12225. Node.prototype.getClassName = function () {
  12226. return "Node";
  12227. };
  12228. Object.defineProperty(Node.prototype, "onDispose", {
  12229. set: function (callback) {
  12230. if (this._onDisposeObserver) {
  12231. this.onDisposeObservable.remove(this._onDisposeObserver);
  12232. }
  12233. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12234. },
  12235. enumerable: true,
  12236. configurable: true
  12237. });
  12238. Node.prototype.getScene = function () {
  12239. return this._scene;
  12240. };
  12241. Node.prototype.getEngine = function () {
  12242. return this._scene.getEngine();
  12243. };
  12244. Node.prototype.addBehavior = function (behavior) {
  12245. var index = this._behaviors.indexOf(behavior);
  12246. if (index !== -1) {
  12247. return this;
  12248. }
  12249. behavior.attach(this);
  12250. this._behaviors.push(behavior);
  12251. return this;
  12252. };
  12253. Node.prototype.removeBehavior = function (behavior) {
  12254. var index = this._behaviors.indexOf(behavior);
  12255. if (index === -1) {
  12256. return this;
  12257. }
  12258. this._behaviors[index].detach();
  12259. this._behaviors.splice(index, 1);
  12260. return this;
  12261. };
  12262. Object.defineProperty(Node.prototype, "behaviors", {
  12263. get: function () {
  12264. return this._behaviors;
  12265. },
  12266. enumerable: true,
  12267. configurable: true
  12268. });
  12269. Node.prototype.getBehaviorByName = function (name) {
  12270. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12271. var behavior = _a[_i];
  12272. if (behavior.name === name) {
  12273. return behavior;
  12274. }
  12275. }
  12276. return null;
  12277. };
  12278. // override it in derived class
  12279. Node.prototype.getWorldMatrix = function () {
  12280. return BABYLON.Matrix.Identity();
  12281. };
  12282. // override it in derived class if you add new variables to the cache
  12283. // and call the parent class method
  12284. Node.prototype._initCache = function () {
  12285. this._cache = {};
  12286. this._cache.parent = undefined;
  12287. };
  12288. Node.prototype.updateCache = function (force) {
  12289. if (!force && this.isSynchronized())
  12290. return;
  12291. this._cache.parent = this.parent;
  12292. this._updateCache();
  12293. };
  12294. // override it in derived class if you add new variables to the cache
  12295. // and call the parent class method if !ignoreParentClass
  12296. Node.prototype._updateCache = function (ignoreParentClass) {
  12297. };
  12298. // override it in derived class if you add new variables to the cache
  12299. Node.prototype._isSynchronized = function () {
  12300. return true;
  12301. };
  12302. Node.prototype._markSyncedWithParent = function () {
  12303. if (this.parent) {
  12304. this._parentRenderId = this.parent._currentRenderId;
  12305. }
  12306. };
  12307. Node.prototype.isSynchronizedWithParent = function () {
  12308. if (!this.parent) {
  12309. return true;
  12310. }
  12311. if (this._parentRenderId !== this.parent._currentRenderId) {
  12312. return false;
  12313. }
  12314. return this.parent.isSynchronized();
  12315. };
  12316. Node.prototype.isSynchronized = function (updateCache) {
  12317. var check = this.hasNewParent();
  12318. check = check || !this.isSynchronizedWithParent();
  12319. check = check || !this._isSynchronized();
  12320. if (updateCache)
  12321. this.updateCache(true);
  12322. return !check;
  12323. };
  12324. Node.prototype.hasNewParent = function (update) {
  12325. if (this._cache.parent === this.parent)
  12326. return false;
  12327. if (update)
  12328. this._cache.parent = this.parent;
  12329. return true;
  12330. };
  12331. /**
  12332. * Is this node ready to be used/rendered
  12333. * @return {boolean} is it ready
  12334. */
  12335. Node.prototype.isReady = function () {
  12336. return this._isReady;
  12337. };
  12338. /**
  12339. * Is this node enabled.
  12340. * If the node has a parent and is enabled, the parent will be inspected as well.
  12341. * @return {boolean} whether this node (and its parent) is enabled.
  12342. * @see setEnabled
  12343. */
  12344. Node.prototype.isEnabled = function () {
  12345. if (!this._isEnabled) {
  12346. return false;
  12347. }
  12348. if (this.parent) {
  12349. return this.parent.isEnabled();
  12350. }
  12351. return true;
  12352. };
  12353. /**
  12354. * Set the enabled state of this node.
  12355. * @param {boolean} value - the new enabled state
  12356. * @see isEnabled
  12357. */
  12358. Node.prototype.setEnabled = function (value) {
  12359. this._isEnabled = value;
  12360. };
  12361. /**
  12362. * Is this node a descendant of the given node.
  12363. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12364. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12365. * @see parent
  12366. */
  12367. Node.prototype.isDescendantOf = function (ancestor) {
  12368. if (this.parent) {
  12369. if (this.parent === ancestor) {
  12370. return true;
  12371. }
  12372. return this.parent.isDescendantOf(ancestor);
  12373. }
  12374. return false;
  12375. };
  12376. /**
  12377. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12378. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12379. * @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.
  12380. * @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.
  12381. */
  12382. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12383. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12384. if (!this._children) {
  12385. return;
  12386. }
  12387. for (var index = 0; index < this._children.length; index++) {
  12388. var item = this._children[index];
  12389. if (!predicate || predicate(item)) {
  12390. results.push(item);
  12391. }
  12392. if (!directDescendantsOnly) {
  12393. item._getDescendants(results, false, predicate);
  12394. }
  12395. }
  12396. };
  12397. /**
  12398. * Will return all nodes that have this node as ascendant.
  12399. * @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.
  12400. * @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.
  12401. * @return {BABYLON.Node[]} all children nodes of all types.
  12402. */
  12403. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12404. var results = new Array();
  12405. this._getDescendants(results, directDescendantsOnly, predicate);
  12406. return results;
  12407. };
  12408. /**
  12409. * Get all child-meshes of this node.
  12410. */
  12411. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12412. var results = [];
  12413. this._getDescendants(results, directDecendantsOnly, function (node) {
  12414. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12415. });
  12416. return results;
  12417. };
  12418. /**
  12419. * Get all direct children of this node.
  12420. */
  12421. Node.prototype.getChildren = function (predicate) {
  12422. return this.getDescendants(true, predicate);
  12423. };
  12424. Node.prototype._setReady = function (state) {
  12425. if (state === this._isReady) {
  12426. return;
  12427. }
  12428. if (!state) {
  12429. this._isReady = false;
  12430. return;
  12431. }
  12432. this._isReady = true;
  12433. if (this.onReady) {
  12434. this.onReady(this);
  12435. }
  12436. };
  12437. Node.prototype.getAnimationByName = function (name) {
  12438. for (var i = 0; i < this.animations.length; i++) {
  12439. var animation = this.animations[i];
  12440. if (animation.name === name) {
  12441. return animation;
  12442. }
  12443. }
  12444. return null;
  12445. };
  12446. Node.prototype.createAnimationRange = function (name, from, to) {
  12447. // check name not already in use
  12448. if (!this._ranges[name]) {
  12449. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12450. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12451. if (this.animations[i]) {
  12452. this.animations[i].createRange(name, from, to);
  12453. }
  12454. }
  12455. }
  12456. };
  12457. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12458. if (deleteFrames === void 0) { deleteFrames = true; }
  12459. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12460. if (this.animations[i]) {
  12461. this.animations[i].deleteRange(name, deleteFrames);
  12462. }
  12463. }
  12464. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12465. };
  12466. Node.prototype.getAnimationRange = function (name) {
  12467. return this._ranges[name];
  12468. };
  12469. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12470. var range = this.getAnimationRange(name);
  12471. if (!range) {
  12472. return;
  12473. }
  12474. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12475. };
  12476. Node.prototype.serializeAnimationRanges = function () {
  12477. var serializationRanges = [];
  12478. for (var name in this._ranges) {
  12479. var localRange = this._ranges[name];
  12480. if (!localRange) {
  12481. continue;
  12482. }
  12483. var range = {};
  12484. range.name = name;
  12485. range.from = localRange.from;
  12486. range.to = localRange.to;
  12487. serializationRanges.push(range);
  12488. }
  12489. return serializationRanges;
  12490. };
  12491. Node.prototype.dispose = function () {
  12492. this.parent = null;
  12493. // Callback
  12494. this.onDisposeObservable.notifyObservers(this);
  12495. this.onDisposeObservable.clear();
  12496. // Behaviors
  12497. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12498. var behavior = _a[_i];
  12499. behavior.detach();
  12500. }
  12501. this._behaviors = [];
  12502. };
  12503. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12504. if (parsedNode.ranges) {
  12505. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12506. var data = parsedNode.ranges[index];
  12507. node.createAnimationRange(data.name, data.from, data.to);
  12508. }
  12509. }
  12510. };
  12511. __decorate([
  12512. BABYLON.serialize()
  12513. ], Node.prototype, "name", void 0);
  12514. __decorate([
  12515. BABYLON.serialize()
  12516. ], Node.prototype, "id", void 0);
  12517. __decorate([
  12518. BABYLON.serialize()
  12519. ], Node.prototype, "uniqueId", void 0);
  12520. __decorate([
  12521. BABYLON.serialize()
  12522. ], Node.prototype, "state", void 0);
  12523. __decorate([
  12524. BABYLON.serialize()
  12525. ], Node.prototype, "metadata", void 0);
  12526. return Node;
  12527. }());
  12528. BABYLON.Node = Node;
  12529. })(BABYLON || (BABYLON = {}));
  12530. //# sourceMappingURL=babylon.node.js.map
  12531. var BABYLON;
  12532. (function (BABYLON) {
  12533. var BoundingSphere = /** @class */ (function () {
  12534. function BoundingSphere(minimum, maximum) {
  12535. this.minimum = minimum;
  12536. this.maximum = maximum;
  12537. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12538. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12539. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12540. this.radius = distance * 0.5;
  12541. this.centerWorld = BABYLON.Vector3.Zero();
  12542. this._update(BABYLON.Matrix.Identity());
  12543. }
  12544. // Methods
  12545. BoundingSphere.prototype._update = function (world) {
  12546. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12547. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12548. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12549. };
  12550. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12551. for (var i = 0; i < 6; i++) {
  12552. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12553. return false;
  12554. }
  12555. return true;
  12556. };
  12557. BoundingSphere.prototype.intersectsPoint = function (point) {
  12558. var x = this.centerWorld.x - point.x;
  12559. var y = this.centerWorld.y - point.y;
  12560. var z = this.centerWorld.z - point.z;
  12561. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12562. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12563. return false;
  12564. return true;
  12565. };
  12566. // Statics
  12567. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12568. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12569. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12570. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12571. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12572. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12573. return false;
  12574. return true;
  12575. };
  12576. return BoundingSphere;
  12577. }());
  12578. BABYLON.BoundingSphere = BoundingSphere;
  12579. })(BABYLON || (BABYLON = {}));
  12580. //# sourceMappingURL=babylon.boundingSphere.js.map
  12581. var BABYLON;
  12582. (function (BABYLON) {
  12583. var BoundingBox = /** @class */ (function () {
  12584. function BoundingBox(minimum, maximum) {
  12585. this.minimum = minimum;
  12586. this.maximum = maximum;
  12587. this.vectors = new Array();
  12588. this.vectorsWorld = new Array();
  12589. // Bounding vectors
  12590. this.vectors.push(this.minimum.clone());
  12591. this.vectors.push(this.maximum.clone());
  12592. this.vectors.push(this.minimum.clone());
  12593. this.vectors[2].x = this.maximum.x;
  12594. this.vectors.push(this.minimum.clone());
  12595. this.vectors[3].y = this.maximum.y;
  12596. this.vectors.push(this.minimum.clone());
  12597. this.vectors[4].z = this.maximum.z;
  12598. this.vectors.push(this.maximum.clone());
  12599. this.vectors[5].z = this.minimum.z;
  12600. this.vectors.push(this.maximum.clone());
  12601. this.vectors[6].x = this.minimum.x;
  12602. this.vectors.push(this.maximum.clone());
  12603. this.vectors[7].y = this.minimum.y;
  12604. // OBB
  12605. this.center = this.maximum.add(this.minimum).scale(0.5);
  12606. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12607. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12608. // World
  12609. for (var index = 0; index < this.vectors.length; index++) {
  12610. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12611. }
  12612. this.minimumWorld = BABYLON.Vector3.Zero();
  12613. this.maximumWorld = BABYLON.Vector3.Zero();
  12614. this.centerWorld = BABYLON.Vector3.Zero();
  12615. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12616. this._update(BABYLON.Matrix.Identity());
  12617. }
  12618. // Methods
  12619. BoundingBox.prototype.getWorldMatrix = function () {
  12620. return this._worldMatrix;
  12621. };
  12622. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12623. this._worldMatrix.copyFrom(matrix);
  12624. return this;
  12625. };
  12626. BoundingBox.prototype._update = function (world) {
  12627. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12628. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12629. for (var index = 0; index < this.vectors.length; index++) {
  12630. var v = this.vectorsWorld[index];
  12631. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12632. if (v.x < this.minimumWorld.x)
  12633. this.minimumWorld.x = v.x;
  12634. if (v.y < this.minimumWorld.y)
  12635. this.minimumWorld.y = v.y;
  12636. if (v.z < this.minimumWorld.z)
  12637. this.minimumWorld.z = v.z;
  12638. if (v.x > this.maximumWorld.x)
  12639. this.maximumWorld.x = v.x;
  12640. if (v.y > this.maximumWorld.y)
  12641. this.maximumWorld.y = v.y;
  12642. if (v.z > this.maximumWorld.z)
  12643. this.maximumWorld.z = v.z;
  12644. }
  12645. // Extend
  12646. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12647. this.extendSizeWorld.scaleInPlace(0.5);
  12648. // OBB
  12649. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12650. this.centerWorld.scaleInPlace(0.5);
  12651. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12652. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12653. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12654. this._worldMatrix = world;
  12655. };
  12656. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12657. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12658. };
  12659. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12660. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12661. };
  12662. BoundingBox.prototype.intersectsPoint = function (point) {
  12663. var delta = -BABYLON.Epsilon;
  12664. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12665. return false;
  12666. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12667. return false;
  12668. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12669. return false;
  12670. return true;
  12671. };
  12672. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12673. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12674. };
  12675. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12676. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12677. return false;
  12678. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12679. return false;
  12680. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12681. return false;
  12682. return true;
  12683. };
  12684. // Statics
  12685. BoundingBox.Intersects = function (box0, box1) {
  12686. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12687. return false;
  12688. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12689. return false;
  12690. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12691. return false;
  12692. return true;
  12693. };
  12694. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12695. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12696. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12697. return (num <= (sphereRadius * sphereRadius));
  12698. };
  12699. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12700. for (var p = 0; p < 6; p++) {
  12701. for (var i = 0; i < 8; i++) {
  12702. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12703. return false;
  12704. }
  12705. }
  12706. }
  12707. return true;
  12708. };
  12709. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12710. for (var p = 0; p < 6; p++) {
  12711. var inCount = 8;
  12712. for (var i = 0; i < 8; i++) {
  12713. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12714. --inCount;
  12715. }
  12716. else {
  12717. break;
  12718. }
  12719. }
  12720. if (inCount === 0)
  12721. return false;
  12722. }
  12723. return true;
  12724. };
  12725. return BoundingBox;
  12726. }());
  12727. BABYLON.BoundingBox = BoundingBox;
  12728. })(BABYLON || (BABYLON = {}));
  12729. //# sourceMappingURL=babylon.boundingBox.js.map
  12730. var BABYLON;
  12731. (function (BABYLON) {
  12732. var computeBoxExtents = function (axis, box) {
  12733. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12734. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12735. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12736. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12737. var r = r0 + r1 + r2;
  12738. return {
  12739. min: p - r,
  12740. max: p + r
  12741. };
  12742. };
  12743. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12744. var axisOverlap = function (axis, box0, box1) {
  12745. var result0 = computeBoxExtents(axis, box0);
  12746. var result1 = computeBoxExtents(axis, box1);
  12747. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12748. };
  12749. var BoundingInfo = /** @class */ (function () {
  12750. function BoundingInfo(minimum, maximum) {
  12751. this.minimum = minimum;
  12752. this.maximum = maximum;
  12753. this._isLocked = false;
  12754. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12755. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12756. }
  12757. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12758. get: function () {
  12759. return this._isLocked;
  12760. },
  12761. set: function (value) {
  12762. this._isLocked = value;
  12763. },
  12764. enumerable: true,
  12765. configurable: true
  12766. });
  12767. // Methods
  12768. BoundingInfo.prototype.update = function (world) {
  12769. if (this._isLocked) {
  12770. return;
  12771. }
  12772. this.boundingBox._update(world);
  12773. this.boundingSphere._update(world);
  12774. };
  12775. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12776. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12777. return false;
  12778. return this.boundingBox.isInFrustum(frustumPlanes);
  12779. };
  12780. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12781. /**
  12782. * Gets the world distance between the min and max points of the bounding box
  12783. */
  12784. get: function () {
  12785. var boundingBox = this.boundingBox;
  12786. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12787. return size.length();
  12788. },
  12789. enumerable: true,
  12790. configurable: true
  12791. });
  12792. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12793. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12794. };
  12795. BoundingInfo.prototype._checkCollision = function (collider) {
  12796. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12797. };
  12798. BoundingInfo.prototype.intersectsPoint = function (point) {
  12799. if (!this.boundingSphere.centerWorld) {
  12800. return false;
  12801. }
  12802. if (!this.boundingSphere.intersectsPoint(point)) {
  12803. return false;
  12804. }
  12805. if (!this.boundingBox.intersectsPoint(point)) {
  12806. return false;
  12807. }
  12808. return true;
  12809. };
  12810. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12811. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12812. return false;
  12813. }
  12814. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12815. return false;
  12816. }
  12817. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12818. return false;
  12819. }
  12820. if (!precise) {
  12821. return true;
  12822. }
  12823. var box0 = this.boundingBox;
  12824. var box1 = boundingInfo.boundingBox;
  12825. if (!axisOverlap(box0.directions[0], box0, box1))
  12826. return false;
  12827. if (!axisOverlap(box0.directions[1], box0, box1))
  12828. return false;
  12829. if (!axisOverlap(box0.directions[2], box0, box1))
  12830. return false;
  12831. if (!axisOverlap(box1.directions[0], box0, box1))
  12832. return false;
  12833. if (!axisOverlap(box1.directions[1], box0, box1))
  12834. return false;
  12835. if (!axisOverlap(box1.directions[2], box0, box1))
  12836. return false;
  12837. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12838. return false;
  12839. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12840. return false;
  12841. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12842. return false;
  12843. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12844. return false;
  12845. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12846. return false;
  12847. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12848. return false;
  12849. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12850. return false;
  12851. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12852. return false;
  12853. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12854. return false;
  12855. return true;
  12856. };
  12857. return BoundingInfo;
  12858. }());
  12859. BABYLON.BoundingInfo = BoundingInfo;
  12860. })(BABYLON || (BABYLON = {}));
  12861. //# sourceMappingURL=babylon.boundingInfo.js.map
  12862. var BABYLON;
  12863. (function (BABYLON) {
  12864. var AbstractMesh = /** @class */ (function (_super) {
  12865. __extends(AbstractMesh, _super);
  12866. // Constructor
  12867. function AbstractMesh(name, scene) {
  12868. if (scene === void 0) { scene = null; }
  12869. var _this = _super.call(this, name, scene) || this;
  12870. _this._facetNb = 0; // facet number
  12871. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12872. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12873. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12874. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12875. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12876. _this._subDiv = {
  12877. max: 1,
  12878. X: 1,
  12879. Y: 1,
  12880. Z: 1
  12881. };
  12882. // Normal matrix
  12883. _this._nonUniformScaling = false;
  12884. // Events
  12885. /**
  12886. * An event triggered when this mesh collides with another one
  12887. * @type {BABYLON.Observable}
  12888. */
  12889. _this.onCollideObservable = new BABYLON.Observable();
  12890. /**
  12891. * An event triggered when the collision's position changes
  12892. * @type {BABYLON.Observable}
  12893. */
  12894. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12895. /**
  12896. * An event triggered after the world matrix is updated
  12897. * @type {BABYLON.Observable}
  12898. */
  12899. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12900. /**
  12901. * An event triggered when material is changed
  12902. * @type {BABYLON.Observable}
  12903. */
  12904. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12905. // Properties
  12906. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12907. _this.position = BABYLON.Vector3.Zero();
  12908. /**
  12909. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12910. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12911. * or
  12912. * 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.
  12913. * for more info check WebGl documentations
  12914. */
  12915. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12916. /**
  12917. * 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:
  12918. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12919. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12920. * 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.
  12921. */
  12922. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12923. /**
  12924. * 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.
  12925. * The default value is -1 which means don't break the query and wait till the result.
  12926. */
  12927. _this.occlusionRetryCount = -1;
  12928. _this._occlusionInternalRetryCounter = 0;
  12929. _this._isOccluded = false;
  12930. _this._isOcclusionQueryInProgress = false;
  12931. _this._rotation = BABYLON.Vector3.Zero();
  12932. _this._scaling = BABYLON.Vector3.One();
  12933. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12934. _this.visibility = 1.0;
  12935. _this.alphaIndex = Number.MAX_VALUE;
  12936. _this.infiniteDistance = false;
  12937. _this.isVisible = true;
  12938. _this.isPickable = true;
  12939. _this.showBoundingBox = false;
  12940. _this.showSubMeshesBoundingBox = false;
  12941. _this.isBlocker = false;
  12942. _this.enablePointerMoveEvents = false;
  12943. _this.renderingGroupId = 0;
  12944. _this._receiveShadows = false;
  12945. _this.renderOutline = false;
  12946. _this.outlineColor = BABYLON.Color3.Red();
  12947. _this.outlineWidth = 0.02;
  12948. _this.renderOverlay = false;
  12949. _this.overlayColor = BABYLON.Color3.Red();
  12950. _this.overlayAlpha = 0.5;
  12951. _this._hasVertexAlpha = false;
  12952. _this._useVertexColors = true;
  12953. _this._computeBonesUsingShaders = true;
  12954. _this._numBoneInfluencers = 4;
  12955. _this._applyFog = true;
  12956. _this.scalingDeterminant = 1;
  12957. _this.useOctreeForRenderingSelection = true;
  12958. _this.useOctreeForPicking = true;
  12959. _this.useOctreeForCollisions = true;
  12960. _this._layerMask = 0x0FFFFFFF;
  12961. /**
  12962. * True if the mesh must be rendered in any case.
  12963. */
  12964. _this.alwaysSelectAsActiveMesh = false;
  12965. // Collisions
  12966. _this._checkCollisions = false;
  12967. _this._collisionMask = -1;
  12968. _this._collisionGroup = -1;
  12969. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12970. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12971. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12972. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12973. // Edges
  12974. _this.edgesWidth = 1;
  12975. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12976. // Cache
  12977. _this._localWorld = BABYLON.Matrix.Zero();
  12978. _this._worldMatrix = BABYLON.Matrix.Zero();
  12979. _this._absolutePosition = BABYLON.Vector3.Zero();
  12980. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12981. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12982. _this._isDirty = false;
  12983. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12984. _this._postMultiplyPivotMatrix = false;
  12985. _this._isDisposed = false;
  12986. _this._renderId = 0;
  12987. _this._intersectionsInProgress = new Array();
  12988. _this._isWorldMatrixFrozen = false;
  12989. _this._unIndexed = false;
  12990. _this._lightSources = new Array();
  12991. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12992. if (collidedMesh === void 0) { collidedMesh = null; }
  12993. //TODO move this to the collision coordinator!
  12994. if (_this.getScene().workerCollisions)
  12995. newPosition.multiplyInPlace(_this._collider.radius);
  12996. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12997. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12998. _this.position.addInPlace(_this._diffPositionForCollisions);
  12999. }
  13000. if (collidedMesh) {
  13001. _this.onCollideObservable.notifyObservers(collidedMesh);
  13002. }
  13003. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  13004. };
  13005. _this.getScene().addMesh(_this);
  13006. _this._resyncLightSources();
  13007. return _this;
  13008. }
  13009. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  13010. get: function () {
  13011. return AbstractMesh._BILLBOARDMODE_NONE;
  13012. },
  13013. enumerable: true,
  13014. configurable: true
  13015. });
  13016. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  13017. get: function () {
  13018. return AbstractMesh._BILLBOARDMODE_X;
  13019. },
  13020. enumerable: true,
  13021. configurable: true
  13022. });
  13023. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  13024. get: function () {
  13025. return AbstractMesh._BILLBOARDMODE_Y;
  13026. },
  13027. enumerable: true,
  13028. configurable: true
  13029. });
  13030. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  13031. get: function () {
  13032. return AbstractMesh._BILLBOARDMODE_Z;
  13033. },
  13034. enumerable: true,
  13035. configurable: true
  13036. });
  13037. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  13038. get: function () {
  13039. return AbstractMesh._BILLBOARDMODE_ALL;
  13040. },
  13041. enumerable: true,
  13042. configurable: true
  13043. });
  13044. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  13045. /**
  13046. * Read-only : the number of facets in the mesh
  13047. */
  13048. get: function () {
  13049. return this._facetNb;
  13050. },
  13051. enumerable: true,
  13052. configurable: true
  13053. });
  13054. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  13055. /**
  13056. * The number (integer) of subdivisions per axis in the partioning space
  13057. */
  13058. get: function () {
  13059. return this._partitioningSubdivisions;
  13060. },
  13061. set: function (nb) {
  13062. this._partitioningSubdivisions = nb;
  13063. },
  13064. enumerable: true,
  13065. configurable: true
  13066. });
  13067. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  13068. /**
  13069. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  13070. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  13071. */
  13072. get: function () {
  13073. return this._partitioningBBoxRatio;
  13074. },
  13075. set: function (ratio) {
  13076. this._partitioningBBoxRatio = ratio;
  13077. },
  13078. enumerable: true,
  13079. configurable: true
  13080. });
  13081. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  13082. /**
  13083. * Read-only boolean : is the feature facetData enabled ?
  13084. */
  13085. get: function () {
  13086. return this._facetDataEnabled;
  13087. },
  13088. enumerable: true,
  13089. configurable: true
  13090. });
  13091. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  13092. get: function () {
  13093. return this._nonUniformScaling;
  13094. },
  13095. set: function (value) {
  13096. if (this._nonUniformScaling === value) {
  13097. return;
  13098. }
  13099. this._nonUniformScaling = true;
  13100. this._markSubMeshesAsMiscDirty();
  13101. },
  13102. enumerable: true,
  13103. configurable: true
  13104. });
  13105. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  13106. set: function (callback) {
  13107. if (this._onCollideObserver) {
  13108. this.onCollideObservable.remove(this._onCollideObserver);
  13109. }
  13110. this._onCollideObserver = this.onCollideObservable.add(callback);
  13111. },
  13112. enumerable: true,
  13113. configurable: true
  13114. });
  13115. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  13116. set: function (callback) {
  13117. if (this._onCollisionPositionChangeObserver) {
  13118. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  13119. }
  13120. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  13121. },
  13122. enumerable: true,
  13123. configurable: true
  13124. });
  13125. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  13126. /**
  13127. * 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.
  13128. */
  13129. get: function () {
  13130. return this._isOccluded;
  13131. },
  13132. set: function (value) {
  13133. this._isOccluded = value;
  13134. },
  13135. enumerable: true,
  13136. configurable: true
  13137. });
  13138. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  13139. /**
  13140. * Flag to check the progress status of the query
  13141. */
  13142. get: function () {
  13143. return this._isOcclusionQueryInProgress;
  13144. },
  13145. enumerable: true,
  13146. configurable: true
  13147. });
  13148. Object.defineProperty(AbstractMesh.prototype, "material", {
  13149. get: function () {
  13150. return this._material;
  13151. },
  13152. set: function (value) {
  13153. if (this._material === value) {
  13154. return;
  13155. }
  13156. this._material = value;
  13157. if (this.onMaterialChangedObservable.hasObservers) {
  13158. this.onMaterialChangedObservable.notifyObservers(this);
  13159. }
  13160. if (!this.subMeshes) {
  13161. return;
  13162. }
  13163. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13164. var subMesh = _a[_i];
  13165. subMesh.setEffect(null);
  13166. }
  13167. },
  13168. enumerable: true,
  13169. configurable: true
  13170. });
  13171. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  13172. get: function () {
  13173. return this._receiveShadows;
  13174. },
  13175. set: function (value) {
  13176. if (this._receiveShadows === value) {
  13177. return;
  13178. }
  13179. this._receiveShadows = value;
  13180. this._markSubMeshesAsLightDirty();
  13181. },
  13182. enumerable: true,
  13183. configurable: true
  13184. });
  13185. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  13186. get: function () {
  13187. return this._hasVertexAlpha;
  13188. },
  13189. set: function (value) {
  13190. if (this._hasVertexAlpha === value) {
  13191. return;
  13192. }
  13193. this._hasVertexAlpha = value;
  13194. this._markSubMeshesAsAttributesDirty();
  13195. },
  13196. enumerable: true,
  13197. configurable: true
  13198. });
  13199. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  13200. get: function () {
  13201. return this._useVertexColors;
  13202. },
  13203. set: function (value) {
  13204. if (this._useVertexColors === value) {
  13205. return;
  13206. }
  13207. this._useVertexColors = value;
  13208. this._markSubMeshesAsAttributesDirty();
  13209. },
  13210. enumerable: true,
  13211. configurable: true
  13212. });
  13213. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  13214. get: function () {
  13215. return this._computeBonesUsingShaders;
  13216. },
  13217. set: function (value) {
  13218. if (this._computeBonesUsingShaders === value) {
  13219. return;
  13220. }
  13221. this._computeBonesUsingShaders = value;
  13222. this._markSubMeshesAsAttributesDirty();
  13223. },
  13224. enumerable: true,
  13225. configurable: true
  13226. });
  13227. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  13228. get: function () {
  13229. return this._numBoneInfluencers;
  13230. },
  13231. set: function (value) {
  13232. if (this._numBoneInfluencers === value) {
  13233. return;
  13234. }
  13235. this._numBoneInfluencers = value;
  13236. this._markSubMeshesAsAttributesDirty();
  13237. },
  13238. enumerable: true,
  13239. configurable: true
  13240. });
  13241. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  13242. get: function () {
  13243. return this._applyFog;
  13244. },
  13245. set: function (value) {
  13246. if (this._applyFog === value) {
  13247. return;
  13248. }
  13249. this._applyFog = value;
  13250. this._markSubMeshesAsMiscDirty();
  13251. },
  13252. enumerable: true,
  13253. configurable: true
  13254. });
  13255. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  13256. get: function () {
  13257. return this._layerMask;
  13258. },
  13259. set: function (value) {
  13260. if (value === this._layerMask) {
  13261. return;
  13262. }
  13263. this._layerMask = value;
  13264. this._resyncLightSources();
  13265. },
  13266. enumerable: true,
  13267. configurable: true
  13268. });
  13269. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  13270. get: function () {
  13271. return this._collisionMask;
  13272. },
  13273. set: function (mask) {
  13274. this._collisionMask = !isNaN(mask) ? mask : -1;
  13275. },
  13276. enumerable: true,
  13277. configurable: true
  13278. });
  13279. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  13280. get: function () {
  13281. return this._collisionGroup;
  13282. },
  13283. set: function (mask) {
  13284. this._collisionGroup = !isNaN(mask) ? mask : -1;
  13285. },
  13286. enumerable: true,
  13287. configurable: true
  13288. });
  13289. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  13290. get: function () {
  13291. return null;
  13292. },
  13293. enumerable: true,
  13294. configurable: true
  13295. });
  13296. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  13297. get: function () {
  13298. return this._skeleton;
  13299. },
  13300. set: function (value) {
  13301. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  13302. this._skeleton._unregisterMeshWithPoseMatrix(this);
  13303. }
  13304. if (value && value.needInitialSkinMatrix) {
  13305. value._registerMeshWithPoseMatrix(this);
  13306. }
  13307. this._skeleton = value;
  13308. if (!this._skeleton) {
  13309. this._bonesTransformMatrices = null;
  13310. }
  13311. this._markSubMeshesAsAttributesDirty();
  13312. },
  13313. enumerable: true,
  13314. configurable: true
  13315. });
  13316. /**
  13317. * Boolean : true if the mesh has been disposed.
  13318. */
  13319. AbstractMesh.prototype.isDisposed = function () {
  13320. return this._isDisposed;
  13321. };
  13322. /**
  13323. * Returns the string "AbstractMesh"
  13324. */
  13325. AbstractMesh.prototype.getClassName = function () {
  13326. return "AbstractMesh";
  13327. };
  13328. /**
  13329. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13330. */
  13331. AbstractMesh.prototype.toString = function (fullDetails) {
  13332. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  13333. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  13334. if (this._skeleton) {
  13335. ret += ", skeleton: " + this._skeleton.name;
  13336. }
  13337. if (fullDetails) {
  13338. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  13339. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  13340. }
  13341. return ret;
  13342. };
  13343. AbstractMesh.prototype._rebuild = function () {
  13344. if (this._occlusionQuery) {
  13345. this._occlusionQuery = null;
  13346. }
  13347. if (this._edgesRenderer) {
  13348. this._edgesRenderer._rebuild();
  13349. }
  13350. if (!this.subMeshes) {
  13351. return;
  13352. }
  13353. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13354. var subMesh = _a[_i];
  13355. subMesh._rebuild();
  13356. }
  13357. };
  13358. AbstractMesh.prototype._resyncLightSources = function () {
  13359. this._lightSources.length = 0;
  13360. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  13361. var light = _a[_i];
  13362. if (!light.isEnabled()) {
  13363. continue;
  13364. }
  13365. if (light.canAffectMesh(this)) {
  13366. this._lightSources.push(light);
  13367. }
  13368. }
  13369. this._markSubMeshesAsLightDirty();
  13370. };
  13371. AbstractMesh.prototype._resyncLighSource = function (light) {
  13372. var isIn = light.isEnabled() && light.canAffectMesh(this);
  13373. var index = this._lightSources.indexOf(light);
  13374. if (index === -1) {
  13375. if (!isIn) {
  13376. return;
  13377. }
  13378. this._lightSources.push(light);
  13379. }
  13380. else {
  13381. if (isIn) {
  13382. return;
  13383. }
  13384. this._lightSources.splice(index, 1);
  13385. }
  13386. this._markSubMeshesAsLightDirty();
  13387. };
  13388. AbstractMesh.prototype._removeLightSource = function (light) {
  13389. var index = this._lightSources.indexOf(light);
  13390. if (index === -1) {
  13391. return;
  13392. }
  13393. this._lightSources.splice(index, 1);
  13394. };
  13395. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  13396. if (!this.subMeshes) {
  13397. return;
  13398. }
  13399. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13400. var subMesh = _a[_i];
  13401. if (subMesh._materialDefines) {
  13402. func(subMesh._materialDefines);
  13403. }
  13404. }
  13405. };
  13406. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13407. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13408. };
  13409. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13410. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13411. };
  13412. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13413. if (!this.subMeshes) {
  13414. return;
  13415. }
  13416. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13417. var subMesh = _a[_i];
  13418. var material = subMesh.getMaterial();
  13419. if (material) {
  13420. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13421. }
  13422. }
  13423. };
  13424. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13425. /**
  13426. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13427. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13428. * Default : (0.0, 0.0, 0.0)
  13429. */
  13430. get: function () {
  13431. return this._rotation;
  13432. },
  13433. set: function (newRotation) {
  13434. this._rotation = newRotation;
  13435. },
  13436. enumerable: true,
  13437. configurable: true
  13438. });
  13439. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13440. /**
  13441. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13442. * Default : (1.0, 1.0, 1.0)
  13443. */
  13444. get: function () {
  13445. return this._scaling;
  13446. },
  13447. set: function (newScaling) {
  13448. this._scaling = newScaling;
  13449. if (this.physicsImpostor) {
  13450. this.physicsImpostor.forceUpdate();
  13451. }
  13452. },
  13453. enumerable: true,
  13454. configurable: true
  13455. });
  13456. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13457. /**
  13458. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13459. * It's null by default.
  13460. * 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)
  13461. */
  13462. get: function () {
  13463. return this._rotationQuaternion;
  13464. },
  13465. set: function (quaternion) {
  13466. this._rotationQuaternion = quaternion;
  13467. //reset the rotation vector.
  13468. if (quaternion && this.rotation.length()) {
  13469. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13470. }
  13471. },
  13472. enumerable: true,
  13473. configurable: true
  13474. });
  13475. // Methods
  13476. /**
  13477. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13478. * Returns the AbstractMesh.
  13479. */
  13480. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13481. this._poseMatrix.copyFrom(matrix);
  13482. return this;
  13483. };
  13484. /**
  13485. * Returns the mesh Pose matrix.
  13486. * Returned object : Matrix
  13487. */
  13488. AbstractMesh.prototype.getPoseMatrix = function () {
  13489. return this._poseMatrix;
  13490. };
  13491. /**
  13492. * Disables the mesh edger rendering mode.
  13493. * Returns the AbstractMesh.
  13494. */
  13495. AbstractMesh.prototype.disableEdgesRendering = function () {
  13496. if (this._edgesRenderer) {
  13497. this._edgesRenderer.dispose();
  13498. this._edgesRenderer = null;
  13499. }
  13500. return this;
  13501. };
  13502. /**
  13503. * Enables the edge rendering mode on the mesh.
  13504. * This mode makes the mesh edges visible.
  13505. * Returns the AbstractMesh.
  13506. */
  13507. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13508. if (epsilon === void 0) { epsilon = 0.95; }
  13509. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13510. this.disableEdgesRendering();
  13511. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13512. return this;
  13513. };
  13514. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13515. /**
  13516. * Returns true if the mesh is blocked. Used by the class Mesh.
  13517. * Returns the boolean `false` by default.
  13518. */
  13519. get: function () {
  13520. return false;
  13521. },
  13522. enumerable: true,
  13523. configurable: true
  13524. });
  13525. /**
  13526. * Returns the mesh itself by default, used by the class Mesh.
  13527. * Returned type : AbstractMesh
  13528. */
  13529. AbstractMesh.prototype.getLOD = function (camera) {
  13530. return this;
  13531. };
  13532. /**
  13533. * Returns 0 by default, used by the class Mesh.
  13534. * Returns an integer.
  13535. */
  13536. AbstractMesh.prototype.getTotalVertices = function () {
  13537. return 0;
  13538. };
  13539. /**
  13540. * Returns null by default, used by the class Mesh.
  13541. * Returned type : integer array
  13542. */
  13543. AbstractMesh.prototype.getIndices = function () {
  13544. return null;
  13545. };
  13546. /**
  13547. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13548. * Returned type : float array or Float32Array
  13549. */
  13550. AbstractMesh.prototype.getVerticesData = function (kind) {
  13551. return null;
  13552. };
  13553. /**
  13554. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13555. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13556. * The `data` are either a numeric array either a Float32Array.
  13557. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13558. * 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).
  13559. * Note that a new underlying VertexBuffer object is created each call.
  13560. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13561. *
  13562. * Possible `kind` values :
  13563. * - BABYLON.VertexBuffer.PositionKind
  13564. * - BABYLON.VertexBuffer.UVKind
  13565. * - BABYLON.VertexBuffer.UV2Kind
  13566. * - BABYLON.VertexBuffer.UV3Kind
  13567. * - BABYLON.VertexBuffer.UV4Kind
  13568. * - BABYLON.VertexBuffer.UV5Kind
  13569. * - BABYLON.VertexBuffer.UV6Kind
  13570. * - BABYLON.VertexBuffer.ColorKind
  13571. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13572. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13573. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13574. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13575. *
  13576. * Returns the Mesh.
  13577. */
  13578. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13579. return this;
  13580. };
  13581. /**
  13582. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13583. * If the mesh has no geometry, it is simply returned as it is.
  13584. * The `data` are either a numeric array either a Float32Array.
  13585. * No new underlying VertexBuffer object is created.
  13586. * 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.
  13587. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13588. *
  13589. * Possible `kind` values :
  13590. * - BABYLON.VertexBuffer.PositionKind
  13591. * - BABYLON.VertexBuffer.UVKind
  13592. * - BABYLON.VertexBuffer.UV2Kind
  13593. * - BABYLON.VertexBuffer.UV3Kind
  13594. * - BABYLON.VertexBuffer.UV4Kind
  13595. * - BABYLON.VertexBuffer.UV5Kind
  13596. * - BABYLON.VertexBuffer.UV6Kind
  13597. * - BABYLON.VertexBuffer.ColorKind
  13598. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13599. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13600. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13601. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13602. *
  13603. * Returns the Mesh.
  13604. */
  13605. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13606. return this;
  13607. };
  13608. /**
  13609. * Sets the mesh indices.
  13610. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13611. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13612. * This method creates a new index buffer each call.
  13613. * Returns the Mesh.
  13614. */
  13615. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13616. return this;
  13617. };
  13618. /** Returns false by default, used by the class Mesh.
  13619. * Returns a boolean
  13620. */
  13621. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13622. return false;
  13623. };
  13624. /**
  13625. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13626. * Returns a BoundingInfo
  13627. */
  13628. AbstractMesh.prototype.getBoundingInfo = function () {
  13629. if (this._masterMesh) {
  13630. return this._masterMesh.getBoundingInfo();
  13631. }
  13632. if (!this._boundingInfo) {
  13633. this._updateBoundingInfo();
  13634. }
  13635. return this._boundingInfo;
  13636. };
  13637. /**
  13638. * Sets a mesh new object BoundingInfo.
  13639. * Returns the AbstractMesh.
  13640. */
  13641. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13642. this._boundingInfo = boundingInfo;
  13643. return this;
  13644. };
  13645. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13646. get: function () {
  13647. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13648. },
  13649. enumerable: true,
  13650. configurable: true
  13651. });
  13652. AbstractMesh.prototype._preActivate = function () {
  13653. };
  13654. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13655. };
  13656. AbstractMesh.prototype._activate = function (renderId) {
  13657. this._renderId = renderId;
  13658. };
  13659. /**
  13660. * Returns the last update of the World matrix
  13661. * Returns a Matrix.
  13662. */
  13663. AbstractMesh.prototype.getWorldMatrix = function (useCachedVersion) {
  13664. if (useCachedVersion === void 0) { useCachedVersion = false; }
  13665. if (this._masterMesh) {
  13666. return this._masterMesh.getWorldMatrix();
  13667. }
  13668. if (!useCachedVersion) {
  13669. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  13670. this.computeWorldMatrix();
  13671. }
  13672. }
  13673. return this._worldMatrix;
  13674. };
  13675. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13676. /**
  13677. * Returns directly the last state of the mesh World matrix.
  13678. * A Matrix is returned.
  13679. */
  13680. get: function () {
  13681. return this._worldMatrix;
  13682. },
  13683. enumerable: true,
  13684. configurable: true
  13685. });
  13686. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13687. /**
  13688. * Returns the current mesh absolute position.
  13689. * Retuns a Vector3.
  13690. */
  13691. get: function () {
  13692. return this._absolutePosition;
  13693. },
  13694. enumerable: true,
  13695. configurable: true
  13696. });
  13697. /**
  13698. * Prevents the World matrix to be computed any longer.
  13699. * Returns the AbstractMesh.
  13700. */
  13701. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13702. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13703. this.computeWorldMatrix(true);
  13704. this._isWorldMatrixFrozen = true;
  13705. return this;
  13706. };
  13707. /**
  13708. * Allows back the World matrix computation.
  13709. * Returns the AbstractMesh.
  13710. */
  13711. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13712. this._isWorldMatrixFrozen = false;
  13713. this.computeWorldMatrix(true);
  13714. return this;
  13715. };
  13716. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13717. /**
  13718. * True if the World matrix has been frozen.
  13719. * Returns a boolean.
  13720. */
  13721. get: function () {
  13722. return this._isWorldMatrixFrozen;
  13723. },
  13724. enumerable: true,
  13725. configurable: true
  13726. });
  13727. /**
  13728. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13729. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13730. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13731. * The passed axis is also normalized.
  13732. * Returns the AbstractMesh.
  13733. */
  13734. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13735. axis.normalize();
  13736. if (!this.rotationQuaternion) {
  13737. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13738. this.rotation = BABYLON.Vector3.Zero();
  13739. }
  13740. var rotationQuaternion;
  13741. if (!space || space === BABYLON.Space.LOCAL) {
  13742. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13743. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13744. }
  13745. else {
  13746. if (this.parent) {
  13747. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13748. invertParentWorldMatrix.invert();
  13749. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13750. }
  13751. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13752. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13753. }
  13754. return this;
  13755. };
  13756. /**
  13757. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13758. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13759. * The passed axis is also normalized.
  13760. * Returns the AbstractMesh.
  13761. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13762. */
  13763. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13764. axis.normalize();
  13765. if (!this.rotationQuaternion) {
  13766. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13767. this.rotation.copyFromFloats(0, 0, 0);
  13768. }
  13769. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13770. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13771. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13772. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13773. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13774. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13775. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13776. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13777. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13778. return this;
  13779. };
  13780. /**
  13781. * Translates the mesh along the axis vector for the passed distance in the given space.
  13782. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13783. * Returns the AbstractMesh.
  13784. */
  13785. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13786. var displacementVector = axis.scale(distance);
  13787. if (!space || space === BABYLON.Space.LOCAL) {
  13788. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13789. this.setPositionWithLocalVector(tempV3);
  13790. }
  13791. else {
  13792. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13793. }
  13794. return this;
  13795. };
  13796. /**
  13797. * Adds a rotation step to the mesh current rotation.
  13798. * x, y, z are Euler angles expressed in radians.
  13799. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13800. * This means this rotation is made in the mesh local space only.
  13801. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13802. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13803. * ```javascript
  13804. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13805. * ```
  13806. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13807. * 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.
  13808. * Returns the AbstractMesh.
  13809. */
  13810. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13811. var rotationQuaternion;
  13812. if (this.rotationQuaternion) {
  13813. rotationQuaternion = this.rotationQuaternion;
  13814. }
  13815. else {
  13816. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13817. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13818. }
  13819. var accumulation = BABYLON.Tmp.Quaternion[0];
  13820. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13821. rotationQuaternion.multiplyInPlace(accumulation);
  13822. if (!this.rotationQuaternion) {
  13823. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13824. }
  13825. return this;
  13826. };
  13827. /**
  13828. * Retuns the mesh absolute position in the World.
  13829. * Returns a Vector3.
  13830. */
  13831. AbstractMesh.prototype.getAbsolutePosition = function () {
  13832. this.computeWorldMatrix();
  13833. return this._absolutePosition;
  13834. };
  13835. /**
  13836. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13837. * Returns the AbstractMesh.
  13838. */
  13839. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13840. if (!absolutePosition) {
  13841. return this;
  13842. }
  13843. var absolutePositionX;
  13844. var absolutePositionY;
  13845. var absolutePositionZ;
  13846. if (absolutePosition.x === undefined) {
  13847. if (arguments.length < 3) {
  13848. return this;
  13849. }
  13850. absolutePositionX = arguments[0];
  13851. absolutePositionY = arguments[1];
  13852. absolutePositionZ = arguments[2];
  13853. }
  13854. else {
  13855. absolutePositionX = absolutePosition.x;
  13856. absolutePositionY = absolutePosition.y;
  13857. absolutePositionZ = absolutePosition.z;
  13858. }
  13859. if (this.parent) {
  13860. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13861. invertParentWorldMatrix.invert();
  13862. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13863. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13864. }
  13865. else {
  13866. this.position.x = absolutePositionX;
  13867. this.position.y = absolutePositionY;
  13868. this.position.z = absolutePositionZ;
  13869. }
  13870. return this;
  13871. };
  13872. // ================================== Point of View Movement =================================
  13873. /**
  13874. * Perform relative position change from the point of view of behind the front of the mesh.
  13875. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13876. * Supports definition of mesh facing forward or backward.
  13877. * @param {number} amountRight
  13878. * @param {number} amountUp
  13879. * @param {number} amountForward
  13880. *
  13881. * Returns the AbstractMesh.
  13882. */
  13883. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13884. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13885. return this;
  13886. };
  13887. /**
  13888. * Calculate relative position change from the point of view of behind the front of the mesh.
  13889. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13890. * Supports definition of mesh facing forward or backward.
  13891. * @param {number} amountRight
  13892. * @param {number} amountUp
  13893. * @param {number} amountForward
  13894. *
  13895. * Returns a new Vector3.
  13896. */
  13897. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13898. var rotMatrix = new BABYLON.Matrix();
  13899. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13900. rotQuaternion.toRotationMatrix(rotMatrix);
  13901. var translationDelta = BABYLON.Vector3.Zero();
  13902. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13903. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13904. return translationDelta;
  13905. };
  13906. // ================================== Point of View Rotation =================================
  13907. /**
  13908. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13909. * Supports definition of mesh facing forward or backward.
  13910. * @param {number} flipBack
  13911. * @param {number} twirlClockwise
  13912. * @param {number} tiltRight
  13913. *
  13914. * Returns the AbstractMesh.
  13915. */
  13916. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13917. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13918. return this;
  13919. };
  13920. /**
  13921. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13922. * Supports definition of mesh facing forward or backward.
  13923. * @param {number} flipBack
  13924. * @param {number} twirlClockwise
  13925. * @param {number} tiltRight
  13926. *
  13927. * Returns a new Vector3.
  13928. */
  13929. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13930. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13931. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13932. };
  13933. /**
  13934. * Sets a new pivot matrix to the mesh.
  13935. * Returns the AbstractMesh.
  13936. */
  13937. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13938. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13939. this._pivotMatrix = matrix.clone();
  13940. this._cache.pivotMatrixUpdated = true;
  13941. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13942. if (this._postMultiplyPivotMatrix) {
  13943. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13944. }
  13945. return this;
  13946. };
  13947. /**
  13948. * Returns the mesh pivot matrix.
  13949. * Default : Identity.
  13950. * A Matrix is returned.
  13951. */
  13952. AbstractMesh.prototype.getPivotMatrix = function () {
  13953. return this._pivotMatrix;
  13954. };
  13955. AbstractMesh.prototype._isSynchronized = function () {
  13956. if (this._isDirty) {
  13957. return false;
  13958. }
  13959. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13960. return false;
  13961. if (this._cache.pivotMatrixUpdated) {
  13962. return false;
  13963. }
  13964. if (this.infiniteDistance) {
  13965. return false;
  13966. }
  13967. if (!this._cache.position.equals(this.position))
  13968. return false;
  13969. if (this.rotationQuaternion) {
  13970. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13971. return false;
  13972. }
  13973. if (!this._cache.rotation.equals(this.rotation))
  13974. return false;
  13975. if (!this._cache.scaling.equals(this.scaling))
  13976. return false;
  13977. return true;
  13978. };
  13979. AbstractMesh.prototype._initCache = function () {
  13980. _super.prototype._initCache.call(this);
  13981. this._cache.localMatrixUpdated = false;
  13982. this._cache.position = BABYLON.Vector3.Zero();
  13983. this._cache.scaling = BABYLON.Vector3.Zero();
  13984. this._cache.rotation = BABYLON.Vector3.Zero();
  13985. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13986. this._cache.billboardMode = -1;
  13987. };
  13988. AbstractMesh.prototype.markAsDirty = function (property) {
  13989. if (property === "rotation") {
  13990. this.rotationQuaternion = null;
  13991. }
  13992. this._currentRenderId = Number.MAX_VALUE;
  13993. this._isDirty = true;
  13994. return this;
  13995. };
  13996. /**
  13997. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13998. */
  13999. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  14000. this.computeWorldMatrix(true);
  14001. var min;
  14002. var max;
  14003. var boundingInfo = this.getBoundingInfo();
  14004. if (!this.subMeshes || !boundingInfo) {
  14005. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14006. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14007. }
  14008. else {
  14009. min = boundingInfo.boundingBox.minimumWorld;
  14010. max = boundingInfo.boundingBox.maximumWorld;
  14011. }
  14012. var descendants = this.getDescendants(false);
  14013. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14014. var descendant = descendants_1[_i];
  14015. var childMesh = descendant;
  14016. childMesh.computeWorldMatrix(true);
  14017. var childBoundingInfo = childMesh.getBoundingInfo();
  14018. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  14019. continue;
  14020. }
  14021. var boundingBox = childBoundingInfo.boundingBox;
  14022. var minBox = boundingBox.minimumWorld;
  14023. var maxBox = boundingBox.maximumWorld;
  14024. BABYLON.Tools.CheckExtends(minBox, min, max);
  14025. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14026. }
  14027. return {
  14028. min: min,
  14029. max: max
  14030. };
  14031. };
  14032. /**
  14033. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14034. * Returns the AbstractMesh.
  14035. */
  14036. AbstractMesh.prototype._updateBoundingInfo = function () {
  14037. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14038. this._boundingInfo.update(this.worldMatrixFromCache);
  14039. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14040. return this;
  14041. };
  14042. /**
  14043. * Update a mesh's children BoundingInfo objects only.
  14044. * Returns the AbstractMesh.
  14045. */
  14046. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14047. if (!this.subMeshes) {
  14048. return this;
  14049. }
  14050. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14051. var subMesh = this.subMeshes[subIndex];
  14052. if (!subMesh.IsGlobal) {
  14053. subMesh.updateBoundingInfo(matrix);
  14054. }
  14055. }
  14056. return this;
  14057. };
  14058. /**
  14059. * Computes the mesh World matrix and returns it.
  14060. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14061. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14062. * If the parameter `force`is set to `true`, the actual computation is done.
  14063. * Returns the mesh World Matrix.
  14064. */
  14065. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  14066. if (this._isWorldMatrixFrozen) {
  14067. return this._worldMatrix;
  14068. }
  14069. if (!force && this.isSynchronized(true)) {
  14070. return this._worldMatrix;
  14071. }
  14072. this._cache.position.copyFrom(this.position);
  14073. this._cache.scaling.copyFrom(this.scaling);
  14074. this._cache.pivotMatrixUpdated = false;
  14075. this._cache.billboardMode = this.billboardMode;
  14076. this._currentRenderId = this.getScene().getRenderId();
  14077. this._isDirty = false;
  14078. // Scaling
  14079. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14080. // Rotation
  14081. //rotate, if quaternion is set and rotation was used
  14082. if (this.rotationQuaternion) {
  14083. var len = this.rotation.length();
  14084. if (len) {
  14085. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14086. this.rotation.copyFromFloats(0, 0, 0);
  14087. }
  14088. }
  14089. if (this.rotationQuaternion) {
  14090. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14091. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14092. }
  14093. else {
  14094. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14095. this._cache.rotation.copyFrom(this.rotation);
  14096. }
  14097. // Translation
  14098. var camera = this.getScene().activeCamera;
  14099. if (this.infiniteDistance && !this.parent && camera) {
  14100. var cameraWorldMatrix = camera.getWorldMatrix();
  14101. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14102. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14103. }
  14104. else {
  14105. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14106. }
  14107. // Composing transformations
  14108. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14109. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14110. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14111. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14112. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  14113. // Need to decompose each rotation here
  14114. var currentPosition = BABYLON.Tmp.Vector3[3];
  14115. if (this.parent && this.parent.getWorldMatrix) {
  14116. if (this._meshToBoneReferal) {
  14117. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14118. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14119. }
  14120. else {
  14121. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14122. }
  14123. }
  14124. else {
  14125. currentPosition.copyFrom(this.position);
  14126. }
  14127. currentPosition.subtractInPlace(camera.globalPosition);
  14128. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14129. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  14130. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14131. }
  14132. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  14133. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14134. }
  14135. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  14136. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14137. }
  14138. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14139. }
  14140. else {
  14141. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14142. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14143. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14144. }
  14145. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14146. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14147. }
  14148. // Local world
  14149. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14150. // Parent
  14151. if (this.parent && this.parent.getWorldMatrix) {
  14152. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  14153. if (this._meshToBoneReferal) {
  14154. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14155. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14156. }
  14157. else {
  14158. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14159. }
  14160. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14161. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14162. this._worldMatrix.copyFrom(this._localWorld);
  14163. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14164. }
  14165. else {
  14166. if (this._meshToBoneReferal) {
  14167. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14168. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14169. }
  14170. else {
  14171. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14172. }
  14173. }
  14174. this._markSyncedWithParent();
  14175. }
  14176. else {
  14177. this._worldMatrix.copyFrom(this._localWorld);
  14178. }
  14179. // Post multiply inverse of pivotMatrix
  14180. if (this._postMultiplyPivotMatrix) {
  14181. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14182. }
  14183. // Normal matrix
  14184. if (this.scaling.isNonUniform) {
  14185. this.nonUniformScaling = true;
  14186. }
  14187. else if (this.parent && this.parent._nonUniformScaling) {
  14188. this.nonUniformScaling = this.parent._nonUniformScaling;
  14189. }
  14190. else {
  14191. this.nonUniformScaling = false;
  14192. }
  14193. // Bounding info
  14194. this._updateBoundingInfo();
  14195. // Absolute position
  14196. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14197. // Callbacks
  14198. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14199. if (!this._poseMatrix) {
  14200. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14201. }
  14202. return this._worldMatrix;
  14203. };
  14204. /**
  14205. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14206. * @param func: callback function to add
  14207. *
  14208. * Returns the AbstractMesh.
  14209. */
  14210. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14211. this.onAfterWorldMatrixUpdateObservable.add(func);
  14212. return this;
  14213. };
  14214. /**
  14215. * Removes a registered callback function.
  14216. * Returns the AbstractMesh.
  14217. */
  14218. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14219. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14220. return this;
  14221. };
  14222. /**
  14223. * Sets the mesh position in its local space.
  14224. * Returns the AbstractMesh.
  14225. */
  14226. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  14227. this.computeWorldMatrix();
  14228. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14229. return this;
  14230. };
  14231. /**
  14232. * Returns the mesh position in the local space from the current World matrix values.
  14233. * Returns a new Vector3.
  14234. */
  14235. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  14236. this.computeWorldMatrix();
  14237. var invLocalWorldMatrix = this._localWorld.clone();
  14238. invLocalWorldMatrix.invert();
  14239. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14240. };
  14241. /**
  14242. * Translates the mesh along the passed Vector3 in its local space.
  14243. * Returns the AbstractMesh.
  14244. */
  14245. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  14246. this.computeWorldMatrix(true);
  14247. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14248. return this;
  14249. };
  14250. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14251. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  14252. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  14253. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  14254. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  14255. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  14256. /// <returns>Mesh oriented towards targetMesh</returns>
  14257. if (yawCor === void 0) { yawCor = 0; }
  14258. if (pitchCor === void 0) { pitchCor = 0; }
  14259. if (rollCor === void 0) { rollCor = 0; }
  14260. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14261. var dv = AbstractMesh._lookAtVectorCache;
  14262. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14263. targetPoint.subtractToRef(pos, dv);
  14264. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14265. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14266. var pitch = Math.atan2(dv.y, len);
  14267. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  14268. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14269. return this;
  14270. };
  14271. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  14272. this._meshToBoneReferal = affectedMesh;
  14273. this.parent = bone;
  14274. if (bone.getWorldMatrix().determinant() < 0) {
  14275. this.scalingDeterminant *= -1;
  14276. }
  14277. return this;
  14278. };
  14279. AbstractMesh.prototype.detachFromBone = function () {
  14280. if (!this.parent) {
  14281. return this;
  14282. }
  14283. if (this.parent.getWorldMatrix().determinant() < 0) {
  14284. this.scalingDeterminant *= -1;
  14285. }
  14286. this._meshToBoneReferal = null;
  14287. this.parent = null;
  14288. return this;
  14289. };
  14290. /**
  14291. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14292. * A mesh is in the frustum if its bounding box intersects the frustum.
  14293. * Boolean returned.
  14294. */
  14295. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14296. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14297. };
  14298. /**
  14299. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14300. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14301. * Boolean returned.
  14302. */
  14303. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14304. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14305. ;
  14306. };
  14307. /**
  14308. * True if the mesh intersects another mesh or a SolidParticle object.
  14309. * 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)
  14310. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14311. * Returns a boolean.
  14312. */
  14313. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14314. if (precise === void 0) { precise = false; }
  14315. if (!this._boundingInfo || !mesh._boundingInfo) {
  14316. return false;
  14317. }
  14318. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14319. return true;
  14320. }
  14321. if (includeDescendants) {
  14322. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14323. var child = _a[_i];
  14324. if (child.intersectsMesh(mesh, precise, true)) {
  14325. return true;
  14326. }
  14327. }
  14328. }
  14329. return false;
  14330. };
  14331. /**
  14332. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14333. * Returns a boolean.
  14334. */
  14335. AbstractMesh.prototype.intersectsPoint = function (point) {
  14336. if (!this._boundingInfo) {
  14337. return false;
  14338. }
  14339. return this._boundingInfo.intersectsPoint(point);
  14340. };
  14341. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14342. return this.physicsImpostor;
  14343. };
  14344. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14345. if (camera === void 0) { camera = null; }
  14346. if (!camera) {
  14347. camera = this.getScene().activeCamera;
  14348. }
  14349. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14350. };
  14351. /**
  14352. * Returns the distance from the mesh to the active camera.
  14353. * Returns a float.
  14354. */
  14355. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14356. if (camera === void 0) { camera = null; }
  14357. if (!camera) {
  14358. camera = this.getScene().activeCamera;
  14359. }
  14360. return this.absolutePosition.subtract(camera.position).length();
  14361. };
  14362. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14363. if (!this.physicsImpostor) {
  14364. return this;
  14365. }
  14366. this.physicsImpostor.applyImpulse(force, contactPoint);
  14367. return this;
  14368. };
  14369. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14370. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14371. return this;
  14372. }
  14373. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14374. mainPivot: pivot1,
  14375. connectedPivot: pivot2,
  14376. nativeParams: options
  14377. });
  14378. return this;
  14379. };
  14380. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14381. // Collisions
  14382. /**
  14383. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14384. * Default `false`.
  14385. */
  14386. get: function () {
  14387. return this._checkCollisions;
  14388. },
  14389. set: function (collisionEnabled) {
  14390. this._checkCollisions = collisionEnabled;
  14391. if (this.getScene().workerCollisions) {
  14392. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14393. }
  14394. },
  14395. enumerable: true,
  14396. configurable: true
  14397. });
  14398. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14399. var globalPosition = this.getAbsolutePosition();
  14400. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14401. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14402. if (!this._collider) {
  14403. this._collider = new BABYLON.Collider();
  14404. }
  14405. this._collider.radius = this.ellipsoid;
  14406. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14407. return this;
  14408. };
  14409. // Submeshes octree
  14410. /**
  14411. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14412. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14413. * Returns an Octree of submeshes.
  14414. */
  14415. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14416. if (maxCapacity === void 0) { maxCapacity = 64; }
  14417. if (maxDepth === void 0) { maxDepth = 2; }
  14418. if (!this._submeshesOctree) {
  14419. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14420. }
  14421. this.computeWorldMatrix(true);
  14422. var boundingInfo = this.getBoundingInfo();
  14423. // Update octree
  14424. if (boundingInfo) {
  14425. var bbox = boundingInfo.boundingBox;
  14426. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14427. }
  14428. return this._submeshesOctree;
  14429. };
  14430. // Collisions
  14431. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14432. this._generatePointsArray();
  14433. if (!this._positions) {
  14434. return this;
  14435. }
  14436. // Transformation
  14437. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14438. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14439. subMesh._lastColliderWorldVertices = [];
  14440. subMesh._trianglePlanes = [];
  14441. var start = subMesh.verticesStart;
  14442. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14443. for (var i = start; i < end; i++) {
  14444. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14445. }
  14446. }
  14447. // Collide
  14448. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14449. if (collider.collisionFound) {
  14450. collider.collidedMesh = this;
  14451. }
  14452. return this;
  14453. };
  14454. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14455. var subMeshes;
  14456. var len;
  14457. // Octrees
  14458. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14459. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14460. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14461. len = intersections.length;
  14462. subMeshes = intersections.data;
  14463. }
  14464. else {
  14465. subMeshes = this.subMeshes;
  14466. len = subMeshes.length;
  14467. }
  14468. for (var index = 0; index < len; index++) {
  14469. var subMesh = subMeshes[index];
  14470. // Bounding test
  14471. if (len > 1 && !subMesh._checkCollision(collider))
  14472. continue;
  14473. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14474. }
  14475. return this;
  14476. };
  14477. AbstractMesh.prototype._checkCollision = function (collider) {
  14478. // Bounding box test
  14479. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14480. return this;
  14481. // Transformation matrix
  14482. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14483. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14484. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14485. return this;
  14486. };
  14487. // Picking
  14488. AbstractMesh.prototype._generatePointsArray = function () {
  14489. return false;
  14490. };
  14491. /**
  14492. * Checks if the passed Ray intersects with the mesh.
  14493. * Returns an object PickingInfo.
  14494. */
  14495. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14496. var pickingInfo = new BABYLON.PickingInfo();
  14497. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14498. return pickingInfo;
  14499. }
  14500. if (!this._generatePointsArray()) {
  14501. return pickingInfo;
  14502. }
  14503. var intersectInfo = null;
  14504. // Octrees
  14505. var subMeshes;
  14506. var len;
  14507. if (this._submeshesOctree && this.useOctreeForPicking) {
  14508. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14509. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14510. len = intersections.length;
  14511. subMeshes = intersections.data;
  14512. }
  14513. else {
  14514. subMeshes = this.subMeshes;
  14515. len = subMeshes.length;
  14516. }
  14517. for (var index = 0; index < len; index++) {
  14518. var subMesh = subMeshes[index];
  14519. // Bounding test
  14520. if (len > 1 && !subMesh.canIntersects(ray))
  14521. continue;
  14522. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14523. if (currentIntersectInfo) {
  14524. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14525. intersectInfo = currentIntersectInfo;
  14526. intersectInfo.subMeshId = index;
  14527. if (fastCheck) {
  14528. break;
  14529. }
  14530. }
  14531. }
  14532. }
  14533. if (intersectInfo) {
  14534. // Get picked point
  14535. var world = this.getWorldMatrix();
  14536. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14537. var direction = ray.direction.clone();
  14538. direction = direction.scale(intersectInfo.distance);
  14539. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14540. var pickedPoint = worldOrigin.add(worldDirection);
  14541. // Return result
  14542. pickingInfo.hit = true;
  14543. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14544. pickingInfo.pickedPoint = pickedPoint;
  14545. pickingInfo.pickedMesh = this;
  14546. pickingInfo.bu = intersectInfo.bu || 0;
  14547. pickingInfo.bv = intersectInfo.bv || 0;
  14548. pickingInfo.faceId = intersectInfo.faceId;
  14549. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14550. return pickingInfo;
  14551. }
  14552. return pickingInfo;
  14553. };
  14554. /**
  14555. * Clones the mesh, used by the class Mesh.
  14556. * Just returns `null` for an AbstractMesh.
  14557. */
  14558. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14559. return null;
  14560. };
  14561. /**
  14562. * Disposes all the mesh submeshes.
  14563. * Returns the AbstractMesh.
  14564. */
  14565. AbstractMesh.prototype.releaseSubMeshes = function () {
  14566. if (this.subMeshes) {
  14567. while (this.subMeshes.length) {
  14568. this.subMeshes[0].dispose();
  14569. }
  14570. }
  14571. else {
  14572. this.subMeshes = new Array();
  14573. }
  14574. return this;
  14575. };
  14576. /**
  14577. * Disposes the AbstractMesh.
  14578. * Some internal references are kept for further use.
  14579. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14580. * Returns nothing.
  14581. */
  14582. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14583. var _this = this;
  14584. var index;
  14585. // Action manager
  14586. if (this.actionManager) {
  14587. this.actionManager.dispose();
  14588. this.actionManager = null;
  14589. }
  14590. // Skeleton
  14591. this.skeleton = null;
  14592. // Animations
  14593. this.getScene().stopAnimation(this);
  14594. // Physics
  14595. if (this.physicsImpostor) {
  14596. this.physicsImpostor.dispose();
  14597. }
  14598. // Intersections in progress
  14599. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14600. var other = this._intersectionsInProgress[index];
  14601. var pos = other._intersectionsInProgress.indexOf(this);
  14602. other._intersectionsInProgress.splice(pos, 1);
  14603. }
  14604. this._intersectionsInProgress = [];
  14605. // Lights
  14606. var lights = this.getScene().lights;
  14607. lights.forEach(function (light) {
  14608. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14609. if (meshIndex !== -1) {
  14610. light.includedOnlyMeshes.splice(meshIndex, 1);
  14611. }
  14612. meshIndex = light.excludedMeshes.indexOf(_this);
  14613. if (meshIndex !== -1) {
  14614. light.excludedMeshes.splice(meshIndex, 1);
  14615. }
  14616. // Shadow generators
  14617. var generator = light.getShadowGenerator();
  14618. if (generator) {
  14619. var shadowMap = generator.getShadowMap();
  14620. if (shadowMap && shadowMap.renderList) {
  14621. meshIndex = shadowMap.renderList.indexOf(_this);
  14622. if (meshIndex !== -1) {
  14623. shadowMap.renderList.splice(meshIndex, 1);
  14624. }
  14625. }
  14626. }
  14627. });
  14628. // Edges
  14629. if (this._edgesRenderer) {
  14630. this._edgesRenderer.dispose();
  14631. this._edgesRenderer = null;
  14632. }
  14633. // SubMeshes
  14634. if (this.getClassName() !== "InstancedMesh") {
  14635. this.releaseSubMeshes();
  14636. }
  14637. // Octree
  14638. var sceneOctree = this.getScene().selectionOctree;
  14639. if (sceneOctree) {
  14640. var index = sceneOctree.dynamicContent.indexOf(this);
  14641. if (index !== -1) {
  14642. sceneOctree.dynamicContent.splice(index, 1);
  14643. }
  14644. }
  14645. // Query
  14646. var engine = this.getScene().getEngine();
  14647. if (this._occlusionQuery) {
  14648. this._isOcclusionQueryInProgress = false;
  14649. engine.deleteQuery(this._occlusionQuery);
  14650. this._occlusionQuery = null;
  14651. }
  14652. // Engine
  14653. engine.wipeCaches();
  14654. // Remove from scene
  14655. this.getScene().removeMesh(this);
  14656. if (!doNotRecurse) {
  14657. // Particles
  14658. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14659. if (this.getScene().particleSystems[index].emitter === this) {
  14660. this.getScene().particleSystems[index].dispose();
  14661. index--;
  14662. }
  14663. }
  14664. // Children
  14665. var objects = this.getDescendants(true);
  14666. for (index = 0; index < objects.length; index++) {
  14667. objects[index].dispose();
  14668. }
  14669. }
  14670. else {
  14671. var childMeshes = this.getChildMeshes(true);
  14672. for (index = 0; index < childMeshes.length; index++) {
  14673. var child = childMeshes[index];
  14674. child.parent = null;
  14675. child.computeWorldMatrix(true);
  14676. }
  14677. }
  14678. // facet data
  14679. if (this._facetDataEnabled) {
  14680. this.disableFacetData();
  14681. }
  14682. this.onAfterWorldMatrixUpdateObservable.clear();
  14683. this.onCollideObservable.clear();
  14684. this.onCollisionPositionChangeObservable.clear();
  14685. this._isDisposed = true;
  14686. _super.prototype.dispose.call(this);
  14687. };
  14688. /**
  14689. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14690. * This Vector3 is expressed in the World space.
  14691. */
  14692. AbstractMesh.prototype.getDirection = function (localAxis) {
  14693. var result = BABYLON.Vector3.Zero();
  14694. this.getDirectionToRef(localAxis, result);
  14695. return result;
  14696. };
  14697. /**
  14698. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14699. * localAxis is expressed in the mesh local space.
  14700. * result is computed in the Wordl space from the mesh World matrix.
  14701. * Returns the AbstractMesh.
  14702. */
  14703. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14704. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14705. return this;
  14706. };
  14707. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14708. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14709. if (this.getScene().getRenderId() == 0) {
  14710. this.computeWorldMatrix(true);
  14711. }
  14712. var wm = this.getWorldMatrix();
  14713. if (space == BABYLON.Space.WORLD) {
  14714. var tmat = BABYLON.Tmp.Matrix[0];
  14715. wm.invertToRef(tmat);
  14716. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14717. }
  14718. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14719. this._pivotMatrix.m[12] = -point.x;
  14720. this._pivotMatrix.m[13] = -point.y;
  14721. this._pivotMatrix.m[14] = -point.z;
  14722. this._cache.pivotMatrixUpdated = true;
  14723. return this;
  14724. };
  14725. /**
  14726. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14727. */
  14728. AbstractMesh.prototype.getPivotPoint = function () {
  14729. var point = BABYLON.Vector3.Zero();
  14730. this.getPivotPointToRef(point);
  14731. return point;
  14732. };
  14733. /**
  14734. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14735. * Returns the AbstractMesh.
  14736. */
  14737. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14738. result.x = -this._pivotMatrix.m[12];
  14739. result.y = -this._pivotMatrix.m[13];
  14740. result.z = -this._pivotMatrix.m[14];
  14741. return this;
  14742. };
  14743. /**
  14744. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14745. */
  14746. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14747. var point = BABYLON.Vector3.Zero();
  14748. this.getAbsolutePivotPointToRef(point);
  14749. return point;
  14750. };
  14751. /**
  14752. * Defines the passed mesh as the parent of the current mesh.
  14753. * Returns the AbstractMesh.
  14754. */
  14755. AbstractMesh.prototype.setParent = function (mesh) {
  14756. var parent = mesh;
  14757. if (mesh == null) {
  14758. var rotation = BABYLON.Tmp.Quaternion[0];
  14759. var position = BABYLON.Tmp.Vector3[0];
  14760. var scale = BABYLON.Tmp.Vector3[1];
  14761. this.getWorldMatrix().decompose(scale, rotation, position);
  14762. if (this.rotationQuaternion) {
  14763. this.rotationQuaternion.copyFrom(rotation);
  14764. }
  14765. else {
  14766. rotation.toEulerAnglesToRef(this.rotation);
  14767. }
  14768. this.position.x = position.x;
  14769. this.position.y = position.y;
  14770. this.position.z = position.z;
  14771. }
  14772. else {
  14773. var position = BABYLON.Tmp.Vector3[0];
  14774. var m1 = BABYLON.Tmp.Matrix[0];
  14775. parent.getWorldMatrix().invertToRef(m1);
  14776. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  14777. this.position.copyFrom(position);
  14778. }
  14779. this.parent = parent;
  14780. return this;
  14781. };
  14782. /**
  14783. * Adds the passed mesh as a child to the current mesh.
  14784. * Returns the AbstractMesh.
  14785. */
  14786. AbstractMesh.prototype.addChild = function (mesh) {
  14787. mesh.setParent(this);
  14788. return this;
  14789. };
  14790. /**
  14791. * Removes the passed mesh from the current mesh children list.
  14792. * Returns the AbstractMesh.
  14793. */
  14794. AbstractMesh.prototype.removeChild = function (mesh) {
  14795. mesh.setParent(null);
  14796. return this;
  14797. };
  14798. /**
  14799. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14800. * Returns the AbstractMesh.
  14801. */
  14802. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14803. result.x = this._pivotMatrix.m[12];
  14804. result.y = this._pivotMatrix.m[13];
  14805. result.z = this._pivotMatrix.m[14];
  14806. this.getPivotPointToRef(result);
  14807. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14808. return this;
  14809. };
  14810. // Facet data
  14811. /**
  14812. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14813. * Returns the AbstractMesh.
  14814. */
  14815. AbstractMesh.prototype._initFacetData = function () {
  14816. if (!this._facetNormals) {
  14817. this._facetNormals = new Array();
  14818. }
  14819. if (!this._facetPositions) {
  14820. this._facetPositions = new Array();
  14821. }
  14822. if (!this._facetPartitioning) {
  14823. this._facetPartitioning = new Array();
  14824. }
  14825. this._facetNb = this.getIndices().length / 3;
  14826. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14827. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14828. for (var f = 0; f < this._facetNb; f++) {
  14829. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14830. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14831. }
  14832. this._facetDataEnabled = true;
  14833. return this;
  14834. };
  14835. /**
  14836. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14837. * This method can be called within the render loop.
  14838. * 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.
  14839. * Returns the AbstractMesh.
  14840. */
  14841. AbstractMesh.prototype.updateFacetData = function () {
  14842. if (!this._facetDataEnabled) {
  14843. this._initFacetData();
  14844. }
  14845. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14846. var indices = this.getIndices();
  14847. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14848. var bInfo = this.getBoundingInfo();
  14849. if (!bInfo) {
  14850. return this;
  14851. }
  14852. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14853. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14854. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14855. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14856. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14857. this._subDiv.max = this._partitioningSubdivisions;
  14858. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14859. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14860. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14861. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14862. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14863. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14864. // set the parameters for ComputeNormals()
  14865. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14866. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14867. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14868. this._facetParameters.bInfo = bInfo;
  14869. this._facetParameters.bbSize = this._bbSize;
  14870. this._facetParameters.subDiv = this._subDiv;
  14871. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14872. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14873. return this;
  14874. };
  14875. /**
  14876. * Returns the facetLocalNormals array.
  14877. * The normals are expressed in the mesh local space.
  14878. */
  14879. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14880. if (!this._facetNormals) {
  14881. this.updateFacetData();
  14882. }
  14883. return this._facetNormals;
  14884. };
  14885. /**
  14886. * Returns the facetLocalPositions array.
  14887. * The facet positions are expressed in the mesh local space.
  14888. */
  14889. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14890. if (!this._facetPositions) {
  14891. this.updateFacetData();
  14892. }
  14893. return this._facetPositions;
  14894. };
  14895. /**
  14896. * Returns the facetLocalPartioning array.
  14897. */
  14898. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14899. if (!this._facetPartitioning) {
  14900. this.updateFacetData();
  14901. }
  14902. return this._facetPartitioning;
  14903. };
  14904. /**
  14905. * Returns the i-th facet position in the world system.
  14906. * This method allocates a new Vector3 per call.
  14907. */
  14908. AbstractMesh.prototype.getFacetPosition = function (i) {
  14909. var pos = BABYLON.Vector3.Zero();
  14910. this.getFacetPositionToRef(i, pos);
  14911. return pos;
  14912. };
  14913. /**
  14914. * Sets the reference Vector3 with the i-th facet position in the world system.
  14915. * Returns the AbstractMesh.
  14916. */
  14917. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14918. var localPos = (this.getFacetLocalPositions())[i];
  14919. var world = this.getWorldMatrix();
  14920. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14921. return this;
  14922. };
  14923. /**
  14924. * Returns the i-th facet normal in the world system.
  14925. * This method allocates a new Vector3 per call.
  14926. */
  14927. AbstractMesh.prototype.getFacetNormal = function (i) {
  14928. var norm = BABYLON.Vector3.Zero();
  14929. this.getFacetNormalToRef(i, norm);
  14930. return norm;
  14931. };
  14932. /**
  14933. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14934. * Returns the AbstractMesh.
  14935. */
  14936. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14937. var localNorm = (this.getFacetLocalNormals())[i];
  14938. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14939. return this;
  14940. };
  14941. /**
  14942. * 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).
  14943. */
  14944. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14945. var bInfo = this.getBoundingInfo();
  14946. if (!bInfo) {
  14947. return null;
  14948. }
  14949. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14950. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14951. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14952. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14953. return null;
  14954. }
  14955. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14956. };
  14957. /**
  14958. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14959. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14960. * 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.
  14961. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14962. * 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.
  14963. */
  14964. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14965. if (checkFace === void 0) { checkFace = false; }
  14966. if (facing === void 0) { facing = true; }
  14967. var world = this.getWorldMatrix();
  14968. var invMat = BABYLON.Tmp.Matrix[5];
  14969. world.invertToRef(invMat);
  14970. var invVect = BABYLON.Tmp.Vector3[8];
  14971. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14972. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14973. if (projected) {
  14974. // tranform the local computed projected vector to world coordinates
  14975. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14976. }
  14977. return closest;
  14978. };
  14979. /**
  14980. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14981. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14982. * 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.
  14983. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14984. * 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.
  14985. */
  14986. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14987. if (checkFace === void 0) { checkFace = false; }
  14988. if (facing === void 0) { facing = true; }
  14989. var closest = null;
  14990. var tmpx = 0.0;
  14991. var tmpy = 0.0;
  14992. var tmpz = 0.0;
  14993. var d = 0.0; // tmp dot facet normal * facet position
  14994. var t0 = 0.0;
  14995. var projx = 0.0;
  14996. var projy = 0.0;
  14997. var projz = 0.0;
  14998. // Get all the facets in the same partitioning block than (x, y, z)
  14999. var facetPositions = this.getFacetLocalPositions();
  15000. var facetNormals = this.getFacetLocalNormals();
  15001. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15002. if (!facetsInBlock) {
  15003. return null;
  15004. }
  15005. // Get the closest facet to (x, y, z)
  15006. var shortest = Number.MAX_VALUE; // init distance vars
  15007. var tmpDistance = shortest;
  15008. var fib; // current facet in the block
  15009. var norm; // current facet normal
  15010. var p0; // current facet barycenter position
  15011. // loop on all the facets in the current partitioning block
  15012. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15013. fib = facetsInBlock[idx];
  15014. norm = facetNormals[fib];
  15015. p0 = facetPositions[fib];
  15016. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15017. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15018. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15019. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15020. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15021. projx = x + norm.x * t0;
  15022. projy = y + norm.y * t0;
  15023. projz = z + norm.z * t0;
  15024. tmpx = projx - x;
  15025. tmpy = projy - y;
  15026. tmpz = projz - z;
  15027. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15028. if (tmpDistance < shortest) {
  15029. shortest = tmpDistance;
  15030. closest = fib;
  15031. if (projected) {
  15032. projected.x = projx;
  15033. projected.y = projy;
  15034. projected.z = projz;
  15035. }
  15036. }
  15037. }
  15038. }
  15039. return closest;
  15040. };
  15041. /**
  15042. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15043. */
  15044. AbstractMesh.prototype.getFacetDataParameters = function () {
  15045. return this._facetParameters;
  15046. };
  15047. /**
  15048. * Disables the feature FacetData and frees the related memory.
  15049. * Returns the AbstractMesh.
  15050. */
  15051. AbstractMesh.prototype.disableFacetData = function () {
  15052. if (this._facetDataEnabled) {
  15053. this._facetDataEnabled = false;
  15054. this._facetPositions = new Array();
  15055. ;
  15056. this._facetNormals = new Array();
  15057. ;
  15058. this._facetPartitioning = new Array();
  15059. ;
  15060. this._facetParameters = null;
  15061. }
  15062. return this;
  15063. };
  15064. /**
  15065. * Creates new normals data for the mesh.
  15066. * @param updatable.
  15067. */
  15068. AbstractMesh.prototype.createNormals = function (updatable) {
  15069. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15070. var indices = this.getIndices();
  15071. var normals;
  15072. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15073. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15074. }
  15075. else {
  15076. normals = [];
  15077. }
  15078. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15079. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15080. };
  15081. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15082. var engine = this.getEngine();
  15083. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15084. this._isOccluded = false;
  15085. return;
  15086. }
  15087. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15088. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15089. if (isOcclusionQueryAvailable) {
  15090. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15091. this._isOcclusionQueryInProgress = false;
  15092. this._occlusionInternalRetryCounter = 0;
  15093. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15094. }
  15095. else {
  15096. this._occlusionInternalRetryCounter++;
  15097. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15098. this._isOcclusionQueryInProgress = false;
  15099. this._occlusionInternalRetryCounter = 0;
  15100. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15101. // if strict continue the last state of the object.
  15102. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15103. }
  15104. else {
  15105. return;
  15106. }
  15107. }
  15108. }
  15109. var scene = this.getScene();
  15110. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15111. if (!this._occlusionQuery) {
  15112. this._occlusionQuery = engine.createQuery();
  15113. }
  15114. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15115. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15116. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15117. this._isOcclusionQueryInProgress = true;
  15118. };
  15119. // Statics
  15120. AbstractMesh._BILLBOARDMODE_NONE = 0;
  15121. AbstractMesh._BILLBOARDMODE_X = 1;
  15122. AbstractMesh._BILLBOARDMODE_Y = 2;
  15123. AbstractMesh._BILLBOARDMODE_Z = 4;
  15124. AbstractMesh._BILLBOARDMODE_ALL = 7;
  15125. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15126. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15127. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15128. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15129. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15130. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  15131. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15132. return AbstractMesh;
  15133. }(BABYLON.Node));
  15134. BABYLON.AbstractMesh = AbstractMesh;
  15135. })(BABYLON || (BABYLON = {}));
  15136. //# sourceMappingURL=babylon.abstractMesh.js.map
  15137. var BABYLON;
  15138. (function (BABYLON) {
  15139. var Light = /** @class */ (function (_super) {
  15140. __extends(Light, _super);
  15141. /**
  15142. * Creates a Light object in the scene.
  15143. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15144. */
  15145. function Light(name, scene) {
  15146. var _this = _super.call(this, name, scene) || this;
  15147. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15148. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15149. _this.intensity = 1.0;
  15150. _this.range = Number.MAX_VALUE;
  15151. /**
  15152. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15153. * of light.
  15154. */
  15155. _this._photometricScale = 1.0;
  15156. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15157. _this._radius = 0.00001;
  15158. _this.renderPriority = 0;
  15159. /**
  15160. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15161. * the current shadow generator.
  15162. */
  15163. _this.shadowEnabled = true;
  15164. _this._excludeWithLayerMask = 0;
  15165. _this._includeOnlyWithLayerMask = 0;
  15166. _this._lightmapMode = 0;
  15167. _this._excludedMeshesIds = new Array();
  15168. _this._includedOnlyMeshesIds = new Array();
  15169. _this.getScene().addLight(_this);
  15170. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15171. _this._buildUniformLayout();
  15172. _this.includedOnlyMeshes = new Array();
  15173. _this.excludedMeshes = new Array();
  15174. _this._resyncMeshes();
  15175. return _this;
  15176. }
  15177. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15178. /**
  15179. * If every light affecting the material is in this lightmapMode,
  15180. * material.lightmapTexture adds or multiplies
  15181. * (depends on material.useLightmapAsShadowmap)
  15182. * after every other light calculations.
  15183. */
  15184. get: function () {
  15185. return Light._LIGHTMAP_DEFAULT;
  15186. },
  15187. enumerable: true,
  15188. configurable: true
  15189. });
  15190. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15191. /**
  15192. * material.lightmapTexture as only diffuse lighting from this light
  15193. * adds pnly specular lighting from this light
  15194. * adds dynamic shadows
  15195. */
  15196. get: function () {
  15197. return Light._LIGHTMAP_SPECULAR;
  15198. },
  15199. enumerable: true,
  15200. configurable: true
  15201. });
  15202. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15203. /**
  15204. * material.lightmapTexture as only lighting
  15205. * no light calculation from this light
  15206. * only adds dynamic shadows from this light
  15207. */
  15208. get: function () {
  15209. return Light._LIGHTMAP_SHADOWSONLY;
  15210. },
  15211. enumerable: true,
  15212. configurable: true
  15213. });
  15214. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15215. /**
  15216. * Each light type uses the default quantity according to its type:
  15217. * point/spot lights use luminous intensity
  15218. * directional lights use illuminance
  15219. */
  15220. get: function () {
  15221. return Light._INTENSITYMODE_AUTOMATIC;
  15222. },
  15223. enumerable: true,
  15224. configurable: true
  15225. });
  15226. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15227. /**
  15228. * lumen (lm)
  15229. */
  15230. get: function () {
  15231. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15232. },
  15233. enumerable: true,
  15234. configurable: true
  15235. });
  15236. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15237. /**
  15238. * candela (lm/sr)
  15239. */
  15240. get: function () {
  15241. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15242. },
  15243. enumerable: true,
  15244. configurable: true
  15245. });
  15246. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15247. /**
  15248. * lux (lm/m^2)
  15249. */
  15250. get: function () {
  15251. return Light._INTENSITYMODE_ILLUMINANCE;
  15252. },
  15253. enumerable: true,
  15254. configurable: true
  15255. });
  15256. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15257. /**
  15258. * nit (cd/m^2)
  15259. */
  15260. get: function () {
  15261. return Light._INTENSITYMODE_LUMINANCE;
  15262. },
  15263. enumerable: true,
  15264. configurable: true
  15265. });
  15266. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15267. /**
  15268. * Light type const id of the point light.
  15269. */
  15270. get: function () {
  15271. return Light._LIGHTTYPEID_POINTLIGHT;
  15272. },
  15273. enumerable: true,
  15274. configurable: true
  15275. });
  15276. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15277. /**
  15278. * Light type const id of the directional light.
  15279. */
  15280. get: function () {
  15281. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15282. },
  15283. enumerable: true,
  15284. configurable: true
  15285. });
  15286. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15287. /**
  15288. * Light type const id of the spot light.
  15289. */
  15290. get: function () {
  15291. return Light._LIGHTTYPEID_SPOTLIGHT;
  15292. },
  15293. enumerable: true,
  15294. configurable: true
  15295. });
  15296. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15297. /**
  15298. * Light type const id of the hemispheric light.
  15299. */
  15300. get: function () {
  15301. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15302. },
  15303. enumerable: true,
  15304. configurable: true
  15305. });
  15306. Object.defineProperty(Light.prototype, "intensityMode", {
  15307. /**
  15308. * Gets the photometric scale used to interpret the intensity.
  15309. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15310. */
  15311. get: function () {
  15312. return this._intensityMode;
  15313. },
  15314. /**
  15315. * Sets the photometric scale used to interpret the intensity.
  15316. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15317. */
  15318. set: function (value) {
  15319. this._intensityMode = value;
  15320. this._computePhotometricScale();
  15321. },
  15322. enumerable: true,
  15323. configurable: true
  15324. });
  15325. ;
  15326. ;
  15327. Object.defineProperty(Light.prototype, "radius", {
  15328. /**
  15329. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15330. */
  15331. get: function () {
  15332. return this._radius;
  15333. },
  15334. /**
  15335. * sets the light radius used by PBR Materials to simulate soft area lights.
  15336. */
  15337. set: function (value) {
  15338. this._radius = value;
  15339. this._computePhotometricScale();
  15340. },
  15341. enumerable: true,
  15342. configurable: true
  15343. });
  15344. ;
  15345. ;
  15346. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15347. get: function () {
  15348. return this._includedOnlyMeshes;
  15349. },
  15350. set: function (value) {
  15351. this._includedOnlyMeshes = value;
  15352. this._hookArrayForIncludedOnly(value);
  15353. },
  15354. enumerable: true,
  15355. configurable: true
  15356. });
  15357. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15358. get: function () {
  15359. return this._excludedMeshes;
  15360. },
  15361. set: function (value) {
  15362. this._excludedMeshes = value;
  15363. this._hookArrayForExcluded(value);
  15364. },
  15365. enumerable: true,
  15366. configurable: true
  15367. });
  15368. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15369. get: function () {
  15370. return this._excludeWithLayerMask;
  15371. },
  15372. set: function (value) {
  15373. this._excludeWithLayerMask = value;
  15374. this._resyncMeshes();
  15375. },
  15376. enumerable: true,
  15377. configurable: true
  15378. });
  15379. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15380. get: function () {
  15381. return this._includeOnlyWithLayerMask;
  15382. },
  15383. set: function (value) {
  15384. this._includeOnlyWithLayerMask = value;
  15385. this._resyncMeshes();
  15386. },
  15387. enumerable: true,
  15388. configurable: true
  15389. });
  15390. Object.defineProperty(Light.prototype, "lightmapMode", {
  15391. get: function () {
  15392. return this._lightmapMode;
  15393. },
  15394. set: function (value) {
  15395. if (this._lightmapMode === value) {
  15396. return;
  15397. }
  15398. this._lightmapMode = value;
  15399. this._markMeshesAsLightDirty();
  15400. },
  15401. enumerable: true,
  15402. configurable: true
  15403. });
  15404. Light.prototype._buildUniformLayout = function () {
  15405. // Overridden
  15406. };
  15407. /**
  15408. * Returns the string "Light".
  15409. */
  15410. Light.prototype.getClassName = function () {
  15411. return "Light";
  15412. };
  15413. /**
  15414. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15415. */
  15416. Light.prototype.toString = function (fullDetails) {
  15417. var ret = "Name: " + this.name;
  15418. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15419. if (this.animations) {
  15420. for (var i = 0; i < this.animations.length; i++) {
  15421. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15422. }
  15423. }
  15424. if (fullDetails) {
  15425. }
  15426. return ret;
  15427. };
  15428. /**
  15429. * Set the enabled state of this node.
  15430. * @param {boolean} value - the new enabled state
  15431. * @see isEnabled
  15432. */
  15433. Light.prototype.setEnabled = function (value) {
  15434. _super.prototype.setEnabled.call(this, value);
  15435. this._resyncMeshes();
  15436. };
  15437. /**
  15438. * Returns the Light associated shadow generator.
  15439. */
  15440. Light.prototype.getShadowGenerator = function () {
  15441. return this._shadowGenerator;
  15442. };
  15443. /**
  15444. * Returns a Vector3, the absolute light position in the World.
  15445. */
  15446. Light.prototype.getAbsolutePosition = function () {
  15447. return BABYLON.Vector3.Zero();
  15448. };
  15449. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15450. };
  15451. Light.prototype._getWorldMatrix = function () {
  15452. return BABYLON.Matrix.Identity();
  15453. };
  15454. /**
  15455. * Boolean : True if the light will affect the passed mesh.
  15456. */
  15457. Light.prototype.canAffectMesh = function (mesh) {
  15458. if (!mesh) {
  15459. return true;
  15460. }
  15461. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15462. return false;
  15463. }
  15464. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15465. return false;
  15466. }
  15467. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15468. return false;
  15469. }
  15470. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15471. return false;
  15472. }
  15473. return true;
  15474. };
  15475. /**
  15476. * Returns the light World matrix.
  15477. */
  15478. Light.prototype.getWorldMatrix = function () {
  15479. this._currentRenderId = this.getScene().getRenderId();
  15480. var worldMatrix = this._getWorldMatrix();
  15481. if (this.parent && this.parent.getWorldMatrix) {
  15482. if (!this._parentedWorldMatrix) {
  15483. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15484. }
  15485. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15486. this._markSyncedWithParent();
  15487. return this._parentedWorldMatrix;
  15488. }
  15489. return worldMatrix;
  15490. };
  15491. /**
  15492. * Sort function to order lights for rendering.
  15493. * @param a First Light object to compare to second.
  15494. * @param b Second Light object to compare first.
  15495. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15496. */
  15497. Light.compareLightsPriority = function (a, b) {
  15498. //shadow-casting lights have priority over non-shadow-casting lights
  15499. //the renderPrioirty is a secondary sort criterion
  15500. if (a.shadowEnabled !== b.shadowEnabled) {
  15501. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15502. }
  15503. return b.renderPriority - a.renderPriority;
  15504. };
  15505. /**
  15506. * Disposes the light.
  15507. */
  15508. Light.prototype.dispose = function () {
  15509. if (this._shadowGenerator) {
  15510. this._shadowGenerator.dispose();
  15511. this._shadowGenerator = null;
  15512. }
  15513. // Animations
  15514. this.getScene().stopAnimation(this);
  15515. // Remove from meshes
  15516. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15517. var mesh = _a[_i];
  15518. mesh._removeLightSource(this);
  15519. }
  15520. this._uniformBuffer.dispose();
  15521. // Remove from scene
  15522. this.getScene().removeLight(this);
  15523. _super.prototype.dispose.call(this);
  15524. };
  15525. /**
  15526. * Returns the light type ID (integer).
  15527. */
  15528. Light.prototype.getTypeID = function () {
  15529. return 0;
  15530. };
  15531. /**
  15532. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15533. */
  15534. Light.prototype.getScaledIntensity = function () {
  15535. return this._photometricScale * this.intensity;
  15536. };
  15537. /**
  15538. * Returns a new Light object, named "name", from the current one.
  15539. */
  15540. Light.prototype.clone = function (name) {
  15541. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15542. if (!constructor) {
  15543. return null;
  15544. }
  15545. return BABYLON.SerializationHelper.Clone(constructor, this);
  15546. };
  15547. /**
  15548. * Serializes the current light into a Serialization object.
  15549. * Returns the serialized object.
  15550. */
  15551. Light.prototype.serialize = function () {
  15552. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15553. // Type
  15554. serializationObject.type = this.getTypeID();
  15555. // Parent
  15556. if (this.parent) {
  15557. serializationObject.parentId = this.parent.id;
  15558. }
  15559. // Inclusion / exclusions
  15560. if (this.excludedMeshes.length > 0) {
  15561. serializationObject.excludedMeshesIds = [];
  15562. this.excludedMeshes.forEach(function (mesh) {
  15563. serializationObject.excludedMeshesIds.push(mesh.id);
  15564. });
  15565. }
  15566. if (this.includedOnlyMeshes.length > 0) {
  15567. serializationObject.includedOnlyMeshesIds = [];
  15568. this.includedOnlyMeshes.forEach(function (mesh) {
  15569. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15570. });
  15571. }
  15572. // Animations
  15573. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15574. serializationObject.ranges = this.serializeAnimationRanges();
  15575. return serializationObject;
  15576. };
  15577. /**
  15578. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15579. * This new light is named "name" and added to the passed scene.
  15580. */
  15581. Light.GetConstructorFromName = function (type, name, scene) {
  15582. switch (type) {
  15583. case 0:
  15584. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15585. case 1:
  15586. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15587. case 2:
  15588. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15589. case 3:
  15590. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15591. }
  15592. return null;
  15593. };
  15594. /**
  15595. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15596. */
  15597. Light.Parse = function (parsedLight, scene) {
  15598. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15599. if (!constructor) {
  15600. return null;
  15601. }
  15602. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15603. // Inclusion / exclusions
  15604. if (parsedLight.excludedMeshesIds) {
  15605. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15606. }
  15607. if (parsedLight.includedOnlyMeshesIds) {
  15608. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15609. }
  15610. // Parent
  15611. if (parsedLight.parentId) {
  15612. light._waitingParentId = parsedLight.parentId;
  15613. }
  15614. // Animations
  15615. if (parsedLight.animations) {
  15616. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15617. var parsedAnimation = parsedLight.animations[animationIndex];
  15618. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15619. }
  15620. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15621. }
  15622. if (parsedLight.autoAnimate) {
  15623. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15624. }
  15625. return light;
  15626. };
  15627. Light.prototype._hookArrayForExcluded = function (array) {
  15628. var _this = this;
  15629. var oldPush = array.push;
  15630. array.push = function () {
  15631. var items = [];
  15632. for (var _i = 0; _i < arguments.length; _i++) {
  15633. items[_i] = arguments[_i];
  15634. }
  15635. var result = oldPush.apply(array, items);
  15636. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15637. var item = items_1[_a];
  15638. item._resyncLighSource(_this);
  15639. }
  15640. return result;
  15641. };
  15642. var oldSplice = array.splice;
  15643. array.splice = function (index, deleteCount) {
  15644. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15645. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15646. var item = deleted_1[_i];
  15647. item._resyncLighSource(_this);
  15648. }
  15649. return deleted;
  15650. };
  15651. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15652. var item = array_1[_i];
  15653. item._resyncLighSource(this);
  15654. }
  15655. };
  15656. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15657. var _this = this;
  15658. var oldPush = array.push;
  15659. array.push = function () {
  15660. var items = [];
  15661. for (var _i = 0; _i < arguments.length; _i++) {
  15662. items[_i] = arguments[_i];
  15663. }
  15664. var result = oldPush.apply(array, items);
  15665. _this._resyncMeshes();
  15666. return result;
  15667. };
  15668. var oldSplice = array.splice;
  15669. array.splice = function (index, deleteCount) {
  15670. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15671. _this._resyncMeshes();
  15672. return deleted;
  15673. };
  15674. this._resyncMeshes();
  15675. };
  15676. Light.prototype._resyncMeshes = function () {
  15677. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15678. var mesh = _a[_i];
  15679. mesh._resyncLighSource(this);
  15680. }
  15681. };
  15682. Light.prototype._markMeshesAsLightDirty = function () {
  15683. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15684. var mesh = _a[_i];
  15685. if (mesh._lightSources.indexOf(this) !== -1) {
  15686. mesh._markSubMeshesAsLightDirty();
  15687. }
  15688. }
  15689. };
  15690. /**
  15691. * Recomputes the cached photometric scale if needed.
  15692. */
  15693. Light.prototype._computePhotometricScale = function () {
  15694. this._photometricScale = this._getPhotometricScale();
  15695. this.getScene().resetCachedMaterial();
  15696. };
  15697. /**
  15698. * Returns the Photometric Scale according to the light type and intensity mode.
  15699. */
  15700. Light.prototype._getPhotometricScale = function () {
  15701. var photometricScale = 0.0;
  15702. var lightTypeID = this.getTypeID();
  15703. //get photometric mode
  15704. var photometricMode = this.intensityMode;
  15705. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15706. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15707. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15708. }
  15709. else {
  15710. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15711. }
  15712. }
  15713. //compute photometric scale
  15714. switch (lightTypeID) {
  15715. case Light.LIGHTTYPEID_POINTLIGHT:
  15716. case Light.LIGHTTYPEID_SPOTLIGHT:
  15717. switch (photometricMode) {
  15718. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15719. photometricScale = 1.0 / (4.0 * Math.PI);
  15720. break;
  15721. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15722. photometricScale = 1.0;
  15723. break;
  15724. case Light.INTENSITYMODE_LUMINANCE:
  15725. photometricScale = this.radius * this.radius;
  15726. break;
  15727. }
  15728. break;
  15729. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15730. switch (photometricMode) {
  15731. case Light.INTENSITYMODE_ILLUMINANCE:
  15732. photometricScale = 1.0;
  15733. break;
  15734. case Light.INTENSITYMODE_LUMINANCE:
  15735. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15736. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15737. var apexAngleRadians = this.radius;
  15738. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15739. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15740. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15741. photometricScale = solidAngle;
  15742. break;
  15743. }
  15744. break;
  15745. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15746. // No fall off in hemisperic light.
  15747. photometricScale = 1.0;
  15748. break;
  15749. }
  15750. return photometricScale;
  15751. };
  15752. Light.prototype._reorderLightsInScene = function () {
  15753. var scene = this.getScene();
  15754. if (this._renderPriority != 0) {
  15755. scene.requireLightSorting = true;
  15756. }
  15757. this.getScene().sortLightsByPriority();
  15758. };
  15759. //lightmapMode Consts
  15760. Light._LIGHTMAP_DEFAULT = 0;
  15761. Light._LIGHTMAP_SPECULAR = 1;
  15762. Light._LIGHTMAP_SHADOWSONLY = 2;
  15763. // Intensity Mode Consts
  15764. Light._INTENSITYMODE_AUTOMATIC = 0;
  15765. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15766. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15767. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15768. Light._INTENSITYMODE_LUMINANCE = 4;
  15769. // Light types ids const.
  15770. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15771. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15772. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15773. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15774. __decorate([
  15775. BABYLON.serializeAsColor3()
  15776. ], Light.prototype, "diffuse", void 0);
  15777. __decorate([
  15778. BABYLON.serializeAsColor3()
  15779. ], Light.prototype, "specular", void 0);
  15780. __decorate([
  15781. BABYLON.serialize()
  15782. ], Light.prototype, "intensity", void 0);
  15783. __decorate([
  15784. BABYLON.serialize()
  15785. ], Light.prototype, "range", void 0);
  15786. __decorate([
  15787. BABYLON.serialize()
  15788. ], Light.prototype, "intensityMode", null);
  15789. __decorate([
  15790. BABYLON.serialize()
  15791. ], Light.prototype, "radius", null);
  15792. __decorate([
  15793. BABYLON.serialize()
  15794. ], Light.prototype, "_renderPriority", void 0);
  15795. __decorate([
  15796. BABYLON.expandToProperty("_reorderLightsInScene")
  15797. ], Light.prototype, "renderPriority", void 0);
  15798. __decorate([
  15799. BABYLON.serialize()
  15800. ], Light.prototype, "shadowEnabled", void 0);
  15801. __decorate([
  15802. BABYLON.serialize("excludeWithLayerMask")
  15803. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15804. __decorate([
  15805. BABYLON.serialize("includeOnlyWithLayerMask")
  15806. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15807. __decorate([
  15808. BABYLON.serialize("lightmapMode")
  15809. ], Light.prototype, "_lightmapMode", void 0);
  15810. return Light;
  15811. }(BABYLON.Node));
  15812. BABYLON.Light = Light;
  15813. })(BABYLON || (BABYLON = {}));
  15814. //# sourceMappingURL=babylon.light.js.map
  15815. var BABYLON;
  15816. (function (BABYLON) {
  15817. var Camera = /** @class */ (function (_super) {
  15818. __extends(Camera, _super);
  15819. function Camera(name, position, scene) {
  15820. var _this = _super.call(this, name, scene) || this;
  15821. _this.upVector = BABYLON.Vector3.Up();
  15822. _this.orthoLeft = null;
  15823. _this.orthoRight = null;
  15824. _this.orthoBottom = null;
  15825. _this.orthoTop = null;
  15826. _this.fov = 0.8;
  15827. _this.minZ = 1;
  15828. _this.maxZ = 10000.0;
  15829. _this.inertia = 0.9;
  15830. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15831. _this.isIntermediate = false;
  15832. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15833. _this.layerMask = 0x0FFFFFFF;
  15834. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15835. // Camera rig members
  15836. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15837. _this._rigCameras = new Array();
  15838. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15839. _this._skipRendering = false;
  15840. _this.customRenderTargets = new Array();
  15841. // Observables
  15842. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15843. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15844. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15845. _this.onRestoreStateObservable = new BABYLON.Observable();
  15846. // Cache
  15847. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15848. _this._projectionMatrix = new BABYLON.Matrix();
  15849. _this._doNotComputeProjectionMatrix = false;
  15850. _this._postProcesses = new Array();
  15851. _this._transformMatrix = BABYLON.Matrix.Zero();
  15852. _this._activeMeshes = new BABYLON.SmartArray(256);
  15853. _this._globalPosition = BABYLON.Vector3.Zero();
  15854. _this._refreshFrustumPlanes = true;
  15855. _this.getScene().addCamera(_this);
  15856. if (!_this.getScene().activeCamera) {
  15857. _this.getScene().activeCamera = _this;
  15858. }
  15859. _this.position = position;
  15860. return _this;
  15861. }
  15862. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15863. get: function () {
  15864. return Camera._PERSPECTIVE_CAMERA;
  15865. },
  15866. enumerable: true,
  15867. configurable: true
  15868. });
  15869. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15870. get: function () {
  15871. return Camera._ORTHOGRAPHIC_CAMERA;
  15872. },
  15873. enumerable: true,
  15874. configurable: true
  15875. });
  15876. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15877. get: function () {
  15878. return Camera._FOVMODE_VERTICAL_FIXED;
  15879. },
  15880. enumerable: true,
  15881. configurable: true
  15882. });
  15883. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15884. get: function () {
  15885. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15886. },
  15887. enumerable: true,
  15888. configurable: true
  15889. });
  15890. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15891. get: function () {
  15892. return Camera._RIG_MODE_NONE;
  15893. },
  15894. enumerable: true,
  15895. configurable: true
  15896. });
  15897. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15898. get: function () {
  15899. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15900. },
  15901. enumerable: true,
  15902. configurable: true
  15903. });
  15904. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15905. get: function () {
  15906. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15907. },
  15908. enumerable: true,
  15909. configurable: true
  15910. });
  15911. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15912. get: function () {
  15913. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15914. },
  15915. enumerable: true,
  15916. configurable: true
  15917. });
  15918. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15919. get: function () {
  15920. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15921. },
  15922. enumerable: true,
  15923. configurable: true
  15924. });
  15925. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15926. get: function () {
  15927. return Camera._RIG_MODE_VR;
  15928. },
  15929. enumerable: true,
  15930. configurable: true
  15931. });
  15932. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15933. get: function () {
  15934. return Camera._RIG_MODE_WEBVR;
  15935. },
  15936. enumerable: true,
  15937. configurable: true
  15938. });
  15939. /**
  15940. * Store current camera state (fov, position, etc..)
  15941. */
  15942. Camera.prototype.storeState = function () {
  15943. this._stateStored = true;
  15944. this._storedFov = this.fov;
  15945. return this;
  15946. };
  15947. /**
  15948. * Restores the camera state values if it has been stored. You must call storeState() first
  15949. */
  15950. Camera.prototype._restoreStateValues = function () {
  15951. if (!this._stateStored) {
  15952. return false;
  15953. }
  15954. this.fov = this._storedFov;
  15955. return true;
  15956. };
  15957. /**
  15958. * Restored camera state. You must call storeState() first
  15959. */
  15960. Camera.prototype.restoreState = function () {
  15961. if (this._restoreStateValues()) {
  15962. this.onRestoreStateObservable.notifyObservers(this);
  15963. return true;
  15964. }
  15965. return false;
  15966. };
  15967. Camera.prototype.getClassName = function () {
  15968. return "Camera";
  15969. };
  15970. /**
  15971. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15972. */
  15973. Camera.prototype.toString = function (fullDetails) {
  15974. var ret = "Name: " + this.name;
  15975. ret += ", type: " + this.getClassName();
  15976. if (this.animations) {
  15977. for (var i = 0; i < this.animations.length; i++) {
  15978. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15979. }
  15980. }
  15981. if (fullDetails) {
  15982. }
  15983. return ret;
  15984. };
  15985. Object.defineProperty(Camera.prototype, "globalPosition", {
  15986. get: function () {
  15987. return this._globalPosition;
  15988. },
  15989. enumerable: true,
  15990. configurable: true
  15991. });
  15992. Camera.prototype.getActiveMeshes = function () {
  15993. return this._activeMeshes;
  15994. };
  15995. Camera.prototype.isActiveMesh = function (mesh) {
  15996. return (this._activeMeshes.indexOf(mesh) !== -1);
  15997. };
  15998. //Cache
  15999. Camera.prototype._initCache = function () {
  16000. _super.prototype._initCache.call(this);
  16001. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16002. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16003. this._cache.mode = undefined;
  16004. this._cache.minZ = undefined;
  16005. this._cache.maxZ = undefined;
  16006. this._cache.fov = undefined;
  16007. this._cache.fovMode = undefined;
  16008. this._cache.aspectRatio = undefined;
  16009. this._cache.orthoLeft = undefined;
  16010. this._cache.orthoRight = undefined;
  16011. this._cache.orthoBottom = undefined;
  16012. this._cache.orthoTop = undefined;
  16013. this._cache.renderWidth = undefined;
  16014. this._cache.renderHeight = undefined;
  16015. };
  16016. Camera.prototype._updateCache = function (ignoreParentClass) {
  16017. if (!ignoreParentClass) {
  16018. _super.prototype._updateCache.call(this);
  16019. }
  16020. this._cache.position.copyFrom(this.position);
  16021. this._cache.upVector.copyFrom(this.upVector);
  16022. };
  16023. // Synchronized
  16024. Camera.prototype._isSynchronized = function () {
  16025. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16026. };
  16027. Camera.prototype._isSynchronizedViewMatrix = function () {
  16028. if (!_super.prototype._isSynchronized.call(this))
  16029. return false;
  16030. return this._cache.position.equals(this.position)
  16031. && this._cache.upVector.equals(this.upVector)
  16032. && this.isSynchronizedWithParent();
  16033. };
  16034. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16035. var check = this._cache.mode === this.mode
  16036. && this._cache.minZ === this.minZ
  16037. && this._cache.maxZ === this.maxZ;
  16038. if (!check) {
  16039. return false;
  16040. }
  16041. var engine = this.getEngine();
  16042. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16043. check = this._cache.fov === this.fov
  16044. && this._cache.fovMode === this.fovMode
  16045. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16046. }
  16047. else {
  16048. check = this._cache.orthoLeft === this.orthoLeft
  16049. && this._cache.orthoRight === this.orthoRight
  16050. && this._cache.orthoBottom === this.orthoBottom
  16051. && this._cache.orthoTop === this.orthoTop
  16052. && this._cache.renderWidth === engine.getRenderWidth()
  16053. && this._cache.renderHeight === engine.getRenderHeight();
  16054. }
  16055. return check;
  16056. };
  16057. // Controls
  16058. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16059. };
  16060. Camera.prototype.detachControl = function (element) {
  16061. };
  16062. Camera.prototype.update = function () {
  16063. this._checkInputs();
  16064. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16065. this._updateRigCameras();
  16066. }
  16067. };
  16068. Camera.prototype._checkInputs = function () {
  16069. this.onAfterCheckInputsObservable.notifyObservers(this);
  16070. };
  16071. Object.defineProperty(Camera.prototype, "rigCameras", {
  16072. get: function () {
  16073. return this._rigCameras;
  16074. },
  16075. enumerable: true,
  16076. configurable: true
  16077. });
  16078. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16079. get: function () {
  16080. return this._rigPostProcess;
  16081. },
  16082. enumerable: true,
  16083. configurable: true
  16084. });
  16085. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16086. // invalidate framebuffer
  16087. if (this._postProcesses.length > 0) {
  16088. this._postProcesses[0].markTextureDirty();
  16089. }
  16090. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16091. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16092. var cam = this._rigCameras[i];
  16093. var rigPostProcess = cam._rigPostProcess;
  16094. // for VR rig, there does not have to be a post process
  16095. if (rigPostProcess) {
  16096. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16097. if (isPass) {
  16098. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16099. cam.isIntermediate = this._postProcesses.length === 0;
  16100. }
  16101. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16102. rigPostProcess.markTextureDirty();
  16103. }
  16104. else {
  16105. cam._postProcesses = this._postProcesses.slice(0);
  16106. }
  16107. }
  16108. };
  16109. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16110. if (insertAt === void 0) { insertAt = null; }
  16111. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16112. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16113. return 0;
  16114. }
  16115. if (insertAt == null || insertAt < 0) {
  16116. this._postProcesses.push(postProcess);
  16117. }
  16118. else {
  16119. this._postProcesses.splice(insertAt, 0, postProcess);
  16120. }
  16121. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16122. return this._postProcesses.indexOf(postProcess);
  16123. };
  16124. Camera.prototype.detachPostProcess = function (postProcess) {
  16125. var idx = this._postProcesses.indexOf(postProcess);
  16126. if (idx !== -1) {
  16127. this._postProcesses.splice(idx, 1);
  16128. }
  16129. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16130. };
  16131. Camera.prototype.getWorldMatrix = function () {
  16132. if (!this._worldMatrix) {
  16133. this._worldMatrix = BABYLON.Matrix.Identity();
  16134. }
  16135. var viewMatrix = this.getViewMatrix();
  16136. viewMatrix.invertToRef(this._worldMatrix);
  16137. return this._worldMatrix;
  16138. };
  16139. Camera.prototype._getViewMatrix = function () {
  16140. return BABYLON.Matrix.Identity();
  16141. };
  16142. Camera.prototype.getViewMatrix = function (force) {
  16143. if (!force && this._isSynchronizedViewMatrix()) {
  16144. return this._computedViewMatrix;
  16145. }
  16146. this.updateCache();
  16147. this._computedViewMatrix = this._getViewMatrix();
  16148. this._currentRenderId = this.getScene().getRenderId();
  16149. this._refreshFrustumPlanes = true;
  16150. if (!this.parent || !this.parent.getWorldMatrix) {
  16151. this._globalPosition.copyFrom(this.position);
  16152. }
  16153. else {
  16154. if (!this._worldMatrix) {
  16155. this._worldMatrix = BABYLON.Matrix.Identity();
  16156. }
  16157. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16158. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16159. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16160. this._computedViewMatrix.invert();
  16161. this._markSyncedWithParent();
  16162. }
  16163. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16164. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16165. }
  16166. this.onViewMatrixChangedObservable.notifyObservers(this);
  16167. return this._computedViewMatrix;
  16168. };
  16169. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16170. this._doNotComputeProjectionMatrix = true;
  16171. if (projection !== undefined) {
  16172. this._projectionMatrix = projection;
  16173. }
  16174. };
  16175. ;
  16176. Camera.prototype.unfreezeProjectionMatrix = function () {
  16177. this._doNotComputeProjectionMatrix = false;
  16178. };
  16179. ;
  16180. Camera.prototype.getProjectionMatrix = function (force) {
  16181. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16182. return this._projectionMatrix;
  16183. }
  16184. // Cache
  16185. this._cache.mode = this.mode;
  16186. this._cache.minZ = this.minZ;
  16187. this._cache.maxZ = this.maxZ;
  16188. // Matrix
  16189. this._refreshFrustumPlanes = true;
  16190. var engine = this.getEngine();
  16191. var scene = this.getScene();
  16192. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16193. this._cache.fov = this.fov;
  16194. this._cache.fovMode = this.fovMode;
  16195. this._cache.aspectRatio = engine.getAspectRatio(this);
  16196. if (this.minZ <= 0) {
  16197. this.minZ = 0.1;
  16198. }
  16199. if (scene.useRightHandedSystem) {
  16200. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16201. }
  16202. else {
  16203. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16204. }
  16205. }
  16206. else {
  16207. var halfWidth = engine.getRenderWidth() / 2.0;
  16208. var halfHeight = engine.getRenderHeight() / 2.0;
  16209. if (scene.useRightHandedSystem) {
  16210. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16211. }
  16212. else {
  16213. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16214. }
  16215. this._cache.orthoLeft = this.orthoLeft;
  16216. this._cache.orthoRight = this.orthoRight;
  16217. this._cache.orthoBottom = this.orthoBottom;
  16218. this._cache.orthoTop = this.orthoTop;
  16219. this._cache.renderWidth = engine.getRenderWidth();
  16220. this._cache.renderHeight = engine.getRenderHeight();
  16221. }
  16222. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16223. return this._projectionMatrix;
  16224. };
  16225. Camera.prototype.getTranformationMatrix = function () {
  16226. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16227. return this._transformMatrix;
  16228. };
  16229. Camera.prototype.updateFrustumPlanes = function () {
  16230. if (!this._refreshFrustumPlanes) {
  16231. return;
  16232. }
  16233. this.getTranformationMatrix();
  16234. if (!this._frustumPlanes) {
  16235. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16236. }
  16237. else {
  16238. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16239. }
  16240. this._refreshFrustumPlanes = false;
  16241. };
  16242. Camera.prototype.isInFrustum = function (target) {
  16243. this.updateFrustumPlanes();
  16244. return target.isInFrustum(this._frustumPlanes);
  16245. };
  16246. Camera.prototype.isCompletelyInFrustum = function (target) {
  16247. this.updateFrustumPlanes();
  16248. return target.isCompletelyInFrustum(this._frustumPlanes);
  16249. };
  16250. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16251. if (length === void 0) { length = 100; }
  16252. if (!transform) {
  16253. transform = this.getWorldMatrix();
  16254. }
  16255. if (!origin) {
  16256. origin = this.position;
  16257. }
  16258. var forward = new BABYLON.Vector3(0, 0, 1);
  16259. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16260. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16261. return new BABYLON.Ray(origin, direction, length);
  16262. };
  16263. Camera.prototype.dispose = function () {
  16264. // Observables
  16265. this.onViewMatrixChangedObservable.clear();
  16266. this.onProjectionMatrixChangedObservable.clear();
  16267. this.onAfterCheckInputsObservable.clear();
  16268. this.onRestoreStateObservable.clear();
  16269. // Inputs
  16270. if (this.inputs) {
  16271. this.inputs.clear();
  16272. }
  16273. // Animations
  16274. this.getScene().stopAnimation(this);
  16275. // Remove from scene
  16276. this.getScene().removeCamera(this);
  16277. while (this._rigCameras.length > 0) {
  16278. var camera = this._rigCameras.pop();
  16279. if (camera) {
  16280. camera.dispose();
  16281. }
  16282. }
  16283. // Postprocesses
  16284. if (this._rigPostProcess) {
  16285. this._rigPostProcess.dispose(this);
  16286. this._rigPostProcess = null;
  16287. this._postProcesses = [];
  16288. }
  16289. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16290. this._rigPostProcess = null;
  16291. this._postProcesses = [];
  16292. }
  16293. else {
  16294. var i = this._postProcesses.length;
  16295. while (--i >= 0) {
  16296. this._postProcesses[i].dispose(this);
  16297. }
  16298. }
  16299. // Render targets
  16300. var i = this.customRenderTargets.length;
  16301. while (--i >= 0) {
  16302. this.customRenderTargets[i].dispose();
  16303. }
  16304. this.customRenderTargets = [];
  16305. // Active Meshes
  16306. this._activeMeshes.dispose();
  16307. _super.prototype.dispose.call(this);
  16308. };
  16309. Object.defineProperty(Camera.prototype, "leftCamera", {
  16310. // ---- Camera rigs section ----
  16311. get: function () {
  16312. if (this._rigCameras.length < 1) {
  16313. return null;
  16314. }
  16315. return this._rigCameras[0];
  16316. },
  16317. enumerable: true,
  16318. configurable: true
  16319. });
  16320. Object.defineProperty(Camera.prototype, "rightCamera", {
  16321. get: function () {
  16322. if (this._rigCameras.length < 2) {
  16323. return null;
  16324. }
  16325. return this._rigCameras[1];
  16326. },
  16327. enumerable: true,
  16328. configurable: true
  16329. });
  16330. Camera.prototype.getLeftTarget = function () {
  16331. if (this._rigCameras.length < 1) {
  16332. return null;
  16333. }
  16334. return this._rigCameras[0].getTarget();
  16335. };
  16336. Camera.prototype.getRightTarget = function () {
  16337. if (this._rigCameras.length < 2) {
  16338. return null;
  16339. }
  16340. return this._rigCameras[1].getTarget();
  16341. };
  16342. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16343. if (this.cameraRigMode === mode) {
  16344. return;
  16345. }
  16346. while (this._rigCameras.length > 0) {
  16347. var camera = this._rigCameras.pop();
  16348. if (camera) {
  16349. camera.dispose();
  16350. }
  16351. }
  16352. this.cameraRigMode = mode;
  16353. this._cameraRigParams = {};
  16354. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16355. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16356. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16357. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16358. // create the rig cameras, unless none
  16359. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16360. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16361. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16362. if (leftCamera && rightCamera) {
  16363. this._rigCameras.push(leftCamera);
  16364. this._rigCameras.push(rightCamera);
  16365. }
  16366. }
  16367. switch (this.cameraRigMode) {
  16368. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16369. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16370. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16371. break;
  16372. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16373. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16374. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16375. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16376. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16377. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16378. break;
  16379. case Camera.RIG_MODE_VR:
  16380. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16381. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16382. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16383. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16384. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16385. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16386. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16387. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16388. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16389. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16390. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16391. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16392. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16393. if (metrics.compensateDistortion) {
  16394. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16395. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16396. }
  16397. break;
  16398. case Camera.RIG_MODE_WEBVR:
  16399. if (rigParams.vrDisplay) {
  16400. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16401. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16402. //Left eye
  16403. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16404. this._rigCameras[0].setCameraRigParameter("left", true);
  16405. //leaving this for future reference
  16406. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16407. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16408. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16409. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16410. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16411. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16412. this._rigCameras[0].parent = this;
  16413. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16414. //Right eye
  16415. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16416. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16417. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16418. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16419. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16420. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16421. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16422. this._rigCameras[1].parent = this;
  16423. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16424. if (Camera.UseAlternateWebVRRendering) {
  16425. this._rigCameras[1]._skipRendering = true;
  16426. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16427. }
  16428. }
  16429. break;
  16430. }
  16431. this._cascadePostProcessesToRigCams();
  16432. this.update();
  16433. };
  16434. Camera.prototype._getVRProjectionMatrix = function () {
  16435. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16436. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16437. return this._projectionMatrix;
  16438. };
  16439. Camera.prototype._updateCameraRotationMatrix = function () {
  16440. //Here for WebVR
  16441. };
  16442. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16443. //Here for WebVR
  16444. };
  16445. /**
  16446. * This function MUST be overwritten by the different WebVR cameras available.
  16447. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16448. */
  16449. Camera.prototype._getWebVRProjectionMatrix = function () {
  16450. return BABYLON.Matrix.Identity();
  16451. };
  16452. /**
  16453. * This function MUST be overwritten by the different WebVR cameras available.
  16454. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16455. */
  16456. Camera.prototype._getWebVRViewMatrix = function () {
  16457. return BABYLON.Matrix.Identity();
  16458. };
  16459. Camera.prototype.setCameraRigParameter = function (name, value) {
  16460. if (!this._cameraRigParams) {
  16461. this._cameraRigParams = {};
  16462. }
  16463. this._cameraRigParams[name] = value;
  16464. //provisionnally:
  16465. if (name === "interaxialDistance") {
  16466. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16467. }
  16468. };
  16469. /**
  16470. * needs to be overridden by children so sub has required properties to be copied
  16471. */
  16472. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16473. return null;
  16474. };
  16475. /**
  16476. * May need to be overridden by children
  16477. */
  16478. Camera.prototype._updateRigCameras = function () {
  16479. for (var i = 0; i < this._rigCameras.length; i++) {
  16480. this._rigCameras[i].minZ = this.minZ;
  16481. this._rigCameras[i].maxZ = this.maxZ;
  16482. this._rigCameras[i].fov = this.fov;
  16483. }
  16484. // only update viewport when ANAGLYPH
  16485. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16486. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16487. }
  16488. };
  16489. Camera.prototype._setupInputs = function () {
  16490. };
  16491. Camera.prototype.serialize = function () {
  16492. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16493. // Type
  16494. serializationObject.type = this.getClassName();
  16495. // Parent
  16496. if (this.parent) {
  16497. serializationObject.parentId = this.parent.id;
  16498. }
  16499. if (this.inputs) {
  16500. this.inputs.serialize(serializationObject);
  16501. }
  16502. // Animations
  16503. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16504. serializationObject.ranges = this.serializeAnimationRanges();
  16505. return serializationObject;
  16506. };
  16507. Camera.prototype.clone = function (name) {
  16508. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16509. };
  16510. Camera.prototype.getDirection = function (localAxis) {
  16511. var result = BABYLON.Vector3.Zero();
  16512. this.getDirectionToRef(localAxis, result);
  16513. return result;
  16514. };
  16515. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16516. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16517. };
  16518. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16519. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16520. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16521. switch (type) {
  16522. case "ArcRotateCamera":
  16523. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16524. case "DeviceOrientationCamera":
  16525. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16526. case "FollowCamera":
  16527. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16528. case "ArcFollowCamera":
  16529. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16530. case "GamepadCamera":
  16531. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16532. case "TouchCamera":
  16533. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16534. case "VirtualJoysticksCamera":
  16535. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16536. case "WebVRFreeCamera":
  16537. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16538. case "WebVRGamepadCamera":
  16539. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16540. case "VRDeviceOrientationFreeCamera":
  16541. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16542. case "VRDeviceOrientationGamepadCamera":
  16543. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16544. case "AnaglyphArcRotateCamera":
  16545. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16546. case "AnaglyphFreeCamera":
  16547. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16548. case "AnaglyphGamepadCamera":
  16549. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16550. case "AnaglyphUniversalCamera":
  16551. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16552. case "StereoscopicArcRotateCamera":
  16553. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16554. case "StereoscopicFreeCamera":
  16555. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16556. case "StereoscopicGamepadCamera":
  16557. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16558. case "StereoscopicUniversalCamera":
  16559. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16560. case "FreeCamera":// Forcing Universal here
  16561. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16562. default:// Universal Camera is the default value
  16563. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16564. }
  16565. };
  16566. Camera.Parse = function (parsedCamera, scene) {
  16567. var type = parsedCamera.type;
  16568. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16569. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16570. // Parent
  16571. if (parsedCamera.parentId) {
  16572. camera._waitingParentId = parsedCamera.parentId;
  16573. }
  16574. //If camera has an input manager, let it parse inputs settings
  16575. if (camera.inputs) {
  16576. camera.inputs.parse(parsedCamera);
  16577. camera._setupInputs();
  16578. }
  16579. if (camera.setPosition) {
  16580. camera.position.copyFromFloats(0, 0, 0);
  16581. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16582. }
  16583. // Target
  16584. if (parsedCamera.target) {
  16585. if (camera.setTarget) {
  16586. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16587. }
  16588. }
  16589. // Apply 3d rig, when found
  16590. if (parsedCamera.cameraRigMode) {
  16591. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16592. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16593. }
  16594. // Animations
  16595. if (parsedCamera.animations) {
  16596. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16597. var parsedAnimation = parsedCamera.animations[animationIndex];
  16598. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16599. }
  16600. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16601. }
  16602. if (parsedCamera.autoAnimate) {
  16603. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16604. }
  16605. return camera;
  16606. };
  16607. // Statics
  16608. Camera._PERSPECTIVE_CAMERA = 0;
  16609. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16610. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16611. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16612. Camera._RIG_MODE_NONE = 0;
  16613. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16614. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16615. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16616. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16617. Camera._RIG_MODE_VR = 20;
  16618. Camera._RIG_MODE_WEBVR = 21;
  16619. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16620. Camera.UseAlternateWebVRRendering = false;
  16621. __decorate([
  16622. BABYLON.serializeAsVector3()
  16623. ], Camera.prototype, "position", void 0);
  16624. __decorate([
  16625. BABYLON.serializeAsVector3()
  16626. ], Camera.prototype, "upVector", void 0);
  16627. __decorate([
  16628. BABYLON.serialize()
  16629. ], Camera.prototype, "orthoLeft", void 0);
  16630. __decorate([
  16631. BABYLON.serialize()
  16632. ], Camera.prototype, "orthoRight", void 0);
  16633. __decorate([
  16634. BABYLON.serialize()
  16635. ], Camera.prototype, "orthoBottom", void 0);
  16636. __decorate([
  16637. BABYLON.serialize()
  16638. ], Camera.prototype, "orthoTop", void 0);
  16639. __decorate([
  16640. BABYLON.serialize()
  16641. ], Camera.prototype, "fov", void 0);
  16642. __decorate([
  16643. BABYLON.serialize()
  16644. ], Camera.prototype, "minZ", void 0);
  16645. __decorate([
  16646. BABYLON.serialize()
  16647. ], Camera.prototype, "maxZ", void 0);
  16648. __decorate([
  16649. BABYLON.serialize()
  16650. ], Camera.prototype, "inertia", void 0);
  16651. __decorate([
  16652. BABYLON.serialize()
  16653. ], Camera.prototype, "mode", void 0);
  16654. __decorate([
  16655. BABYLON.serialize()
  16656. ], Camera.prototype, "layerMask", void 0);
  16657. __decorate([
  16658. BABYLON.serialize()
  16659. ], Camera.prototype, "fovMode", void 0);
  16660. __decorate([
  16661. BABYLON.serialize()
  16662. ], Camera.prototype, "cameraRigMode", void 0);
  16663. __decorate([
  16664. BABYLON.serialize()
  16665. ], Camera.prototype, "interaxialDistance", void 0);
  16666. __decorate([
  16667. BABYLON.serialize()
  16668. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16669. return Camera;
  16670. }(BABYLON.Node));
  16671. BABYLON.Camera = Camera;
  16672. })(BABYLON || (BABYLON = {}));
  16673. //# sourceMappingURL=babylon.camera.js.map
  16674. var BABYLON;
  16675. (function (BABYLON) {
  16676. var RenderingManager = /** @class */ (function () {
  16677. function RenderingManager(scene) {
  16678. this._renderingGroups = new Array();
  16679. this._autoClearDepthStencil = {};
  16680. this._customOpaqueSortCompareFn = {};
  16681. this._customAlphaTestSortCompareFn = {};
  16682. this._customTransparentSortCompareFn = {};
  16683. this._renderinGroupInfo = null;
  16684. this._scene = scene;
  16685. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16686. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16687. }
  16688. }
  16689. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16690. if (depth === void 0) { depth = true; }
  16691. if (stencil === void 0) { stencil = true; }
  16692. if (this._depthStencilBufferAlreadyCleaned) {
  16693. return;
  16694. }
  16695. this._scene.getEngine().clear(null, false, depth, stencil);
  16696. this._depthStencilBufferAlreadyCleaned = true;
  16697. };
  16698. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16699. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16700. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16701. var info = null;
  16702. if (observable) {
  16703. if (!this._renderinGroupInfo) {
  16704. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16705. }
  16706. info = this._renderinGroupInfo;
  16707. info.scene = this._scene;
  16708. info.camera = this._scene.activeCamera;
  16709. }
  16710. // Dispatch sprites
  16711. if (renderSprites) {
  16712. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16713. var manager = this._scene.spriteManagers[index];
  16714. this.dispatchSprites(manager);
  16715. }
  16716. }
  16717. // Render
  16718. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16719. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16720. var renderingGroup = this._renderingGroups[index];
  16721. if (!renderingGroup && !observable)
  16722. continue;
  16723. this._currentIndex = index;
  16724. var renderingGroupMask = 0;
  16725. // Fire PRECLEAR stage
  16726. if (observable && info) {
  16727. renderingGroupMask = Math.pow(2, index);
  16728. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16729. info.renderingGroupId = index;
  16730. observable.notifyObservers(info, renderingGroupMask);
  16731. }
  16732. // Clear depth/stencil if needed
  16733. if (RenderingManager.AUTOCLEAR) {
  16734. var autoClear = this._autoClearDepthStencil[index];
  16735. if (autoClear && autoClear.autoClear) {
  16736. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16737. }
  16738. }
  16739. if (observable && info) {
  16740. // Fire PREOPAQUE stage
  16741. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16742. observable.notifyObservers(info, renderingGroupMask);
  16743. // Fire PRETRANSPARENT stage
  16744. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16745. observable.notifyObservers(info, renderingGroupMask);
  16746. }
  16747. if (renderingGroup)
  16748. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16749. // Fire POSTTRANSPARENT stage
  16750. if (observable && info) {
  16751. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16752. observable.notifyObservers(info, renderingGroupMask);
  16753. }
  16754. }
  16755. };
  16756. RenderingManager.prototype.reset = function () {
  16757. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16758. var renderingGroup = this._renderingGroups[index];
  16759. if (renderingGroup) {
  16760. renderingGroup.prepare();
  16761. }
  16762. }
  16763. };
  16764. RenderingManager.prototype.dispose = function () {
  16765. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16766. var renderingGroup = this._renderingGroups[index];
  16767. if (renderingGroup) {
  16768. renderingGroup.dispose();
  16769. }
  16770. }
  16771. this._renderingGroups.length = 0;
  16772. };
  16773. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16774. if (!this._renderingGroups[renderingGroupId]) {
  16775. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16776. }
  16777. };
  16778. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16779. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16780. this._prepareRenderingGroup(renderingGroupId);
  16781. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16782. };
  16783. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16784. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16785. this._prepareRenderingGroup(renderingGroupId);
  16786. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16787. };
  16788. RenderingManager.prototype.dispatch = function (subMesh) {
  16789. var mesh = subMesh.getMesh();
  16790. var renderingGroupId = mesh.renderingGroupId || 0;
  16791. this._prepareRenderingGroup(renderingGroupId);
  16792. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16793. };
  16794. /**
  16795. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16796. * This allowed control for front to back rendering or reversly depending of the special needs.
  16797. *
  16798. * @param renderingGroupId The rendering group id corresponding to its index
  16799. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16800. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16801. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16802. */
  16803. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16804. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16805. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16806. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16807. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16808. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16809. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16810. if (this._renderingGroups[renderingGroupId]) {
  16811. var group = this._renderingGroups[renderingGroupId];
  16812. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16813. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16814. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16815. }
  16816. };
  16817. /**
  16818. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16819. *
  16820. * @param renderingGroupId The rendering group id corresponding to its index
  16821. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16822. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16823. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16824. */
  16825. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16826. if (depth === void 0) { depth = true; }
  16827. if (stencil === void 0) { stencil = true; }
  16828. this._autoClearDepthStencil[renderingGroupId] = {
  16829. autoClear: autoClearDepthStencil,
  16830. depth: depth,
  16831. stencil: stencil
  16832. };
  16833. };
  16834. /**
  16835. * The max id used for rendering groups (not included)
  16836. */
  16837. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16838. /**
  16839. * The min id used for rendering groups (included)
  16840. */
  16841. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16842. /**
  16843. * Used to globally prevent autoclearing scenes.
  16844. */
  16845. RenderingManager.AUTOCLEAR = true;
  16846. return RenderingManager;
  16847. }());
  16848. BABYLON.RenderingManager = RenderingManager;
  16849. })(BABYLON || (BABYLON = {}));
  16850. //# sourceMappingURL=babylon.renderingManager.js.map
  16851. var BABYLON;
  16852. (function (BABYLON) {
  16853. var RenderingGroup = /** @class */ (function () {
  16854. /**
  16855. * Creates a new rendering group.
  16856. * @param index The rendering group index
  16857. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16858. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16859. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16860. */
  16861. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16862. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16863. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16864. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16865. this.index = index;
  16866. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16867. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16868. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16869. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16870. this._particleSystems = new BABYLON.SmartArray(256);
  16871. this._spriteManagers = new BABYLON.SmartArray(256);
  16872. this._edgesRenderers = new BABYLON.SmartArray(16);
  16873. this._scene = scene;
  16874. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16875. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16876. this.transparentSortCompareFn = transparentSortCompareFn;
  16877. }
  16878. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16879. /**
  16880. * Set the opaque sort comparison function.
  16881. * If null the sub meshes will be render in the order they were created
  16882. */
  16883. set: function (value) {
  16884. this._opaqueSortCompareFn = value;
  16885. if (value) {
  16886. this._renderOpaque = this.renderOpaqueSorted;
  16887. }
  16888. else {
  16889. this._renderOpaque = RenderingGroup.renderUnsorted;
  16890. }
  16891. },
  16892. enumerable: true,
  16893. configurable: true
  16894. });
  16895. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16896. /**
  16897. * Set the alpha test sort comparison function.
  16898. * If null the sub meshes will be render in the order they were created
  16899. */
  16900. set: function (value) {
  16901. this._alphaTestSortCompareFn = value;
  16902. if (value) {
  16903. this._renderAlphaTest = this.renderAlphaTestSorted;
  16904. }
  16905. else {
  16906. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16907. }
  16908. },
  16909. enumerable: true,
  16910. configurable: true
  16911. });
  16912. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16913. /**
  16914. * Set the transparent sort comparison function.
  16915. * If null the sub meshes will be render in the order they were created
  16916. */
  16917. set: function (value) {
  16918. if (value) {
  16919. this._transparentSortCompareFn = value;
  16920. }
  16921. else {
  16922. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16923. }
  16924. this._renderTransparent = this.renderTransparentSorted;
  16925. },
  16926. enumerable: true,
  16927. configurable: true
  16928. });
  16929. /**
  16930. * Render all the sub meshes contained in the group.
  16931. * @param customRenderFunction Used to override the default render behaviour of the group.
  16932. * @returns true if rendered some submeshes.
  16933. */
  16934. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16935. if (customRenderFunction) {
  16936. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16937. return;
  16938. }
  16939. var engine = this._scene.getEngine();
  16940. // Depth only
  16941. if (this._depthOnlySubMeshes.length !== 0) {
  16942. engine.setAlphaTesting(true);
  16943. engine.setColorWrite(false);
  16944. this._renderAlphaTest(this._depthOnlySubMeshes);
  16945. engine.setAlphaTesting(false);
  16946. engine.setColorWrite(true);
  16947. }
  16948. // Opaque
  16949. if (this._opaqueSubMeshes.length !== 0) {
  16950. this._renderOpaque(this._opaqueSubMeshes);
  16951. }
  16952. // Alpha test
  16953. if (this._alphaTestSubMeshes.length !== 0) {
  16954. engine.setAlphaTesting(true);
  16955. this._renderAlphaTest(this._alphaTestSubMeshes);
  16956. engine.setAlphaTesting(false);
  16957. }
  16958. var stencilState = engine.getStencilBuffer();
  16959. engine.setStencilBuffer(false);
  16960. // Sprites
  16961. if (renderSprites) {
  16962. this._renderSprites();
  16963. }
  16964. // Particles
  16965. if (renderParticles) {
  16966. this._renderParticles(activeMeshes);
  16967. }
  16968. if (this.onBeforeTransparentRendering) {
  16969. this.onBeforeTransparentRendering();
  16970. }
  16971. // Transparent
  16972. if (this._transparentSubMeshes.length !== 0) {
  16973. this._renderTransparent(this._transparentSubMeshes);
  16974. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16975. }
  16976. // Set back stencil to false in case it changes before the edge renderer.
  16977. engine.setStencilBuffer(false);
  16978. // Edges
  16979. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16980. this._edgesRenderers.data[edgesRendererIndex].render();
  16981. }
  16982. // Restore Stencil state.
  16983. engine.setStencilBuffer(stencilState);
  16984. };
  16985. /**
  16986. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16987. * @param subMeshes The submeshes to render
  16988. */
  16989. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16990. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  16991. };
  16992. /**
  16993. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16994. * @param subMeshes The submeshes to render
  16995. */
  16996. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16997. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  16998. };
  16999. /**
  17000. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17001. * @param subMeshes The submeshes to render
  17002. */
  17003. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17004. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17005. };
  17006. /**
  17007. * Renders the submeshes in a specified order.
  17008. * @param subMeshes The submeshes to sort before render
  17009. * @param sortCompareFn The comparison function use to sort
  17010. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17011. * @param transparent Specifies to activate blending if true
  17012. */
  17013. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17014. var subIndex = 0;
  17015. var subMesh;
  17016. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17017. for (; subIndex < subMeshes.length; subIndex++) {
  17018. subMesh = subMeshes.data[subIndex];
  17019. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17020. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17021. }
  17022. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17023. if (sortCompareFn) {
  17024. sortedArray.sort(sortCompareFn);
  17025. }
  17026. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17027. subMesh = sortedArray[subIndex];
  17028. if (transparent) {
  17029. var material = subMesh.getMaterial();
  17030. if (material && material.needDepthPrePass) {
  17031. var engine = material.getScene().getEngine();
  17032. engine.setColorWrite(false);
  17033. engine.setAlphaTesting(true);
  17034. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17035. subMesh.render(false);
  17036. engine.setAlphaTesting(false);
  17037. engine.setColorWrite(true);
  17038. }
  17039. }
  17040. subMesh.render(transparent);
  17041. }
  17042. };
  17043. /**
  17044. * Renders the submeshes in the order they were dispatched (no sort applied).
  17045. * @param subMeshes The submeshes to render
  17046. */
  17047. RenderingGroup.renderUnsorted = function (subMeshes) {
  17048. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17049. var submesh = subMeshes.data[subIndex];
  17050. submesh.render(false);
  17051. }
  17052. };
  17053. /**
  17054. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17055. * are rendered back to front if in the same alpha index.
  17056. *
  17057. * @param a The first submesh
  17058. * @param b The second submesh
  17059. * @returns The result of the comparison
  17060. */
  17061. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17062. // Alpha index first
  17063. if (a._alphaIndex > b._alphaIndex) {
  17064. return 1;
  17065. }
  17066. if (a._alphaIndex < b._alphaIndex) {
  17067. return -1;
  17068. }
  17069. // Then distance to camera
  17070. return RenderingGroup.backToFrontSortCompare(a, b);
  17071. };
  17072. /**
  17073. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17074. * are rendered back to front.
  17075. *
  17076. * @param a The first submesh
  17077. * @param b The second submesh
  17078. * @returns The result of the comparison
  17079. */
  17080. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17081. // Then distance to camera
  17082. if (a._distanceToCamera < b._distanceToCamera) {
  17083. return 1;
  17084. }
  17085. if (a._distanceToCamera > b._distanceToCamera) {
  17086. return -1;
  17087. }
  17088. return 0;
  17089. };
  17090. /**
  17091. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17092. * are rendered front to back (prevent overdraw).
  17093. *
  17094. * @param a The first submesh
  17095. * @param b The second submesh
  17096. * @returns The result of the comparison
  17097. */
  17098. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17099. // Then distance to camera
  17100. if (a._distanceToCamera < b._distanceToCamera) {
  17101. return -1;
  17102. }
  17103. if (a._distanceToCamera > b._distanceToCamera) {
  17104. return 1;
  17105. }
  17106. return 0;
  17107. };
  17108. /**
  17109. * Resets the different lists of submeshes to prepare a new frame.
  17110. */
  17111. RenderingGroup.prototype.prepare = function () {
  17112. this._opaqueSubMeshes.reset();
  17113. this._transparentSubMeshes.reset();
  17114. this._alphaTestSubMeshes.reset();
  17115. this._depthOnlySubMeshes.reset();
  17116. this._particleSystems.reset();
  17117. this._spriteManagers.reset();
  17118. this._edgesRenderers.reset();
  17119. };
  17120. RenderingGroup.prototype.dispose = function () {
  17121. this._opaqueSubMeshes.dispose();
  17122. this._transparentSubMeshes.dispose();
  17123. this._alphaTestSubMeshes.dispose();
  17124. this._depthOnlySubMeshes.dispose();
  17125. this._particleSystems.dispose();
  17126. this._spriteManagers.dispose();
  17127. this._edgesRenderers.dispose();
  17128. };
  17129. /**
  17130. * Inserts the submesh in its correct queue depending on its material.
  17131. * @param subMesh The submesh to dispatch
  17132. */
  17133. RenderingGroup.prototype.dispatch = function (subMesh) {
  17134. var material = subMesh.getMaterial();
  17135. var mesh = subMesh.getMesh();
  17136. if (!material) {
  17137. return;
  17138. }
  17139. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  17140. this._transparentSubMeshes.push(subMesh);
  17141. }
  17142. else if (material.needAlphaTesting()) {
  17143. if (material.needDepthPrePass) {
  17144. this._depthOnlySubMeshes.push(subMesh);
  17145. }
  17146. this._alphaTestSubMeshes.push(subMesh);
  17147. }
  17148. else {
  17149. if (material.needDepthPrePass) {
  17150. this._depthOnlySubMeshes.push(subMesh);
  17151. }
  17152. this._opaqueSubMeshes.push(subMesh); // Opaque
  17153. }
  17154. if (mesh._edgesRenderer) {
  17155. this._edgesRenderers.push(mesh._edgesRenderer);
  17156. }
  17157. };
  17158. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17159. this._spriteManagers.push(spriteManager);
  17160. };
  17161. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17162. this._particleSystems.push(particleSystem);
  17163. };
  17164. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17165. if (this._particleSystems.length === 0) {
  17166. return;
  17167. }
  17168. // Particles
  17169. var activeCamera = this._scene.activeCamera;
  17170. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17171. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17172. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17173. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17174. continue;
  17175. }
  17176. var emitter = particleSystem.emitter;
  17177. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17178. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17179. }
  17180. }
  17181. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17182. };
  17183. RenderingGroup.prototype._renderSprites = function () {
  17184. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17185. return;
  17186. }
  17187. // Sprites
  17188. var activeCamera = this._scene.activeCamera;
  17189. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17190. for (var id = 0; id < this._spriteManagers.length; id++) {
  17191. var spriteManager = this._spriteManagers.data[id];
  17192. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17193. spriteManager.render();
  17194. }
  17195. }
  17196. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17197. };
  17198. return RenderingGroup;
  17199. }());
  17200. BABYLON.RenderingGroup = RenderingGroup;
  17201. })(BABYLON || (BABYLON = {}));
  17202. //# sourceMappingURL=babylon.renderingGroup.js.map
  17203. var BABYLON;
  17204. (function (BABYLON) {
  17205. var ClickInfo = /** @class */ (function () {
  17206. function ClickInfo() {
  17207. this._singleClick = false;
  17208. this._doubleClick = false;
  17209. this._hasSwiped = false;
  17210. this._ignore = false;
  17211. }
  17212. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17213. get: function () {
  17214. return this._singleClick;
  17215. },
  17216. set: function (b) {
  17217. this._singleClick = b;
  17218. },
  17219. enumerable: true,
  17220. configurable: true
  17221. });
  17222. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17223. get: function () {
  17224. return this._doubleClick;
  17225. },
  17226. set: function (b) {
  17227. this._doubleClick = b;
  17228. },
  17229. enumerable: true,
  17230. configurable: true
  17231. });
  17232. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17233. get: function () {
  17234. return this._hasSwiped;
  17235. },
  17236. set: function (b) {
  17237. this._hasSwiped = b;
  17238. },
  17239. enumerable: true,
  17240. configurable: true
  17241. });
  17242. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17243. get: function () {
  17244. return this._ignore;
  17245. },
  17246. set: function (b) {
  17247. this._ignore = b;
  17248. },
  17249. enumerable: true,
  17250. configurable: true
  17251. });
  17252. return ClickInfo;
  17253. }());
  17254. /**
  17255. * This class is used by the onRenderingGroupObservable
  17256. */
  17257. var RenderingGroupInfo = /** @class */ (function () {
  17258. function RenderingGroupInfo() {
  17259. }
  17260. /**
  17261. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17262. * This stage will be fired no matter what
  17263. */
  17264. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17265. /**
  17266. * Called before opaque object are rendered.
  17267. * This stage will be fired only if there's 3D Opaque content to render
  17268. */
  17269. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17270. /**
  17271. * Called after the opaque objects are rendered and before the transparent ones
  17272. * This stage will be fired only if there's 3D transparent content to render
  17273. */
  17274. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17275. /**
  17276. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17277. * This stage will be fired no matter what
  17278. */
  17279. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17280. return RenderingGroupInfo;
  17281. }());
  17282. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17283. /**
  17284. * Represents a scene to be rendered by the engine.
  17285. * @see http://doc.babylonjs.com/page.php?p=21911
  17286. */
  17287. var Scene = /** @class */ (function () {
  17288. /**
  17289. * @constructor
  17290. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17291. */
  17292. function Scene(engine) {
  17293. // Members
  17294. this.autoClear = true;
  17295. this.autoClearDepthAndStencil = true;
  17296. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17297. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17298. this.forceWireframe = false;
  17299. this._forcePointsCloud = false;
  17300. this.forceShowBoundingBoxes = false;
  17301. this.animationsEnabled = true;
  17302. this.constantlyUpdateMeshUnderPointer = false;
  17303. this.hoverCursor = "pointer";
  17304. this.defaultCursor = "";
  17305. /**
  17306. * This is used to call preventDefault() on pointer down
  17307. * in order to block unwanted artifacts like system double clicks
  17308. */
  17309. this.preventDefaultOnPointerDown = true;
  17310. // Metadata
  17311. this.metadata = null;
  17312. /**
  17313. * An event triggered when the scene is disposed.
  17314. * @type {BABYLON.Observable}
  17315. */
  17316. this.onDisposeObservable = new BABYLON.Observable();
  17317. /**
  17318. * An event triggered before rendering the scene (right after animations and physics)
  17319. * @type {BABYLON.Observable}
  17320. */
  17321. this.onBeforeRenderObservable = new BABYLON.Observable();
  17322. /**
  17323. * An event triggered after rendering the scene
  17324. * @type {BABYLON.Observable}
  17325. */
  17326. this.onAfterRenderObservable = new BABYLON.Observable();
  17327. /**
  17328. * An event triggered before animating the scene
  17329. * @type {BABYLON.Observable}
  17330. */
  17331. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17332. /**
  17333. * An event triggered after animations processing
  17334. * @type {BABYLON.Observable}
  17335. */
  17336. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17337. /**
  17338. * An event triggered before draw calls are ready to be sent
  17339. * @type {BABYLON.Observable}
  17340. */
  17341. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17342. /**
  17343. * An event triggered after draw calls have been sent
  17344. * @type {BABYLON.Observable}
  17345. */
  17346. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17347. /**
  17348. * An event triggered when physic simulation is about to be run
  17349. * @type {BABYLON.Observable}
  17350. */
  17351. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17352. /**
  17353. * An event triggered when physic simulation has been done
  17354. * @type {BABYLON.Observable}
  17355. */
  17356. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17357. /**
  17358. * An event triggered when the scene is ready
  17359. * @type {BABYLON.Observable}
  17360. */
  17361. this.onReadyObservable = new BABYLON.Observable();
  17362. /**
  17363. * An event triggered before rendering a camera
  17364. * @type {BABYLON.Observable}
  17365. */
  17366. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17367. /**
  17368. * An event triggered after rendering a camera
  17369. * @type {BABYLON.Observable}
  17370. */
  17371. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17372. /**
  17373. * An event triggered when active meshes evaluation is about to start
  17374. * @type {BABYLON.Observable}
  17375. */
  17376. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17377. /**
  17378. * An event triggered when active meshes evaluation is done
  17379. * @type {BABYLON.Observable}
  17380. */
  17381. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17382. /**
  17383. * An event triggered when particles rendering is about to start
  17384. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17385. * @type {BABYLON.Observable}
  17386. */
  17387. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17388. /**
  17389. * An event triggered when particles rendering is done
  17390. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17391. * @type {BABYLON.Observable}
  17392. */
  17393. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17394. /**
  17395. * An event triggered when sprites rendering is about to start
  17396. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17397. * @type {BABYLON.Observable}
  17398. */
  17399. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17400. /**
  17401. * An event triggered when sprites rendering is done
  17402. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17403. * @type {BABYLON.Observable}
  17404. */
  17405. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17406. /**
  17407. * An event triggered when a camera is created
  17408. * @type {BABYLON.Observable}
  17409. */
  17410. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17411. /**
  17412. * An event triggered when a camera is removed
  17413. * @type {BABYLON.Observable}
  17414. */
  17415. this.onCameraRemovedObservable = new BABYLON.Observable();
  17416. /**
  17417. * An event triggered when a light is created
  17418. * @type {BABYLON.Observable}
  17419. */
  17420. this.onNewLightAddedObservable = new BABYLON.Observable();
  17421. /**
  17422. * An event triggered when a light is removed
  17423. * @type {BABYLON.Observable}
  17424. */
  17425. this.onLightRemovedObservable = new BABYLON.Observable();
  17426. /**
  17427. * An event triggered when a geometry is created
  17428. * @type {BABYLON.Observable}
  17429. */
  17430. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17431. /**
  17432. * An event triggered when a geometry is removed
  17433. * @type {BABYLON.Observable}
  17434. */
  17435. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17436. /**
  17437. * An event triggered when a mesh is created
  17438. * @type {BABYLON.Observable}
  17439. */
  17440. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17441. /**
  17442. * An event triggered when a mesh is removed
  17443. * @type {BABYLON.Observable}
  17444. */
  17445. this.onMeshRemovedObservable = new BABYLON.Observable();
  17446. /**
  17447. * An event triggered when render targets are about to be rendered
  17448. * Can happen multiple times per frame.
  17449. * @type {BABYLON.Observable}
  17450. */
  17451. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17452. /**
  17453. * An event triggered when render targets were rendered.
  17454. * Can happen multiple times per frame.
  17455. * @type {BABYLON.Observable}
  17456. */
  17457. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17458. /**
  17459. * An event triggered before calculating deterministic simulation step
  17460. * @type {BABYLON.Observable}
  17461. */
  17462. this.onBeforeStepObservable = new BABYLON.Observable();
  17463. /**
  17464. * An event triggered after calculating deterministic simulation step
  17465. * @type {BABYLON.Observable}
  17466. */
  17467. this.onAfterStepObservable = new BABYLON.Observable();
  17468. /**
  17469. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17470. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17471. * 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)
  17472. */
  17473. this.onRenderingGroupObservable = new BABYLON.Observable();
  17474. // Animations
  17475. this.animations = [];
  17476. /**
  17477. * 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).
  17478. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17479. */
  17480. this.onPrePointerObservable = new BABYLON.Observable();
  17481. /**
  17482. * Observable event triggered each time an input event is received from the rendering canvas
  17483. */
  17484. this.onPointerObservable = new BABYLON.Observable();
  17485. this._meshPickProceed = false;
  17486. this._previousHasSwiped = false;
  17487. this._currentPickResult = null;
  17488. this._previousPickResult = null;
  17489. this._totalPointersPressed = 0;
  17490. this._doubleClickOccured = false;
  17491. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17492. this.cameraToUseForPointers = null;
  17493. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17494. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17495. this._startingPointerTime = 0;
  17496. this._previousStartingPointerTime = 0;
  17497. // Deterministic lockstep
  17498. this._timeAccumulator = 0;
  17499. this._currentStepId = 0;
  17500. this._currentInternalStep = 0;
  17501. // Keyboard
  17502. /**
  17503. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17504. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17505. */
  17506. this.onPreKeyboardObservable = new BABYLON.Observable();
  17507. /**
  17508. * Observable event triggered each time an keyboard event is received from the hosting window
  17509. */
  17510. this.onKeyboardObservable = new BABYLON.Observable();
  17511. // Coordinate system
  17512. /**
  17513. * use right-handed coordinate system on this scene.
  17514. * @type {boolean}
  17515. */
  17516. this._useRightHandedSystem = false;
  17517. // Fog
  17518. this._fogEnabled = true;
  17519. this._fogMode = Scene.FOGMODE_NONE;
  17520. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17521. this.fogDensity = 0.1;
  17522. this.fogStart = 0;
  17523. this.fogEnd = 1000.0;
  17524. // Lights
  17525. /**
  17526. * is shadow enabled on this scene.
  17527. * @type {boolean}
  17528. */
  17529. this._shadowsEnabled = true;
  17530. /**
  17531. * is light enabled on this scene.
  17532. * @type {boolean}
  17533. */
  17534. this._lightsEnabled = true;
  17535. /**
  17536. * All of the lights added to this scene.
  17537. * @see BABYLON.Light
  17538. * @type {BABYLON.Light[]}
  17539. */
  17540. this.lights = new Array();
  17541. // Cameras
  17542. /** All of the cameras added to this scene. */
  17543. this.cameras = new Array();
  17544. /** All of the active cameras added to this scene. */
  17545. this.activeCameras = new Array();
  17546. // Meshes
  17547. /**
  17548. * All of the (abstract) meshes added to this scene.
  17549. * @see BABYLON.AbstractMesh
  17550. * @type {BABYLON.AbstractMesh[]}
  17551. */
  17552. this.meshes = new Array();
  17553. // Geometries
  17554. this._geometries = new Array();
  17555. this.materials = new Array();
  17556. this.multiMaterials = new Array();
  17557. // Textures
  17558. this._texturesEnabled = true;
  17559. this.textures = new Array();
  17560. // Particles
  17561. this.particlesEnabled = true;
  17562. this.particleSystems = new Array();
  17563. // Sprites
  17564. this.spritesEnabled = true;
  17565. this.spriteManagers = new Array();
  17566. // Layers
  17567. this.layers = new Array();
  17568. this.highlightLayers = new Array();
  17569. // Skeletons
  17570. this._skeletonsEnabled = true;
  17571. this.skeletons = new Array();
  17572. // Morph targets
  17573. this.morphTargetManagers = new Array();
  17574. // Lens flares
  17575. this.lensFlaresEnabled = true;
  17576. this.lensFlareSystems = new Array();
  17577. // Collisions
  17578. this.collisionsEnabled = true;
  17579. /** Defines the gravity applied to this scene */
  17580. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17581. // Postprocesses
  17582. this.postProcesses = new Array();
  17583. this.postProcessesEnabled = true;
  17584. // Customs render targets
  17585. this.renderTargetsEnabled = true;
  17586. this.dumpNextRenderTargets = false;
  17587. this.customRenderTargets = new Array();
  17588. // Imported meshes
  17589. this.importedMeshesFiles = new Array();
  17590. // Probes
  17591. this.probesEnabled = true;
  17592. this.reflectionProbes = new Array();
  17593. this._actionManagers = new Array();
  17594. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17595. // Procedural textures
  17596. this.proceduralTexturesEnabled = true;
  17597. this._proceduralTextures = new Array();
  17598. this.soundTracks = new Array();
  17599. this._audioEnabled = true;
  17600. this._headphone = false;
  17601. // Performance counters
  17602. this._totalVertices = new BABYLON.PerfCounter();
  17603. this._activeIndices = new BABYLON.PerfCounter();
  17604. this._activeParticles = new BABYLON.PerfCounter();
  17605. this._activeBones = new BABYLON.PerfCounter();
  17606. this._animationTime = 0;
  17607. this.animationTimeScale = 1;
  17608. this._renderId = 0;
  17609. this._executeWhenReadyTimeoutId = -1;
  17610. this._intermediateRendering = false;
  17611. this._viewUpdateFlag = -1;
  17612. this._projectionUpdateFlag = -1;
  17613. this._alternateViewUpdateFlag = -1;
  17614. this._alternateProjectionUpdateFlag = -1;
  17615. this._toBeDisposed = new BABYLON.SmartArray(256);
  17616. this._pendingData = new Array();
  17617. this._isDisposed = false;
  17618. this._activeMeshes = new BABYLON.SmartArray(256);
  17619. this._processedMaterials = new BABYLON.SmartArray(256);
  17620. this._renderTargets = new BABYLON.SmartArray(256);
  17621. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17622. this._activeSkeletons = new BABYLON.SmartArray(32);
  17623. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17624. this._activeAnimatables = new Array();
  17625. this._transformMatrix = BABYLON.Matrix.Zero();
  17626. this._useAlternateCameraConfiguration = false;
  17627. this._alternateRendering = false;
  17628. this.requireLightSorting = false;
  17629. this._activeMeshesFrozen = false;
  17630. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17631. this._engine.scenes.push(this);
  17632. this._uid = null;
  17633. this._renderingManager = new BABYLON.RenderingManager(this);
  17634. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17635. if (BABYLON.OutlineRenderer) {
  17636. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17637. }
  17638. if (BABYLON.Tools.IsWindowObjectExist()) {
  17639. this.attachControl();
  17640. }
  17641. //simplification queue
  17642. if (BABYLON.SimplificationQueue) {
  17643. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17644. }
  17645. //collision coordinator initialization. For now legacy per default.
  17646. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17647. // Uniform Buffer
  17648. this._createUbo();
  17649. // Default Image processing definition.
  17650. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17651. }
  17652. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17653. /** The fog is deactivated */
  17654. get: function () {
  17655. return Scene._FOGMODE_NONE;
  17656. },
  17657. enumerable: true,
  17658. configurable: true
  17659. });
  17660. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17661. /** The fog density is following an exponential function */
  17662. get: function () {
  17663. return Scene._FOGMODE_EXP;
  17664. },
  17665. enumerable: true,
  17666. configurable: true
  17667. });
  17668. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17669. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17670. get: function () {
  17671. return Scene._FOGMODE_EXP2;
  17672. },
  17673. enumerable: true,
  17674. configurable: true
  17675. });
  17676. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17677. /** The fog density is following a linear function. */
  17678. get: function () {
  17679. return Scene._FOGMODE_LINEAR;
  17680. },
  17681. enumerable: true,
  17682. configurable: true
  17683. });
  17684. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17685. /**
  17686. * Texture used in all pbr material as the reflection texture.
  17687. * As in the majority of the scene they are the same (exception for multi room and so on),
  17688. * this is easier to reference from here than from all the materials.
  17689. */
  17690. get: function () {
  17691. return this._environmentTexture;
  17692. },
  17693. /**
  17694. * Texture used in all pbr material as the reflection texture.
  17695. * As in the majority of the scene they are the same (exception for multi room and so on),
  17696. * this is easier to set here than in all the materials.
  17697. */
  17698. set: function (value) {
  17699. if (this._environmentTexture === value) {
  17700. return;
  17701. }
  17702. this._environmentTexture = value;
  17703. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17704. },
  17705. enumerable: true,
  17706. configurable: true
  17707. });
  17708. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17709. /**
  17710. * Default image processing configuration used either in the rendering
  17711. * Forward main pass or through the imageProcessingPostProcess if present.
  17712. * As in the majority of the scene they are the same (exception for multi camera),
  17713. * this is easier to reference from here than from all the materials and post process.
  17714. *
  17715. * No setter as we it is a shared configuration, you can set the values instead.
  17716. */
  17717. get: function () {
  17718. return this._imageProcessingConfiguration;
  17719. },
  17720. enumerable: true,
  17721. configurable: true
  17722. });
  17723. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17724. get: function () {
  17725. return this._forcePointsCloud;
  17726. },
  17727. set: function (value) {
  17728. if (this._forcePointsCloud === value) {
  17729. return;
  17730. }
  17731. this._forcePointsCloud = value;
  17732. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17733. },
  17734. enumerable: true,
  17735. configurable: true
  17736. });
  17737. Object.defineProperty(Scene.prototype, "onDispose", {
  17738. /** A function to be executed when this scene is disposed. */
  17739. set: function (callback) {
  17740. if (this._onDisposeObserver) {
  17741. this.onDisposeObservable.remove(this._onDisposeObserver);
  17742. }
  17743. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17744. },
  17745. enumerable: true,
  17746. configurable: true
  17747. });
  17748. Object.defineProperty(Scene.prototype, "beforeRender", {
  17749. /** A function to be executed before rendering this scene */
  17750. set: function (callback) {
  17751. if (this._onBeforeRenderObserver) {
  17752. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17753. }
  17754. if (callback) {
  17755. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17756. }
  17757. },
  17758. enumerable: true,
  17759. configurable: true
  17760. });
  17761. Object.defineProperty(Scene.prototype, "afterRender", {
  17762. /** A function to be executed after rendering this scene */
  17763. set: function (callback) {
  17764. if (this._onAfterRenderObserver) {
  17765. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17766. }
  17767. if (callback) {
  17768. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17769. }
  17770. },
  17771. enumerable: true,
  17772. configurable: true
  17773. });
  17774. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17775. set: function (callback) {
  17776. if (this._onBeforeCameraRenderObserver) {
  17777. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17778. }
  17779. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17780. },
  17781. enumerable: true,
  17782. configurable: true
  17783. });
  17784. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17785. set: function (callback) {
  17786. if (this._onAfterCameraRenderObserver) {
  17787. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17788. }
  17789. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17790. },
  17791. enumerable: true,
  17792. configurable: true
  17793. });
  17794. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17795. get: function () {
  17796. if (!this._gamepadManager) {
  17797. this._gamepadManager = new BABYLON.GamepadManager();
  17798. }
  17799. return this._gamepadManager;
  17800. },
  17801. enumerable: true,
  17802. configurable: true
  17803. });
  17804. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17805. get: function () {
  17806. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17807. },
  17808. enumerable: true,
  17809. configurable: true
  17810. });
  17811. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17812. get: function () {
  17813. return this._useRightHandedSystem;
  17814. },
  17815. set: function (value) {
  17816. if (this._useRightHandedSystem === value) {
  17817. return;
  17818. }
  17819. this._useRightHandedSystem = value;
  17820. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17821. },
  17822. enumerable: true,
  17823. configurable: true
  17824. });
  17825. Scene.prototype.setStepId = function (newStepId) {
  17826. this._currentStepId = newStepId;
  17827. };
  17828. ;
  17829. Scene.prototype.getStepId = function () {
  17830. return this._currentStepId;
  17831. };
  17832. ;
  17833. Scene.prototype.getInternalStep = function () {
  17834. return this._currentInternalStep;
  17835. };
  17836. ;
  17837. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17838. get: function () {
  17839. return this._fogEnabled;
  17840. },
  17841. /**
  17842. * is fog enabled on this scene.
  17843. */
  17844. set: function (value) {
  17845. if (this._fogEnabled === value) {
  17846. return;
  17847. }
  17848. this._fogEnabled = value;
  17849. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17850. },
  17851. enumerable: true,
  17852. configurable: true
  17853. });
  17854. Object.defineProperty(Scene.prototype, "fogMode", {
  17855. get: function () {
  17856. return this._fogMode;
  17857. },
  17858. set: function (value) {
  17859. if (this._fogMode === value) {
  17860. return;
  17861. }
  17862. this._fogMode = value;
  17863. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17864. },
  17865. enumerable: true,
  17866. configurable: true
  17867. });
  17868. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17869. get: function () {
  17870. return this._shadowsEnabled;
  17871. },
  17872. set: function (value) {
  17873. if (this._shadowsEnabled === value) {
  17874. return;
  17875. }
  17876. this._shadowsEnabled = value;
  17877. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17878. },
  17879. enumerable: true,
  17880. configurable: true
  17881. });
  17882. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17883. get: function () {
  17884. return this._lightsEnabled;
  17885. },
  17886. set: function (value) {
  17887. if (this._lightsEnabled === value) {
  17888. return;
  17889. }
  17890. this._lightsEnabled = value;
  17891. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17892. },
  17893. enumerable: true,
  17894. configurable: true
  17895. });
  17896. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17897. /** The default material used on meshes when no material is affected */
  17898. get: function () {
  17899. if (!this._defaultMaterial) {
  17900. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17901. }
  17902. return this._defaultMaterial;
  17903. },
  17904. /** The default material used on meshes when no material is affected */
  17905. set: function (value) {
  17906. this._defaultMaterial = value;
  17907. },
  17908. enumerable: true,
  17909. configurable: true
  17910. });
  17911. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17912. get: function () {
  17913. return this._texturesEnabled;
  17914. },
  17915. set: function (value) {
  17916. if (this._texturesEnabled === value) {
  17917. return;
  17918. }
  17919. this._texturesEnabled = value;
  17920. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17921. },
  17922. enumerable: true,
  17923. configurable: true
  17924. });
  17925. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17926. get: function () {
  17927. return this._skeletonsEnabled;
  17928. },
  17929. set: function (value) {
  17930. if (this._skeletonsEnabled === value) {
  17931. return;
  17932. }
  17933. this._skeletonsEnabled = value;
  17934. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17935. },
  17936. enumerable: true,
  17937. configurable: true
  17938. });
  17939. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17940. get: function () {
  17941. if (!this._postProcessRenderPipelineManager) {
  17942. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17943. }
  17944. return this._postProcessRenderPipelineManager;
  17945. },
  17946. enumerable: true,
  17947. configurable: true
  17948. });
  17949. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17950. get: function () {
  17951. if (!this._mainSoundTrack) {
  17952. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17953. }
  17954. return this._mainSoundTrack;
  17955. },
  17956. enumerable: true,
  17957. configurable: true
  17958. });
  17959. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17960. get: function () {
  17961. return this._alternateRendering;
  17962. },
  17963. enumerable: true,
  17964. configurable: true
  17965. });
  17966. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17967. get: function () {
  17968. return this._frustumPlanes;
  17969. },
  17970. enumerable: true,
  17971. configurable: true
  17972. });
  17973. Object.defineProperty(Scene.prototype, "debugLayer", {
  17974. // Properties
  17975. get: function () {
  17976. if (!this._debugLayer) {
  17977. this._debugLayer = new BABYLON.DebugLayer(this);
  17978. }
  17979. return this._debugLayer;
  17980. },
  17981. enumerable: true,
  17982. configurable: true
  17983. });
  17984. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17985. get: function () {
  17986. return this._workerCollisions;
  17987. },
  17988. set: function (enabled) {
  17989. if (!BABYLON.CollisionCoordinatorLegacy) {
  17990. return;
  17991. }
  17992. enabled = (enabled && !!Worker);
  17993. this._workerCollisions = enabled;
  17994. if (this.collisionCoordinator) {
  17995. this.collisionCoordinator.destroy();
  17996. }
  17997. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17998. this.collisionCoordinator.init(this);
  17999. },
  18000. enumerable: true,
  18001. configurable: true
  18002. });
  18003. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18004. get: function () {
  18005. return this._selectionOctree;
  18006. },
  18007. enumerable: true,
  18008. configurable: true
  18009. });
  18010. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18011. /**
  18012. * The mesh that is currently under the pointer.
  18013. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18014. */
  18015. get: function () {
  18016. return this._pointerOverMesh;
  18017. },
  18018. enumerable: true,
  18019. configurable: true
  18020. });
  18021. Object.defineProperty(Scene.prototype, "pointerX", {
  18022. /**
  18023. * Current on-screen X position of the pointer
  18024. * @return {number} X position of the pointer
  18025. */
  18026. get: function () {
  18027. return this._pointerX;
  18028. },
  18029. enumerable: true,
  18030. configurable: true
  18031. });
  18032. Object.defineProperty(Scene.prototype, "pointerY", {
  18033. /**
  18034. * Current on-screen Y position of the pointer
  18035. * @return {number} Y position of the pointer
  18036. */
  18037. get: function () {
  18038. return this._pointerY;
  18039. },
  18040. enumerable: true,
  18041. configurable: true
  18042. });
  18043. Scene.prototype.getCachedMaterial = function () {
  18044. return this._cachedMaterial;
  18045. };
  18046. Scene.prototype.getCachedEffect = function () {
  18047. return this._cachedEffect;
  18048. };
  18049. Scene.prototype.getCachedVisibility = function () {
  18050. return this._cachedVisibility;
  18051. };
  18052. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18053. if (visibility === void 0) { visibility = 1; }
  18054. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18055. };
  18056. Scene.prototype.getBoundingBoxRenderer = function () {
  18057. if (!this._boundingBoxRenderer) {
  18058. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18059. }
  18060. return this._boundingBoxRenderer;
  18061. };
  18062. Scene.prototype.getOutlineRenderer = function () {
  18063. return this._outlineRenderer;
  18064. };
  18065. Scene.prototype.getEngine = function () {
  18066. return this._engine;
  18067. };
  18068. Scene.prototype.getTotalVertices = function () {
  18069. return this._totalVertices.current;
  18070. };
  18071. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18072. get: function () {
  18073. return this._totalVertices;
  18074. },
  18075. enumerable: true,
  18076. configurable: true
  18077. });
  18078. Scene.prototype.getActiveIndices = function () {
  18079. return this._activeIndices.current;
  18080. };
  18081. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18082. get: function () {
  18083. return this._activeIndices;
  18084. },
  18085. enumerable: true,
  18086. configurable: true
  18087. });
  18088. Scene.prototype.getActiveParticles = function () {
  18089. return this._activeParticles.current;
  18090. };
  18091. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18092. get: function () {
  18093. return this._activeParticles;
  18094. },
  18095. enumerable: true,
  18096. configurable: true
  18097. });
  18098. Scene.prototype.getActiveBones = function () {
  18099. return this._activeBones.current;
  18100. };
  18101. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18102. get: function () {
  18103. return this._activeBones;
  18104. },
  18105. enumerable: true,
  18106. configurable: true
  18107. });
  18108. // Stats
  18109. Scene.prototype.getInterFramePerfCounter = function () {
  18110. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18111. return 0;
  18112. };
  18113. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18114. get: function () {
  18115. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18116. return null;
  18117. },
  18118. enumerable: true,
  18119. configurable: true
  18120. });
  18121. Scene.prototype.getLastFrameDuration = function () {
  18122. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18123. return 0;
  18124. };
  18125. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18126. get: function () {
  18127. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18128. return null;
  18129. },
  18130. enumerable: true,
  18131. configurable: true
  18132. });
  18133. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18134. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18135. return 0;
  18136. };
  18137. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18138. get: function () {
  18139. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18140. return null;
  18141. },
  18142. enumerable: true,
  18143. configurable: true
  18144. });
  18145. Scene.prototype.getActiveMeshes = function () {
  18146. return this._activeMeshes;
  18147. };
  18148. Scene.prototype.getRenderTargetsDuration = function () {
  18149. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18150. return 0;
  18151. };
  18152. Scene.prototype.getRenderDuration = function () {
  18153. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18154. return 0;
  18155. };
  18156. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18157. get: function () {
  18158. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18159. return null;
  18160. },
  18161. enumerable: true,
  18162. configurable: true
  18163. });
  18164. Scene.prototype.getParticlesDuration = function () {
  18165. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18166. return 0;
  18167. };
  18168. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18169. get: function () {
  18170. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18171. return null;
  18172. },
  18173. enumerable: true,
  18174. configurable: true
  18175. });
  18176. Scene.prototype.getSpritesDuration = function () {
  18177. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18178. return 0;
  18179. };
  18180. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18181. get: function () {
  18182. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18183. return null;
  18184. },
  18185. enumerable: true,
  18186. configurable: true
  18187. });
  18188. Scene.prototype.getAnimationRatio = function () {
  18189. return this._animationRatio;
  18190. };
  18191. Scene.prototype.getRenderId = function () {
  18192. return this._renderId;
  18193. };
  18194. Scene.prototype.incrementRenderId = function () {
  18195. this._renderId++;
  18196. };
  18197. Scene.prototype._updatePointerPosition = function (evt) {
  18198. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18199. if (!canvasRect) {
  18200. return;
  18201. }
  18202. this._pointerX = evt.clientX - canvasRect.left;
  18203. this._pointerY = evt.clientY - canvasRect.top;
  18204. this._unTranslatedPointerX = this._pointerX;
  18205. this._unTranslatedPointerY = this._pointerY;
  18206. };
  18207. Scene.prototype._createUbo = function () {
  18208. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18209. this._sceneUbo.addUniform("viewProjection", 16);
  18210. this._sceneUbo.addUniform("view", 16);
  18211. };
  18212. Scene.prototype._createAlternateUbo = function () {
  18213. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18214. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18215. this._alternateSceneUbo.addUniform("view", 16);
  18216. };
  18217. // Pointers handling
  18218. /**
  18219. * Use this method to simulate a pointer move on a mesh
  18220. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18221. */
  18222. Scene.prototype.simulatePointerMove = function (pickResult) {
  18223. var evt = new PointerEvent("pointermove");
  18224. return this._processPointerMove(pickResult, evt);
  18225. };
  18226. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18227. var canvas = this._engine.getRenderingCanvas();
  18228. if (!canvas) {
  18229. return this;
  18230. }
  18231. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18232. this.setPointerOverSprite(null);
  18233. this.setPointerOverMesh(pickResult.pickedMesh);
  18234. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18235. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18236. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18237. }
  18238. else {
  18239. canvas.style.cursor = this.hoverCursor;
  18240. }
  18241. }
  18242. else {
  18243. canvas.style.cursor = this.defaultCursor;
  18244. }
  18245. }
  18246. else {
  18247. this.setPointerOverMesh(null);
  18248. // Sprites
  18249. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18250. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18251. this.setPointerOverSprite(pickResult.pickedSprite);
  18252. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18253. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18254. }
  18255. else {
  18256. canvas.style.cursor = this.hoverCursor;
  18257. }
  18258. }
  18259. else {
  18260. this.setPointerOverSprite(null);
  18261. // Restore pointer
  18262. canvas.style.cursor = this.defaultCursor;
  18263. }
  18264. }
  18265. if (pickResult) {
  18266. if (this.onPointerMove) {
  18267. this.onPointerMove(evt, pickResult);
  18268. }
  18269. if (this.onPointerObservable.hasObservers()) {
  18270. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18271. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18272. this.onPointerObservable.notifyObservers(pi, type);
  18273. }
  18274. }
  18275. return this;
  18276. };
  18277. /**
  18278. * Use this method to simulate a pointer down on a mesh
  18279. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18280. */
  18281. Scene.prototype.simulatePointerDown = function (pickResult) {
  18282. var evt = new PointerEvent("pointerdown");
  18283. return this._processPointerDown(pickResult, evt);
  18284. };
  18285. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18286. var _this = this;
  18287. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18288. this._pickedDownMesh = pickResult.pickedMesh;
  18289. var actionManager = pickResult.pickedMesh.actionManager;
  18290. if (actionManager) {
  18291. if (actionManager.hasPickTriggers) {
  18292. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18293. switch (evt.button) {
  18294. case 0:
  18295. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18296. break;
  18297. case 1:
  18298. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18299. break;
  18300. case 2:
  18301. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18302. break;
  18303. }
  18304. }
  18305. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18306. window.setTimeout(function () {
  18307. 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);
  18308. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18309. if (_this._totalPointersPressed !== 0 &&
  18310. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18311. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18312. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18313. _this._startingPointerTime = 0;
  18314. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18315. }
  18316. }
  18317. }, Scene.LongPressDelay);
  18318. }
  18319. }
  18320. }
  18321. if (pickResult) {
  18322. if (this.onPointerDown) {
  18323. this.onPointerDown(evt, pickResult);
  18324. }
  18325. if (this.onPointerObservable.hasObservers()) {
  18326. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18327. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18328. this.onPointerObservable.notifyObservers(pi, type);
  18329. }
  18330. }
  18331. return this;
  18332. };
  18333. /**
  18334. * Use this method to simulate a pointer up on a mesh
  18335. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18336. */
  18337. Scene.prototype.simulatePointerUp = function (pickResult) {
  18338. var evt = new PointerEvent("pointerup");
  18339. var clickInfo = new ClickInfo();
  18340. clickInfo.singleClick = true;
  18341. return this._processPointerUp(pickResult, evt, clickInfo);
  18342. };
  18343. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18344. if (pickResult && pickResult && pickResult.pickedMesh) {
  18345. this._pickedUpMesh = pickResult.pickedMesh;
  18346. if (this._pickedDownMesh === this._pickedUpMesh) {
  18347. if (this.onPointerPick) {
  18348. this.onPointerPick(evt, pickResult);
  18349. }
  18350. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18351. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18352. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18353. this.onPointerObservable.notifyObservers(pi, type);
  18354. }
  18355. }
  18356. if (pickResult.pickedMesh.actionManager) {
  18357. if (clickInfo.ignore) {
  18358. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18359. }
  18360. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18361. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18362. }
  18363. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18364. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18365. }
  18366. }
  18367. }
  18368. if (this._pickedDownMesh &&
  18369. this._pickedDownMesh.actionManager &&
  18370. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18371. this._pickedDownMesh !== this._pickedUpMesh) {
  18372. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18373. }
  18374. if (this.onPointerUp) {
  18375. this.onPointerUp(evt, pickResult);
  18376. }
  18377. if (this.onPointerObservable.hasObservers()) {
  18378. if (!clickInfo.ignore) {
  18379. if (!clickInfo.hasSwiped) {
  18380. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18381. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18382. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18383. this.onPointerObservable.notifyObservers(pi, type);
  18384. }
  18385. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18386. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18387. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18388. this.onPointerObservable.notifyObservers(pi, type);
  18389. }
  18390. }
  18391. }
  18392. else {
  18393. var type = BABYLON.PointerEventTypes.POINTERUP;
  18394. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18395. this.onPointerObservable.notifyObservers(pi, type);
  18396. }
  18397. }
  18398. return this;
  18399. };
  18400. /**
  18401. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18402. * @param attachUp defines if you want to attach events to pointerup
  18403. * @param attachDown defines if you want to attach events to pointerdown
  18404. * @param attachMove defines if you want to attach events to pointermove
  18405. */
  18406. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18407. var _this = this;
  18408. if (attachUp === void 0) { attachUp = true; }
  18409. if (attachDown === void 0) { attachDown = true; }
  18410. if (attachMove === void 0) { attachMove = true; }
  18411. this._initActionManager = function (act, clickInfo) {
  18412. if (!_this._meshPickProceed) {
  18413. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18414. _this._currentPickResult = pickResult;
  18415. if (pickResult) {
  18416. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18417. }
  18418. _this._meshPickProceed = true;
  18419. }
  18420. return act;
  18421. };
  18422. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18423. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18424. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18425. btn !== _this._previousButtonPressed) {
  18426. _this._doubleClickOccured = false;
  18427. clickInfo.singleClick = true;
  18428. clickInfo.ignore = false;
  18429. cb(clickInfo, _this._currentPickResult);
  18430. }
  18431. };
  18432. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18433. var clickInfo = new ClickInfo();
  18434. _this._currentPickResult = null;
  18435. var act = null;
  18436. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18437. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18438. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18439. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18440. act = _this._initActionManager(act, clickInfo);
  18441. if (act)
  18442. checkPicking = act.hasPickTriggers;
  18443. }
  18444. if (checkPicking) {
  18445. var btn = evt.button;
  18446. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18447. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18448. if (!clickInfo.hasSwiped) {
  18449. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18450. if (!checkSingleClickImmediately) {
  18451. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18452. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18453. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18454. act = _this._initActionManager(act, clickInfo);
  18455. if (act)
  18456. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18457. }
  18458. }
  18459. if (checkSingleClickImmediately) {
  18460. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18461. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18462. btn !== _this._previousButtonPressed) {
  18463. clickInfo.singleClick = true;
  18464. cb(clickInfo, _this._currentPickResult);
  18465. }
  18466. }
  18467. else {
  18468. // wait that no double click has been raised during the double click delay
  18469. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18470. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18471. }
  18472. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18473. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18474. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18475. act = _this._initActionManager(act, clickInfo);
  18476. if (act)
  18477. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18478. }
  18479. if (checkDoubleClick) {
  18480. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18481. if (btn === _this._previousButtonPressed &&
  18482. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18483. !_this._doubleClickOccured) {
  18484. // pointer has not moved for 2 clicks, it's a double click
  18485. if (!clickInfo.hasSwiped &&
  18486. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18487. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18488. _this._previousStartingPointerTime = 0;
  18489. _this._doubleClickOccured = true;
  18490. clickInfo.doubleClick = true;
  18491. clickInfo.ignore = false;
  18492. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18493. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18494. }
  18495. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18496. cb(clickInfo, _this._currentPickResult);
  18497. }
  18498. else {
  18499. _this._doubleClickOccured = false;
  18500. _this._previousStartingPointerTime = _this._startingPointerTime;
  18501. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18502. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18503. _this._previousButtonPressed = btn;
  18504. _this._previousHasSwiped = clickInfo.hasSwiped;
  18505. if (Scene.ExclusiveDoubleClickMode) {
  18506. if (_this._previousDelayedSimpleClickTimeout) {
  18507. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18508. }
  18509. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18510. cb(clickInfo, _this._previousPickResult);
  18511. }
  18512. else {
  18513. cb(clickInfo, _this._currentPickResult);
  18514. }
  18515. }
  18516. }
  18517. else {
  18518. _this._doubleClickOccured = false;
  18519. _this._previousStartingPointerTime = _this._startingPointerTime;
  18520. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18521. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18522. _this._previousButtonPressed = btn;
  18523. _this._previousHasSwiped = clickInfo.hasSwiped;
  18524. }
  18525. }
  18526. }
  18527. }
  18528. clickInfo.ignore = true;
  18529. cb(clickInfo, _this._currentPickResult);
  18530. };
  18531. this._spritePredicate = function (sprite) {
  18532. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18533. };
  18534. this._onPointerMove = function (evt) {
  18535. _this._updatePointerPosition(evt);
  18536. // PreObservable support
  18537. if (_this.onPrePointerObservable.hasObservers()) {
  18538. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18539. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18540. _this.onPrePointerObservable.notifyObservers(pi, type);
  18541. if (pi.skipOnPointerObservable) {
  18542. return;
  18543. }
  18544. }
  18545. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18546. return;
  18547. }
  18548. if (!_this.pointerMovePredicate) {
  18549. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18550. }
  18551. // Meshes
  18552. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18553. _this._processPointerMove(pickResult, evt);
  18554. };
  18555. this._onPointerDown = function (evt) {
  18556. _this._totalPointersPressed++;
  18557. _this._pickedDownMesh = null;
  18558. _this._meshPickProceed = false;
  18559. _this._updatePointerPosition(evt);
  18560. if (_this.preventDefaultOnPointerDown && canvas) {
  18561. evt.preventDefault();
  18562. canvas.focus();
  18563. }
  18564. // PreObservable support
  18565. if (_this.onPrePointerObservable.hasObservers()) {
  18566. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18567. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18568. _this.onPrePointerObservable.notifyObservers(pi, type);
  18569. if (pi.skipOnPointerObservable) {
  18570. return;
  18571. }
  18572. }
  18573. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18574. return;
  18575. }
  18576. _this._startingPointerPosition.x = _this._pointerX;
  18577. _this._startingPointerPosition.y = _this._pointerY;
  18578. _this._startingPointerTime = new Date().getTime();
  18579. if (!_this.pointerDownPredicate) {
  18580. _this.pointerDownPredicate = function (mesh) {
  18581. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18582. };
  18583. }
  18584. // Meshes
  18585. _this._pickedDownMesh = null;
  18586. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18587. _this._processPointerDown(pickResult, evt);
  18588. // Sprites
  18589. _this._pickedDownSprite = null;
  18590. if (_this.spriteManagers.length > 0) {
  18591. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18592. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18593. if (pickResult.pickedSprite.actionManager) {
  18594. _this._pickedDownSprite = pickResult.pickedSprite;
  18595. switch (evt.button) {
  18596. case 0:
  18597. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18598. break;
  18599. case 1:
  18600. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18601. break;
  18602. case 2:
  18603. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18604. break;
  18605. }
  18606. if (pickResult.pickedSprite.actionManager) {
  18607. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18608. }
  18609. }
  18610. }
  18611. }
  18612. };
  18613. this._onPointerUp = function (evt) {
  18614. if (_this._totalPointersPressed === 0) {
  18615. return; // So we need to test it the pointer down was pressed before.
  18616. }
  18617. _this._totalPointersPressed--;
  18618. _this._pickedUpMesh = null;
  18619. _this._meshPickProceed = false;
  18620. _this._updatePointerPosition(evt);
  18621. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18622. // PreObservable support
  18623. if (_this.onPrePointerObservable.hasObservers()) {
  18624. if (!clickInfo.ignore) {
  18625. if (!clickInfo.hasSwiped) {
  18626. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18627. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18628. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18629. _this.onPrePointerObservable.notifyObservers(pi, type);
  18630. if (pi.skipOnPointerObservable) {
  18631. return;
  18632. }
  18633. }
  18634. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18635. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18636. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18637. _this.onPrePointerObservable.notifyObservers(pi, type);
  18638. if (pi.skipOnPointerObservable) {
  18639. return;
  18640. }
  18641. }
  18642. }
  18643. }
  18644. else {
  18645. var type = BABYLON.PointerEventTypes.POINTERUP;
  18646. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18647. _this.onPrePointerObservable.notifyObservers(pi, type);
  18648. if (pi.skipOnPointerObservable) {
  18649. return;
  18650. }
  18651. }
  18652. }
  18653. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18654. return;
  18655. }
  18656. if (!_this.pointerUpPredicate) {
  18657. _this.pointerUpPredicate = function (mesh) {
  18658. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18659. };
  18660. }
  18661. // Meshes
  18662. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18663. _this._initActionManager(null, clickInfo);
  18664. }
  18665. if (!pickResult) {
  18666. pickResult = _this._currentPickResult;
  18667. }
  18668. _this._processPointerUp(pickResult, evt, clickInfo);
  18669. // Sprites
  18670. if (_this.spriteManagers.length > 0) {
  18671. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18672. if (spritePickResult) {
  18673. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18674. if (spritePickResult.pickedSprite.actionManager) {
  18675. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18676. if (spritePickResult.pickedSprite.actionManager) {
  18677. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18678. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18679. }
  18680. }
  18681. }
  18682. }
  18683. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18684. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18685. }
  18686. }
  18687. }
  18688. _this._previousPickResult = _this._currentPickResult;
  18689. });
  18690. };
  18691. this._onKeyDown = function (evt) {
  18692. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18693. if (_this.onPreKeyboardObservable.hasObservers()) {
  18694. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18695. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18696. if (pi.skipOnPointerObservable) {
  18697. return;
  18698. }
  18699. }
  18700. if (_this.onKeyboardObservable.hasObservers()) {
  18701. var pi = new BABYLON.KeyboardInfo(type, evt);
  18702. _this.onKeyboardObservable.notifyObservers(pi, type);
  18703. }
  18704. if (_this.actionManager) {
  18705. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18706. }
  18707. };
  18708. this._onKeyUp = function (evt) {
  18709. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18710. if (_this.onPreKeyboardObservable.hasObservers()) {
  18711. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18712. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18713. if (pi.skipOnPointerObservable) {
  18714. return;
  18715. }
  18716. }
  18717. if (_this.onKeyboardObservable.hasObservers()) {
  18718. var pi = new BABYLON.KeyboardInfo(type, evt);
  18719. _this.onKeyboardObservable.notifyObservers(pi, type);
  18720. }
  18721. if (_this.actionManager) {
  18722. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18723. }
  18724. };
  18725. var engine = this.getEngine();
  18726. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18727. if (!canvas) {
  18728. return;
  18729. }
  18730. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18731. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18732. });
  18733. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18734. if (!canvas) {
  18735. return;
  18736. }
  18737. canvas.removeEventListener("keydown", _this._onKeyDown);
  18738. canvas.removeEventListener("keyup", _this._onKeyUp);
  18739. });
  18740. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18741. var canvas = this._engine.getRenderingCanvas();
  18742. if (!canvas) {
  18743. return;
  18744. }
  18745. if (attachMove) {
  18746. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18747. // Wheel
  18748. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18749. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18750. }
  18751. if (attachDown) {
  18752. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18753. }
  18754. if (attachUp) {
  18755. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18756. }
  18757. canvas.tabIndex = 1;
  18758. };
  18759. Scene.prototype.detachControl = function () {
  18760. var engine = this.getEngine();
  18761. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18762. var canvas = engine.getRenderingCanvas();
  18763. if (!canvas) {
  18764. return;
  18765. }
  18766. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18767. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18768. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18769. if (this._onCanvasBlurObserver) {
  18770. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18771. }
  18772. if (this._onCanvasFocusObserver) {
  18773. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18774. }
  18775. // Wheel
  18776. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18777. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18778. // Keyboard
  18779. canvas.removeEventListener("keydown", this._onKeyDown);
  18780. canvas.removeEventListener("keyup", this._onKeyUp);
  18781. // Observables
  18782. this.onKeyboardObservable.clear();
  18783. this.onPreKeyboardObservable.clear();
  18784. this.onPointerObservable.clear();
  18785. this.onPrePointerObservable.clear();
  18786. };
  18787. // Ready
  18788. Scene.prototype.isReady = function () {
  18789. if (this._isDisposed) {
  18790. return false;
  18791. }
  18792. if (this._pendingData.length > 0) {
  18793. return false;
  18794. }
  18795. var index;
  18796. // Geometries
  18797. for (index = 0; index < this._geometries.length; index++) {
  18798. var geometry = this._geometries[index];
  18799. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18800. return false;
  18801. }
  18802. }
  18803. // Meshes
  18804. for (index = 0; index < this.meshes.length; index++) {
  18805. var mesh = this.meshes[index];
  18806. if (!mesh.isEnabled()) {
  18807. continue;
  18808. }
  18809. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18810. continue;
  18811. }
  18812. if (!mesh.isReady()) {
  18813. return false;
  18814. }
  18815. var mat = mesh.material;
  18816. if (mat) {
  18817. if (!mat.isReady(mesh)) {
  18818. return false;
  18819. }
  18820. }
  18821. }
  18822. return true;
  18823. };
  18824. Scene.prototype.resetCachedMaterial = function () {
  18825. this._cachedMaterial = null;
  18826. this._cachedEffect = null;
  18827. this._cachedVisibility = null;
  18828. };
  18829. Scene.prototype.registerBeforeRender = function (func) {
  18830. this.onBeforeRenderObservable.add(func);
  18831. };
  18832. Scene.prototype.unregisterBeforeRender = function (func) {
  18833. this.onBeforeRenderObservable.removeCallback(func);
  18834. };
  18835. Scene.prototype.registerAfterRender = function (func) {
  18836. this.onAfterRenderObservable.add(func);
  18837. };
  18838. Scene.prototype.unregisterAfterRender = function (func) {
  18839. this.onAfterRenderObservable.removeCallback(func);
  18840. };
  18841. Scene.prototype._addPendingData = function (data) {
  18842. this._pendingData.push(data);
  18843. };
  18844. Scene.prototype._removePendingData = function (data) {
  18845. var index = this._pendingData.indexOf(data);
  18846. if (index !== -1) {
  18847. this._pendingData.splice(index, 1);
  18848. }
  18849. };
  18850. Scene.prototype.getWaitingItemsCount = function () {
  18851. return this._pendingData.length;
  18852. };
  18853. /**
  18854. * Registers a function to be executed when the scene is ready.
  18855. * @param {Function} func - the function to be executed.
  18856. */
  18857. Scene.prototype.executeWhenReady = function (func) {
  18858. var _this = this;
  18859. this.onReadyObservable.add(func);
  18860. if (this._executeWhenReadyTimeoutId !== -1) {
  18861. return;
  18862. }
  18863. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18864. _this._checkIsReady();
  18865. }, 150);
  18866. };
  18867. Scene.prototype._checkIsReady = function () {
  18868. var _this = this;
  18869. if (this.isReady()) {
  18870. this.onReadyObservable.notifyObservers(this);
  18871. this.onReadyObservable.clear();
  18872. this._executeWhenReadyTimeoutId = -1;
  18873. return;
  18874. }
  18875. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18876. _this._checkIsReady();
  18877. }, 150);
  18878. };
  18879. // Animations
  18880. /**
  18881. * Will start the animation sequence of a given target
  18882. * @param target - the target
  18883. * @param {number} from - from which frame should animation start
  18884. * @param {number} to - till which frame should animation run.
  18885. * @param {boolean} [loop] - should the animation loop
  18886. * @param {number} [speedRatio] - the speed in which to run the animation
  18887. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18888. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18889. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18890. * See BABYLON.Animatable
  18891. */
  18892. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18893. if (speedRatio === void 0) { speedRatio = 1.0; }
  18894. if (from > to && speedRatio > 0) {
  18895. speedRatio *= -1;
  18896. }
  18897. this.stopAnimation(target);
  18898. if (!animatable) {
  18899. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18900. }
  18901. // Local animations
  18902. if (target.animations) {
  18903. animatable.appendAnimations(target, target.animations);
  18904. }
  18905. // Children animations
  18906. if (target.getAnimatables) {
  18907. var animatables = target.getAnimatables();
  18908. for (var index = 0; index < animatables.length; index++) {
  18909. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18910. }
  18911. }
  18912. animatable.reset();
  18913. return animatable;
  18914. };
  18915. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18916. if (speedRatio === undefined) {
  18917. speedRatio = 1.0;
  18918. }
  18919. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18920. return animatable;
  18921. };
  18922. Scene.prototype.getAnimatableByTarget = function (target) {
  18923. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18924. if (this._activeAnimatables[index].target === target) {
  18925. return this._activeAnimatables[index];
  18926. }
  18927. }
  18928. return null;
  18929. };
  18930. Object.defineProperty(Scene.prototype, "Animatables", {
  18931. get: function () {
  18932. return this._activeAnimatables;
  18933. },
  18934. enumerable: true,
  18935. configurable: true
  18936. });
  18937. /**
  18938. * Will stop the animation of the given target
  18939. * @param target - the target
  18940. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18941. * @see beginAnimation
  18942. */
  18943. Scene.prototype.stopAnimation = function (target, animationName) {
  18944. var animatable = this.getAnimatableByTarget(target);
  18945. if (animatable) {
  18946. animatable.stop(animationName);
  18947. }
  18948. };
  18949. Scene.prototype._animate = function () {
  18950. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18951. return;
  18952. }
  18953. // Getting time
  18954. var now = BABYLON.Tools.Now;
  18955. if (!this._animationTimeLast) {
  18956. if (this._pendingData.length > 0) {
  18957. return;
  18958. }
  18959. this._animationTimeLast = now;
  18960. }
  18961. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18962. this._animationTime += deltaTime;
  18963. this._animationTimeLast = now;
  18964. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18965. this._activeAnimatables[index]._animate(this._animationTime);
  18966. }
  18967. };
  18968. // Matrix
  18969. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18970. this._useAlternateCameraConfiguration = active;
  18971. };
  18972. Scene.prototype.getViewMatrix = function () {
  18973. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18974. };
  18975. Scene.prototype.getProjectionMatrix = function () {
  18976. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18977. };
  18978. Scene.prototype.getTransformMatrix = function () {
  18979. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18980. };
  18981. Scene.prototype.setTransformMatrix = function (view, projection) {
  18982. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18983. return;
  18984. }
  18985. this._viewUpdateFlag = view.updateFlag;
  18986. this._projectionUpdateFlag = projection.updateFlag;
  18987. this._viewMatrix = view;
  18988. this._projectionMatrix = projection;
  18989. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18990. // Update frustum
  18991. if (!this._frustumPlanes) {
  18992. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18993. }
  18994. else {
  18995. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18996. }
  18997. if (this.activeCamera && this.activeCamera._alternateCamera) {
  18998. var otherCamera = this.activeCamera._alternateCamera;
  18999. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19000. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19001. }
  19002. if (this._sceneUbo.useUbo) {
  19003. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19004. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19005. this._sceneUbo.update();
  19006. }
  19007. };
  19008. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19009. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19010. return;
  19011. }
  19012. this._alternateViewUpdateFlag = view.updateFlag;
  19013. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19014. this._alternateViewMatrix = view;
  19015. this._alternateProjectionMatrix = projection;
  19016. if (!this._alternateTransformMatrix) {
  19017. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19018. }
  19019. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19020. if (!this._alternateSceneUbo) {
  19021. this._createAlternateUbo();
  19022. }
  19023. if (this._alternateSceneUbo.useUbo) {
  19024. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19025. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19026. this._alternateSceneUbo.update();
  19027. }
  19028. };
  19029. Scene.prototype.getSceneUniformBuffer = function () {
  19030. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19031. };
  19032. // Methods
  19033. Scene.prototype.getUniqueId = function () {
  19034. var result = Scene._uniqueIdCounter;
  19035. Scene._uniqueIdCounter++;
  19036. return result;
  19037. };
  19038. Scene.prototype.addMesh = function (newMesh) {
  19039. this.meshes.push(newMesh);
  19040. //notify the collision coordinator
  19041. if (this.collisionCoordinator) {
  19042. this.collisionCoordinator.onMeshAdded(newMesh);
  19043. }
  19044. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19045. };
  19046. Scene.prototype.removeMesh = function (toRemove) {
  19047. var index = this.meshes.indexOf(toRemove);
  19048. if (index !== -1) {
  19049. // Remove from the scene if mesh found
  19050. this.meshes.splice(index, 1);
  19051. }
  19052. //notify the collision coordinator
  19053. if (this.collisionCoordinator) {
  19054. this.collisionCoordinator.onMeshRemoved(toRemove);
  19055. }
  19056. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19057. return index;
  19058. };
  19059. Scene.prototype.removeSkeleton = function (toRemove) {
  19060. var index = this.skeletons.indexOf(toRemove);
  19061. if (index !== -1) {
  19062. // Remove from the scene if found
  19063. this.skeletons.splice(index, 1);
  19064. }
  19065. return index;
  19066. };
  19067. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19068. var index = this.morphTargetManagers.indexOf(toRemove);
  19069. if (index !== -1) {
  19070. // Remove from the scene if found
  19071. this.morphTargetManagers.splice(index, 1);
  19072. }
  19073. return index;
  19074. };
  19075. Scene.prototype.removeLight = function (toRemove) {
  19076. var index = this.lights.indexOf(toRemove);
  19077. if (index !== -1) {
  19078. // Remove from the scene if mesh found
  19079. this.lights.splice(index, 1);
  19080. this.sortLightsByPriority();
  19081. }
  19082. this.onLightRemovedObservable.notifyObservers(toRemove);
  19083. return index;
  19084. };
  19085. Scene.prototype.removeCamera = function (toRemove) {
  19086. var index = this.cameras.indexOf(toRemove);
  19087. if (index !== -1) {
  19088. // Remove from the scene if mesh found
  19089. this.cameras.splice(index, 1);
  19090. }
  19091. // Remove from activeCameras
  19092. var index2 = this.activeCameras.indexOf(toRemove);
  19093. if (index2 !== -1) {
  19094. // Remove from the scene if mesh found
  19095. this.activeCameras.splice(index2, 1);
  19096. }
  19097. // Reset the activeCamera
  19098. if (this.activeCamera === toRemove) {
  19099. if (this.cameras.length > 0) {
  19100. this.activeCamera = this.cameras[0];
  19101. }
  19102. else {
  19103. this.activeCamera = null;
  19104. }
  19105. }
  19106. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19107. return index;
  19108. };
  19109. Scene.prototype.addLight = function (newLight) {
  19110. this.lights.push(newLight);
  19111. this.sortLightsByPriority();
  19112. this.onNewLightAddedObservable.notifyObservers(newLight);
  19113. };
  19114. Scene.prototype.sortLightsByPriority = function () {
  19115. if (this.requireLightSorting) {
  19116. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19117. }
  19118. };
  19119. Scene.prototype.addCamera = function (newCamera) {
  19120. this.cameras.push(newCamera);
  19121. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19122. };
  19123. /**
  19124. * Switch active camera
  19125. * @param {Camera} newCamera - new active camera
  19126. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19127. */
  19128. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19129. if (attachControl === void 0) { attachControl = true; }
  19130. var canvas = this._engine.getRenderingCanvas();
  19131. if (!canvas) {
  19132. return;
  19133. }
  19134. if (this.activeCamera) {
  19135. this.activeCamera.detachControl(canvas);
  19136. }
  19137. this.activeCamera = newCamera;
  19138. if (attachControl) {
  19139. newCamera.attachControl(canvas);
  19140. }
  19141. };
  19142. /**
  19143. * sets the active camera of the scene using its ID
  19144. * @param {string} id - the camera's ID
  19145. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19146. * @see activeCamera
  19147. */
  19148. Scene.prototype.setActiveCameraByID = function (id) {
  19149. var camera = this.getCameraByID(id);
  19150. if (camera) {
  19151. this.activeCamera = camera;
  19152. return camera;
  19153. }
  19154. return null;
  19155. };
  19156. /**
  19157. * sets the active camera of the scene using its name
  19158. * @param {string} name - the camera's name
  19159. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19160. * @see activeCamera
  19161. */
  19162. Scene.prototype.setActiveCameraByName = function (name) {
  19163. var camera = this.getCameraByName(name);
  19164. if (camera) {
  19165. this.activeCamera = camera;
  19166. return camera;
  19167. }
  19168. return null;
  19169. };
  19170. /**
  19171. * get a material using its id
  19172. * @param {string} the material's ID
  19173. * @return {BABYLON.Material|null} the material or null if none found.
  19174. */
  19175. Scene.prototype.getMaterialByID = function (id) {
  19176. for (var index = 0; index < this.materials.length; index++) {
  19177. if (this.materials[index].id === id) {
  19178. return this.materials[index];
  19179. }
  19180. }
  19181. return null;
  19182. };
  19183. /**
  19184. * get a material using its name
  19185. * @param {string} the material's name
  19186. * @return {BABYLON.Material|null} the material or null if none found.
  19187. */
  19188. Scene.prototype.getMaterialByName = function (name) {
  19189. for (var index = 0; index < this.materials.length; index++) {
  19190. if (this.materials[index].name === name) {
  19191. return this.materials[index];
  19192. }
  19193. }
  19194. return null;
  19195. };
  19196. Scene.prototype.getLensFlareSystemByName = function (name) {
  19197. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19198. if (this.lensFlareSystems[index].name === name) {
  19199. return this.lensFlareSystems[index];
  19200. }
  19201. }
  19202. return null;
  19203. };
  19204. Scene.prototype.getLensFlareSystemByID = function (id) {
  19205. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19206. if (this.lensFlareSystems[index].id === id) {
  19207. return this.lensFlareSystems[index];
  19208. }
  19209. }
  19210. return null;
  19211. };
  19212. Scene.prototype.getCameraByID = function (id) {
  19213. for (var index = 0; index < this.cameras.length; index++) {
  19214. if (this.cameras[index].id === id) {
  19215. return this.cameras[index];
  19216. }
  19217. }
  19218. return null;
  19219. };
  19220. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19221. for (var index = 0; index < this.cameras.length; index++) {
  19222. if (this.cameras[index].uniqueId === uniqueId) {
  19223. return this.cameras[index];
  19224. }
  19225. }
  19226. return null;
  19227. };
  19228. /**
  19229. * get a camera using its name
  19230. * @param {string} the camera's name
  19231. * @return {BABYLON.Camera|null} the camera or null if none found.
  19232. */
  19233. Scene.prototype.getCameraByName = function (name) {
  19234. for (var index = 0; index < this.cameras.length; index++) {
  19235. if (this.cameras[index].name === name) {
  19236. return this.cameras[index];
  19237. }
  19238. }
  19239. return null;
  19240. };
  19241. /**
  19242. * get a bone using its id
  19243. * @param {string} the bone's id
  19244. * @return {BABYLON.Bone|null} the bone or null if not found
  19245. */
  19246. Scene.prototype.getBoneByID = function (id) {
  19247. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19248. var skeleton = this.skeletons[skeletonIndex];
  19249. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19250. if (skeleton.bones[boneIndex].id === id) {
  19251. return skeleton.bones[boneIndex];
  19252. }
  19253. }
  19254. }
  19255. return null;
  19256. };
  19257. /**
  19258. * get a bone using its id
  19259. * @param {string} the bone's name
  19260. * @return {BABYLON.Bone|null} the bone or null if not found
  19261. */
  19262. Scene.prototype.getBoneByName = function (name) {
  19263. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19264. var skeleton = this.skeletons[skeletonIndex];
  19265. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19266. if (skeleton.bones[boneIndex].name === name) {
  19267. return skeleton.bones[boneIndex];
  19268. }
  19269. }
  19270. }
  19271. return null;
  19272. };
  19273. /**
  19274. * get a light node using its name
  19275. * @param {string} the light's name
  19276. * @return {BABYLON.Light|null} the light or null if none found.
  19277. */
  19278. Scene.prototype.getLightByName = function (name) {
  19279. for (var index = 0; index < this.lights.length; index++) {
  19280. if (this.lights[index].name === name) {
  19281. return this.lights[index];
  19282. }
  19283. }
  19284. return null;
  19285. };
  19286. /**
  19287. * get a light node using its ID
  19288. * @param {string} the light's id
  19289. * @return {BABYLON.Light|null} the light or null if none found.
  19290. */
  19291. Scene.prototype.getLightByID = function (id) {
  19292. for (var index = 0; index < this.lights.length; index++) {
  19293. if (this.lights[index].id === id) {
  19294. return this.lights[index];
  19295. }
  19296. }
  19297. return null;
  19298. };
  19299. /**
  19300. * get a light node using its scene-generated unique ID
  19301. * @param {number} the light's unique id
  19302. * @return {BABYLON.Light|null} the light or null if none found.
  19303. */
  19304. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19305. for (var index = 0; index < this.lights.length; index++) {
  19306. if (this.lights[index].uniqueId === uniqueId) {
  19307. return this.lights[index];
  19308. }
  19309. }
  19310. return null;
  19311. };
  19312. /**
  19313. * get a particle system by id
  19314. * @param id {number} the particle system id
  19315. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19316. */
  19317. Scene.prototype.getParticleSystemByID = function (id) {
  19318. for (var index = 0; index < this.particleSystems.length; index++) {
  19319. if (this.particleSystems[index].id === id) {
  19320. return this.particleSystems[index];
  19321. }
  19322. }
  19323. return null;
  19324. };
  19325. /**
  19326. * get a geometry using its ID
  19327. * @param {string} the geometry's id
  19328. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19329. */
  19330. Scene.prototype.getGeometryByID = function (id) {
  19331. for (var index = 0; index < this._geometries.length; index++) {
  19332. if (this._geometries[index].id === id) {
  19333. return this._geometries[index];
  19334. }
  19335. }
  19336. return null;
  19337. };
  19338. /**
  19339. * add a new geometry to this scene.
  19340. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19341. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19342. * @return {boolean} was the geometry added or not
  19343. */
  19344. Scene.prototype.pushGeometry = function (geometry, force) {
  19345. if (!force && this.getGeometryByID(geometry.id)) {
  19346. return false;
  19347. }
  19348. this._geometries.push(geometry);
  19349. //notify the collision coordinator
  19350. if (this.collisionCoordinator) {
  19351. this.collisionCoordinator.onGeometryAdded(geometry);
  19352. }
  19353. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19354. return true;
  19355. };
  19356. /**
  19357. * Removes an existing geometry
  19358. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19359. * @return {boolean} was the geometry removed or not
  19360. */
  19361. Scene.prototype.removeGeometry = function (geometry) {
  19362. var index = this._geometries.indexOf(geometry);
  19363. if (index > -1) {
  19364. this._geometries.splice(index, 1);
  19365. //notify the collision coordinator
  19366. if (this.collisionCoordinator) {
  19367. this.collisionCoordinator.onGeometryDeleted(geometry);
  19368. }
  19369. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19370. return true;
  19371. }
  19372. return false;
  19373. };
  19374. Scene.prototype.getGeometries = function () {
  19375. return this._geometries;
  19376. };
  19377. /**
  19378. * Get the first added mesh found of a given ID
  19379. * @param {string} id - the id to search for
  19380. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19381. */
  19382. Scene.prototype.getMeshByID = function (id) {
  19383. for (var index = 0; index < this.meshes.length; index++) {
  19384. if (this.meshes[index].id === id) {
  19385. return this.meshes[index];
  19386. }
  19387. }
  19388. return null;
  19389. };
  19390. Scene.prototype.getMeshesByID = function (id) {
  19391. return this.meshes.filter(function (m) {
  19392. return m.id === id;
  19393. });
  19394. };
  19395. /**
  19396. * Get a mesh with its auto-generated unique id
  19397. * @param {number} uniqueId - the unique id to search for
  19398. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19399. */
  19400. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19401. for (var index = 0; index < this.meshes.length; index++) {
  19402. if (this.meshes[index].uniqueId === uniqueId) {
  19403. return this.meshes[index];
  19404. }
  19405. }
  19406. return null;
  19407. };
  19408. /**
  19409. * Get a the last added mesh found of a given ID
  19410. * @param {string} id - the id to search for
  19411. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19412. */
  19413. Scene.prototype.getLastMeshByID = function (id) {
  19414. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19415. if (this.meshes[index].id === id) {
  19416. return this.meshes[index];
  19417. }
  19418. }
  19419. return null;
  19420. };
  19421. /**
  19422. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19423. * @param {string} id - the id to search for
  19424. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19425. */
  19426. Scene.prototype.getLastEntryByID = function (id) {
  19427. var index;
  19428. for (index = this.meshes.length - 1; index >= 0; index--) {
  19429. if (this.meshes[index].id === id) {
  19430. return this.meshes[index];
  19431. }
  19432. }
  19433. for (index = this.cameras.length - 1; index >= 0; index--) {
  19434. if (this.cameras[index].id === id) {
  19435. return this.cameras[index];
  19436. }
  19437. }
  19438. for (index = this.lights.length - 1; index >= 0; index--) {
  19439. if (this.lights[index].id === id) {
  19440. return this.lights[index];
  19441. }
  19442. }
  19443. return null;
  19444. };
  19445. Scene.prototype.getNodeByID = function (id) {
  19446. var mesh = this.getMeshByID(id);
  19447. if (mesh) {
  19448. return mesh;
  19449. }
  19450. var light = this.getLightByID(id);
  19451. if (light) {
  19452. return light;
  19453. }
  19454. var camera = this.getCameraByID(id);
  19455. if (camera) {
  19456. return camera;
  19457. }
  19458. var bone = this.getBoneByID(id);
  19459. return bone;
  19460. };
  19461. Scene.prototype.getNodeByName = function (name) {
  19462. var mesh = this.getMeshByName(name);
  19463. if (mesh) {
  19464. return mesh;
  19465. }
  19466. var light = this.getLightByName(name);
  19467. if (light) {
  19468. return light;
  19469. }
  19470. var camera = this.getCameraByName(name);
  19471. if (camera) {
  19472. return camera;
  19473. }
  19474. var bone = this.getBoneByName(name);
  19475. return bone;
  19476. };
  19477. Scene.prototype.getMeshByName = function (name) {
  19478. for (var index = 0; index < this.meshes.length; index++) {
  19479. if (this.meshes[index].name === name) {
  19480. return this.meshes[index];
  19481. }
  19482. }
  19483. return null;
  19484. };
  19485. Scene.prototype.getSoundByName = function (name) {
  19486. var index;
  19487. if (BABYLON.AudioEngine) {
  19488. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19489. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19490. return this.mainSoundTrack.soundCollection[index];
  19491. }
  19492. }
  19493. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19494. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19495. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19496. return this.soundTracks[sdIndex].soundCollection[index];
  19497. }
  19498. }
  19499. }
  19500. }
  19501. return null;
  19502. };
  19503. Scene.prototype.getLastSkeletonByID = function (id) {
  19504. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19505. if (this.skeletons[index].id === id) {
  19506. return this.skeletons[index];
  19507. }
  19508. }
  19509. return null;
  19510. };
  19511. Scene.prototype.getSkeletonById = function (id) {
  19512. for (var index = 0; index < this.skeletons.length; index++) {
  19513. if (this.skeletons[index].id === id) {
  19514. return this.skeletons[index];
  19515. }
  19516. }
  19517. return null;
  19518. };
  19519. Scene.prototype.getSkeletonByName = function (name) {
  19520. for (var index = 0; index < this.skeletons.length; index++) {
  19521. if (this.skeletons[index].name === name) {
  19522. return this.skeletons[index];
  19523. }
  19524. }
  19525. return null;
  19526. };
  19527. Scene.prototype.getMorphTargetManagerById = function (id) {
  19528. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19529. if (this.morphTargetManagers[index].uniqueId === id) {
  19530. return this.morphTargetManagers[index];
  19531. }
  19532. }
  19533. return null;
  19534. };
  19535. Scene.prototype.isActiveMesh = function (mesh) {
  19536. return (this._activeMeshes.indexOf(mesh) !== -1);
  19537. };
  19538. /**
  19539. * Return a the first highlight layer of the scene with a given name.
  19540. * @param name The name of the highlight layer to look for.
  19541. * @return The highlight layer if found otherwise null.
  19542. */
  19543. Scene.prototype.getHighlightLayerByName = function (name) {
  19544. for (var index = 0; index < this.highlightLayers.length; index++) {
  19545. if (this.highlightLayers[index].name === name) {
  19546. return this.highlightLayers[index];
  19547. }
  19548. }
  19549. return null;
  19550. };
  19551. Object.defineProperty(Scene.prototype, "uid", {
  19552. /**
  19553. * Return a unique id as a string which can serve as an identifier for the scene
  19554. */
  19555. get: function () {
  19556. if (!this._uid) {
  19557. this._uid = BABYLON.Tools.RandomId();
  19558. }
  19559. return this._uid;
  19560. },
  19561. enumerable: true,
  19562. configurable: true
  19563. });
  19564. /**
  19565. * Add an externaly attached data from its key.
  19566. * This method call will fail and return false, if such key already exists.
  19567. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19568. * @param key the unique key that identifies the data
  19569. * @param data the data object to associate to the key for this Engine instance
  19570. * @return true if no such key were already present and the data was added successfully, false otherwise
  19571. */
  19572. Scene.prototype.addExternalData = function (key, data) {
  19573. if (!this._externalData) {
  19574. this._externalData = new BABYLON.StringDictionary();
  19575. }
  19576. return this._externalData.add(key, data);
  19577. };
  19578. /**
  19579. * Get an externaly attached data from its key
  19580. * @param key the unique key that identifies the data
  19581. * @return the associated data, if present (can be null), or undefined if not present
  19582. */
  19583. Scene.prototype.getExternalData = function (key) {
  19584. if (!this._externalData) {
  19585. return null;
  19586. }
  19587. return this._externalData.get(key);
  19588. };
  19589. /**
  19590. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19591. * @param key the unique key that identifies the data
  19592. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19593. * @return the associated data, can be null if the factory returned null.
  19594. */
  19595. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19596. if (!this._externalData) {
  19597. this._externalData = new BABYLON.StringDictionary();
  19598. }
  19599. return this._externalData.getOrAddWithFactory(key, factory);
  19600. };
  19601. /**
  19602. * Remove an externaly attached data from the Engine instance
  19603. * @param key the unique key that identifies the data
  19604. * @return true if the data was successfully removed, false if it doesn't exist
  19605. */
  19606. Scene.prototype.removeExternalData = function (key) {
  19607. return this._externalData.remove(key);
  19608. };
  19609. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19610. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19611. var material = subMesh.getMaterial();
  19612. if (mesh.showSubMeshesBoundingBox) {
  19613. var boundingInfo = subMesh.getBoundingInfo();
  19614. if (boundingInfo) {
  19615. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19616. }
  19617. }
  19618. if (material) {
  19619. // Render targets
  19620. if (material.getRenderTargetTextures) {
  19621. if (this._processedMaterials.indexOf(material) === -1) {
  19622. this._processedMaterials.push(material);
  19623. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19624. }
  19625. }
  19626. // Dispatch
  19627. this._activeIndices.addCount(subMesh.indexCount, false);
  19628. this._renderingManager.dispatch(subMesh);
  19629. }
  19630. }
  19631. };
  19632. Scene.prototype._isInIntermediateRendering = function () {
  19633. return this._intermediateRendering;
  19634. };
  19635. /**
  19636. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19637. */
  19638. Scene.prototype.freezeActiveMeshes = function () {
  19639. this._evaluateActiveMeshes();
  19640. this._activeMeshesFrozen = true;
  19641. return this;
  19642. };
  19643. /**
  19644. * Use this function to restart evaluating active meshes on every frame
  19645. */
  19646. Scene.prototype.unfreezeActiveMeshes = function () {
  19647. this._activeMeshesFrozen = false;
  19648. return this;
  19649. };
  19650. Scene.prototype._evaluateActiveMeshes = function () {
  19651. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19652. return;
  19653. }
  19654. if (!this.activeCamera) {
  19655. return;
  19656. }
  19657. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  19658. this.activeCamera._activeMeshes.reset();
  19659. this._activeMeshes.reset();
  19660. this._renderingManager.reset();
  19661. this._processedMaterials.reset();
  19662. this._activeParticleSystems.reset();
  19663. this._activeSkeletons.reset();
  19664. this._softwareSkinnedMeshes.reset();
  19665. if (this._boundingBoxRenderer) {
  19666. this._boundingBoxRenderer.reset();
  19667. }
  19668. // Meshes
  19669. var meshes;
  19670. var len;
  19671. if (this._selectionOctree) {
  19672. var selection = this._selectionOctree.select(this._frustumPlanes);
  19673. meshes = selection.data;
  19674. len = selection.length;
  19675. }
  19676. else {
  19677. len = this.meshes.length;
  19678. meshes = this.meshes;
  19679. }
  19680. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19681. var mesh = meshes[meshIndex];
  19682. if (mesh.isBlocked) {
  19683. continue;
  19684. }
  19685. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19686. if (!mesh.isReady() || !mesh.isEnabled()) {
  19687. continue;
  19688. }
  19689. mesh.computeWorldMatrix();
  19690. // Intersections
  19691. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19692. this._meshesForIntersections.pushNoDuplicate(mesh);
  19693. }
  19694. // Switch to current LOD
  19695. var meshLOD = mesh.getLOD(this.activeCamera);
  19696. if (!meshLOD) {
  19697. continue;
  19698. }
  19699. mesh._preActivate();
  19700. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19701. this._activeMeshes.push(mesh);
  19702. this.activeCamera._activeMeshes.push(mesh);
  19703. mesh._activate(this._renderId);
  19704. if (meshLOD !== mesh) {
  19705. meshLOD._activate(this._renderId);
  19706. }
  19707. this._activeMesh(mesh, meshLOD);
  19708. }
  19709. }
  19710. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  19711. // Particle systems
  19712. if (this.particlesEnabled) {
  19713. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  19714. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19715. var particleSystem = this.particleSystems[particleIndex];
  19716. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19717. continue;
  19718. }
  19719. var emitter = particleSystem.emitter;
  19720. if (!emitter.position || emitter.isEnabled()) {
  19721. this._activeParticleSystems.push(particleSystem);
  19722. particleSystem.animate();
  19723. this._renderingManager.dispatchParticles(particleSystem);
  19724. }
  19725. }
  19726. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  19727. }
  19728. };
  19729. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19730. if (mesh.skeleton && this.skeletonsEnabled) {
  19731. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19732. mesh.skeleton.prepare();
  19733. }
  19734. if (!mesh.computeBonesUsingShaders) {
  19735. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19736. }
  19737. }
  19738. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19739. var boundingInfo = sourceMesh.getBoundingInfo();
  19740. if (boundingInfo) {
  19741. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19742. }
  19743. }
  19744. if (mesh && mesh.subMeshes) {
  19745. // Submeshes Octrees
  19746. var len;
  19747. var subMeshes;
  19748. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19749. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19750. len = intersections.length;
  19751. subMeshes = intersections.data;
  19752. }
  19753. else {
  19754. subMeshes = mesh.subMeshes;
  19755. len = subMeshes.length;
  19756. }
  19757. for (var subIndex = 0; subIndex < len; subIndex++) {
  19758. var subMesh = subMeshes[subIndex];
  19759. this._evaluateSubMesh(subMesh, mesh);
  19760. }
  19761. }
  19762. };
  19763. Scene.prototype.updateTransformMatrix = function (force) {
  19764. if (!this.activeCamera) {
  19765. return;
  19766. }
  19767. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19768. };
  19769. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19770. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19771. };
  19772. Scene.prototype._renderForCamera = function (camera) {
  19773. if (camera && camera._skipRendering) {
  19774. return;
  19775. }
  19776. var engine = this._engine;
  19777. this.activeCamera = camera;
  19778. if (!this.activeCamera)
  19779. throw new Error("Active camera not set");
  19780. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19781. // Viewport
  19782. engine.setViewport(this.activeCamera.viewport);
  19783. // Camera
  19784. this.resetCachedMaterial();
  19785. this._renderId++;
  19786. this.activeCamera.update();
  19787. this.updateTransformMatrix();
  19788. if (camera._alternateCamera) {
  19789. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19790. this._alternateRendering = true;
  19791. }
  19792. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19793. // Meshes
  19794. this._evaluateActiveMeshes();
  19795. // Software skinning
  19796. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19797. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19798. mesh.applySkeleton(mesh.skeleton);
  19799. }
  19800. // Render targets
  19801. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19802. var needsRestoreFrameBuffer = false;
  19803. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19804. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19805. }
  19806. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19807. this._intermediateRendering = true;
  19808. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19809. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19810. var renderTarget = this._renderTargets.data[renderIndex];
  19811. if (renderTarget._shouldRender()) {
  19812. this._renderId++;
  19813. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19814. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19815. }
  19816. }
  19817. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19818. this._intermediateRendering = false;
  19819. this._renderId++;
  19820. needsRestoreFrameBuffer = true; // Restore back buffer
  19821. }
  19822. // Render HighlightLayer Texture
  19823. var stencilState = this._engine.getStencilBuffer();
  19824. var renderhighlights = false;
  19825. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19826. this._intermediateRendering = true;
  19827. for (var i = 0; i < this.highlightLayers.length; i++) {
  19828. var highlightLayer = this.highlightLayers[i];
  19829. if (highlightLayer.shouldRender() &&
  19830. (!highlightLayer.camera ||
  19831. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19832. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19833. renderhighlights = true;
  19834. var renderTarget = highlightLayer._mainTexture;
  19835. if (renderTarget._shouldRender()) {
  19836. this._renderId++;
  19837. renderTarget.render(false, false);
  19838. needsRestoreFrameBuffer = true;
  19839. }
  19840. }
  19841. }
  19842. this._intermediateRendering = false;
  19843. this._renderId++;
  19844. }
  19845. if (needsRestoreFrameBuffer) {
  19846. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19847. }
  19848. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19849. // Prepare Frame
  19850. this.postProcessManager._prepareFrame();
  19851. // Backgrounds
  19852. var layerIndex;
  19853. var layer;
  19854. if (this.layers.length) {
  19855. engine.setDepthBuffer(false);
  19856. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19857. layer = this.layers[layerIndex];
  19858. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19859. layer.render();
  19860. }
  19861. }
  19862. engine.setDepthBuffer(true);
  19863. }
  19864. // Activate HighlightLayer stencil
  19865. if (renderhighlights) {
  19866. this._engine.setStencilBuffer(true);
  19867. }
  19868. // Render
  19869. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  19870. this._renderingManager.render(null, null, true, true);
  19871. this.onAfterDrawPhaseObservable.notifyObservers(this);
  19872. // Restore HighlightLayer stencil
  19873. if (renderhighlights) {
  19874. this._engine.setStencilBuffer(stencilState);
  19875. }
  19876. // Bounding boxes
  19877. if (this._boundingBoxRenderer) {
  19878. this._boundingBoxRenderer.render();
  19879. }
  19880. // Lens flares
  19881. if (this.lensFlaresEnabled) {
  19882. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19883. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19884. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19885. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19886. lensFlareSystem.render();
  19887. }
  19888. }
  19889. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19890. }
  19891. // Foregrounds
  19892. if (this.layers.length) {
  19893. engine.setDepthBuffer(false);
  19894. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19895. layer = this.layers[layerIndex];
  19896. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19897. layer.render();
  19898. }
  19899. }
  19900. engine.setDepthBuffer(true);
  19901. }
  19902. // Highlight Layer
  19903. if (renderhighlights) {
  19904. engine.setDepthBuffer(false);
  19905. for (var i = 0; i < this.highlightLayers.length; i++) {
  19906. if (this.highlightLayers[i].shouldRender()) {
  19907. this.highlightLayers[i].render();
  19908. }
  19909. }
  19910. engine.setDepthBuffer(true);
  19911. }
  19912. // Finalize frame
  19913. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19914. // Reset some special arrays
  19915. this._renderTargets.reset();
  19916. this._alternateRendering = false;
  19917. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19918. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19919. };
  19920. Scene.prototype._processSubCameras = function (camera) {
  19921. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19922. this._renderForCamera(camera);
  19923. return;
  19924. }
  19925. // Update camera
  19926. if (this.activeCamera) {
  19927. this.activeCamera.update();
  19928. }
  19929. // rig cameras
  19930. for (var index = 0; index < camera._rigCameras.length; index++) {
  19931. this._renderForCamera(camera._rigCameras[index]);
  19932. }
  19933. this.activeCamera = camera;
  19934. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19935. };
  19936. Scene.prototype._checkIntersections = function () {
  19937. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19938. var sourceMesh = this._meshesForIntersections.data[index];
  19939. if (!sourceMesh.actionManager) {
  19940. continue;
  19941. }
  19942. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19943. var action = sourceMesh.actionManager.actions[actionIndex];
  19944. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19945. var parameters = action.getTriggerParameter();
  19946. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19947. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19948. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19949. if (areIntersecting && currentIntersectionInProgress === -1) {
  19950. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19951. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19952. sourceMesh._intersectionsInProgress.push(otherMesh);
  19953. }
  19954. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19955. sourceMesh._intersectionsInProgress.push(otherMesh);
  19956. }
  19957. }
  19958. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19959. //They intersected, and now they don't.
  19960. //is this trigger an exit trigger? execute an event.
  19961. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19962. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19963. }
  19964. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19965. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19966. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19967. }
  19968. }
  19969. }
  19970. }
  19971. }
  19972. };
  19973. Scene.prototype.render = function () {
  19974. if (this.isDisposed) {
  19975. return;
  19976. }
  19977. this._activeParticles.fetchNewFrame();
  19978. this._totalVertices.fetchNewFrame();
  19979. this._activeIndices.fetchNewFrame();
  19980. this._activeBones.fetchNewFrame();
  19981. this._meshesForIntersections.reset();
  19982. this.resetCachedMaterial();
  19983. this.onBeforeAnimationsObservable.notifyObservers(this);
  19984. // Actions
  19985. if (this.actionManager) {
  19986. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  19987. }
  19988. //Simplification Queue
  19989. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19990. this.simplificationQueue.executeNext();
  19991. }
  19992. if (this._engine.isDeterministicLockStep()) {
  19993. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19994. var defaultTimeStep = (60.0 / 1000.0);
  19995. if (this._physicsEngine) {
  19996. defaultTimeStep = this._physicsEngine.getTimeStep();
  19997. }
  19998. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19999. this._timeAccumulator += deltaTime;
  20000. // compute the amount of fixed steps we should have taken since the last step
  20001. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  20002. internalSteps = Math.min(internalSteps, maxSubSteps);
  20003. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  20004. this.onBeforeStepObservable.notifyObservers(this);
  20005. // Animations
  20006. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  20007. this._animate();
  20008. this.onAfterAnimationsObservable.notifyObservers(this);
  20009. // Physics
  20010. if (this._physicsEngine) {
  20011. this.onBeforePhysicsObservable.notifyObservers(this);
  20012. this._physicsEngine._step(defaultTimeStep);
  20013. this.onAfterPhysicsObservable.notifyObservers(this);
  20014. }
  20015. this._timeAccumulator -= defaultTimeStep;
  20016. this.onAfterStepObservable.notifyObservers(this);
  20017. this._currentStepId++;
  20018. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  20019. this._evaluateActiveMeshes();
  20020. }
  20021. }
  20022. }
  20023. else {
  20024. // Animations
  20025. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20026. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20027. this._animate();
  20028. this.onAfterAnimationsObservable.notifyObservers(this);
  20029. // Physics
  20030. if (this._physicsEngine) {
  20031. this.onBeforePhysicsObservable.notifyObservers(this);
  20032. this._physicsEngine._step(deltaTime / 1000.0);
  20033. this.onAfterPhysicsObservable.notifyObservers(this);
  20034. }
  20035. }
  20036. // Before render
  20037. this.onBeforeRenderObservable.notifyObservers(this);
  20038. // Customs render targets
  20039. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20040. var engine = this.getEngine();
  20041. var currentActiveCamera = this.activeCamera;
  20042. if (this.renderTargetsEnabled) {
  20043. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20044. this._intermediateRendering = true;
  20045. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20046. var renderTarget = this.customRenderTargets[customIndex];
  20047. if (renderTarget._shouldRender()) {
  20048. this._renderId++;
  20049. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20050. if (!this.activeCamera)
  20051. throw new Error("Active camera not set");
  20052. // Viewport
  20053. engine.setViewport(this.activeCamera.viewport);
  20054. // Camera
  20055. this.updateTransformMatrix();
  20056. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20057. }
  20058. }
  20059. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20060. this._intermediateRendering = false;
  20061. this._renderId++;
  20062. }
  20063. // Restore back buffer
  20064. if (this.customRenderTargets.length > 0) {
  20065. engine.restoreDefaultFramebuffer();
  20066. }
  20067. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20068. this.activeCamera = currentActiveCamera;
  20069. // Procedural textures
  20070. if (this.proceduralTexturesEnabled) {
  20071. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20072. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20073. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20074. if (proceduralTexture._shouldRender()) {
  20075. proceduralTexture.render();
  20076. }
  20077. }
  20078. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20079. }
  20080. // Clear
  20081. if (this.autoClearDepthAndStencil || this.autoClear) {
  20082. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20083. }
  20084. // Shadows
  20085. if (this.shadowsEnabled) {
  20086. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20087. var light = this.lights[lightIndex];
  20088. var shadowGenerator = light.getShadowGenerator();
  20089. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20090. var shadowMap = (shadowGenerator.getShadowMap());
  20091. if (this.textures.indexOf(shadowMap) !== -1) {
  20092. this._renderTargets.push(shadowMap);
  20093. }
  20094. }
  20095. }
  20096. }
  20097. // Depth renderer
  20098. if (this._depthRenderer) {
  20099. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20100. }
  20101. // Geometry renderer
  20102. if (this._geometryBufferRenderer) {
  20103. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20104. }
  20105. // RenderPipeline
  20106. if (this._postProcessRenderPipelineManager) {
  20107. this._postProcessRenderPipelineManager.update();
  20108. }
  20109. // Multi-cameras?
  20110. if (this.activeCameras.length > 0) {
  20111. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20112. if (cameraIndex > 0) {
  20113. this._engine.clear(null, false, true, true);
  20114. }
  20115. this._processSubCameras(this.activeCameras[cameraIndex]);
  20116. }
  20117. }
  20118. else {
  20119. if (!this.activeCamera) {
  20120. throw new Error("No camera defined");
  20121. }
  20122. this._processSubCameras(this.activeCamera);
  20123. }
  20124. // Intersection checks
  20125. this._checkIntersections();
  20126. // Update the audio listener attached to the camera
  20127. if (BABYLON.AudioEngine) {
  20128. this._updateAudioParameters();
  20129. }
  20130. // After render
  20131. if (this.afterRender) {
  20132. this.afterRender();
  20133. }
  20134. this.onAfterRenderObservable.notifyObservers(this);
  20135. // Cleaning
  20136. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20137. var data = this._toBeDisposed.data[index];
  20138. if (data) {
  20139. data.dispose();
  20140. }
  20141. this._toBeDisposed[index] = null;
  20142. }
  20143. this._toBeDisposed.reset();
  20144. if (this.dumpNextRenderTargets) {
  20145. this.dumpNextRenderTargets = false;
  20146. }
  20147. this._activeBones.addCount(0, true);
  20148. this._activeIndices.addCount(0, true);
  20149. this._activeParticles.addCount(0, true);
  20150. };
  20151. Scene.prototype._updateAudioParameters = function () {
  20152. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20153. return;
  20154. }
  20155. var listeningCamera;
  20156. var audioEngine = BABYLON.Engine.audioEngine;
  20157. if (this.activeCameras.length > 0) {
  20158. listeningCamera = this.activeCameras[0];
  20159. }
  20160. else {
  20161. listeningCamera = this.activeCamera;
  20162. }
  20163. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20164. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20165. // for VR cameras
  20166. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20167. listeningCamera = listeningCamera.rigCameras[0];
  20168. }
  20169. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20170. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20171. cameraDirection.normalize();
  20172. // To avoid some errors on GearVR
  20173. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20174. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20175. }
  20176. var i;
  20177. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20178. var sound = this.mainSoundTrack.soundCollection[i];
  20179. if (sound.useCustomAttenuation) {
  20180. sound.updateDistanceFromListener();
  20181. }
  20182. }
  20183. for (i = 0; i < this.soundTracks.length; i++) {
  20184. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20185. sound = this.soundTracks[i].soundCollection[j];
  20186. if (sound.useCustomAttenuation) {
  20187. sound.updateDistanceFromListener();
  20188. }
  20189. }
  20190. }
  20191. }
  20192. };
  20193. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20194. // Audio
  20195. get: function () {
  20196. return this._audioEnabled;
  20197. },
  20198. set: function (value) {
  20199. this._audioEnabled = value;
  20200. if (BABYLON.AudioEngine) {
  20201. if (this._audioEnabled) {
  20202. this._enableAudio();
  20203. }
  20204. else {
  20205. this._disableAudio();
  20206. }
  20207. }
  20208. },
  20209. enumerable: true,
  20210. configurable: true
  20211. });
  20212. Scene.prototype._disableAudio = function () {
  20213. var i;
  20214. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20215. this.mainSoundTrack.soundCollection[i].pause();
  20216. }
  20217. for (i = 0; i < this.soundTracks.length; i++) {
  20218. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20219. this.soundTracks[i].soundCollection[j].pause();
  20220. }
  20221. }
  20222. };
  20223. Scene.prototype._enableAudio = function () {
  20224. var i;
  20225. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20226. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20227. this.mainSoundTrack.soundCollection[i].play();
  20228. }
  20229. }
  20230. for (i = 0; i < this.soundTracks.length; i++) {
  20231. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20232. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20233. this.soundTracks[i].soundCollection[j].play();
  20234. }
  20235. }
  20236. }
  20237. };
  20238. Object.defineProperty(Scene.prototype, "headphone", {
  20239. get: function () {
  20240. return this._headphone;
  20241. },
  20242. set: function (value) {
  20243. this._headphone = value;
  20244. if (BABYLON.AudioEngine) {
  20245. if (this._headphone) {
  20246. this._switchAudioModeForHeadphones();
  20247. }
  20248. else {
  20249. this._switchAudioModeForNormalSpeakers();
  20250. }
  20251. }
  20252. },
  20253. enumerable: true,
  20254. configurable: true
  20255. });
  20256. Scene.prototype._switchAudioModeForHeadphones = function () {
  20257. this.mainSoundTrack.switchPanningModelToHRTF();
  20258. for (var i = 0; i < this.soundTracks.length; i++) {
  20259. this.soundTracks[i].switchPanningModelToHRTF();
  20260. }
  20261. };
  20262. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20263. this.mainSoundTrack.switchPanningModelToEqualPower();
  20264. for (var i = 0; i < this.soundTracks.length; i++) {
  20265. this.soundTracks[i].switchPanningModelToEqualPower();
  20266. }
  20267. };
  20268. Scene.prototype.enableDepthRenderer = function () {
  20269. if (this._depthRenderer) {
  20270. return this._depthRenderer;
  20271. }
  20272. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20273. return this._depthRenderer;
  20274. };
  20275. Scene.prototype.disableDepthRenderer = function () {
  20276. if (!this._depthRenderer) {
  20277. return;
  20278. }
  20279. this._depthRenderer.dispose();
  20280. this._depthRenderer = null;
  20281. };
  20282. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20283. if (ratio === void 0) { ratio = 1; }
  20284. if (this._geometryBufferRenderer) {
  20285. return this._geometryBufferRenderer;
  20286. }
  20287. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20288. if (!this._geometryBufferRenderer.isSupported) {
  20289. this._geometryBufferRenderer = null;
  20290. }
  20291. return this._geometryBufferRenderer;
  20292. };
  20293. Scene.prototype.disableGeometryBufferRenderer = function () {
  20294. if (!this._geometryBufferRenderer) {
  20295. return;
  20296. }
  20297. this._geometryBufferRenderer.dispose();
  20298. this._geometryBufferRenderer = null;
  20299. };
  20300. Scene.prototype.freezeMaterials = function () {
  20301. for (var i = 0; i < this.materials.length; i++) {
  20302. this.materials[i].freeze();
  20303. }
  20304. };
  20305. Scene.prototype.unfreezeMaterials = function () {
  20306. for (var i = 0; i < this.materials.length; i++) {
  20307. this.materials[i].unfreeze();
  20308. }
  20309. };
  20310. Scene.prototype.dispose = function () {
  20311. this.beforeRender = null;
  20312. this.afterRender = null;
  20313. this.skeletons = [];
  20314. this.morphTargetManagers = [];
  20315. this.importedMeshesFiles = new Array();
  20316. this.resetCachedMaterial();
  20317. if (this._depthRenderer) {
  20318. this._depthRenderer.dispose();
  20319. }
  20320. if (this._gamepadManager) {
  20321. this._gamepadManager.dispose();
  20322. this._gamepadManager = null;
  20323. }
  20324. // Smart arrays
  20325. if (this.activeCamera) {
  20326. this.activeCamera._activeMeshes.dispose();
  20327. this.activeCamera = null;
  20328. }
  20329. this._activeMeshes.dispose();
  20330. this._renderingManager.dispose();
  20331. this._processedMaterials.dispose();
  20332. this._activeParticleSystems.dispose();
  20333. this._activeSkeletons.dispose();
  20334. this._softwareSkinnedMeshes.dispose();
  20335. this._renderTargets.dispose();
  20336. if (this._boundingBoxRenderer) {
  20337. this._boundingBoxRenderer.dispose();
  20338. }
  20339. this._meshesForIntersections.dispose();
  20340. this._toBeDisposed.dispose();
  20341. // Debug layer
  20342. if (this._debugLayer) {
  20343. this._debugLayer.hide();
  20344. }
  20345. // Events
  20346. this.onDisposeObservable.notifyObservers(this);
  20347. this.onDisposeObservable.clear();
  20348. this.onBeforeRenderObservable.clear();
  20349. this.onAfterRenderObservable.clear();
  20350. this.OnBeforeRenderTargetsRenderObservable.clear();
  20351. this.OnAfterRenderTargetsRenderObservable.clear();
  20352. this.onAfterStepObservable.clear();
  20353. this.onBeforeStepObservable.clear();
  20354. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20355. this.onAfterActiveMeshesEvaluationObservable.clear();
  20356. this.onBeforeParticlesRenderingObservable.clear();
  20357. this.onAfterParticlesRenderingObservable.clear();
  20358. this.onBeforeSpritesRenderingObservable.clear();
  20359. this.onAfterSpritesRenderingObservable.clear();
  20360. this.onBeforeDrawPhaseObservable.clear();
  20361. this.onAfterDrawPhaseObservable.clear();
  20362. this.onBeforePhysicsObservable.clear();
  20363. this.onAfterPhysicsObservable.clear();
  20364. this.onBeforeAnimationsObservable.clear();
  20365. this.onAfterAnimationsObservable.clear();
  20366. this.detachControl();
  20367. // Release sounds & sounds tracks
  20368. if (BABYLON.AudioEngine) {
  20369. this.disposeSounds();
  20370. }
  20371. // VR Helper
  20372. if (this.VRHelper) {
  20373. this.VRHelper.dispose();
  20374. }
  20375. // Detach cameras
  20376. var canvas = this._engine.getRenderingCanvas();
  20377. if (canvas) {
  20378. var index;
  20379. for (index = 0; index < this.cameras.length; index++) {
  20380. this.cameras[index].detachControl(canvas);
  20381. }
  20382. }
  20383. // Release lights
  20384. while (this.lights.length) {
  20385. this.lights[0].dispose();
  20386. }
  20387. // Release meshes
  20388. while (this.meshes.length) {
  20389. this.meshes[0].dispose(true);
  20390. }
  20391. // Release cameras
  20392. while (this.cameras.length) {
  20393. this.cameras[0].dispose();
  20394. }
  20395. // Release materials
  20396. if (this.defaultMaterial) {
  20397. this.defaultMaterial.dispose();
  20398. }
  20399. while (this.multiMaterials.length) {
  20400. this.multiMaterials[0].dispose();
  20401. }
  20402. while (this.materials.length) {
  20403. this.materials[0].dispose();
  20404. }
  20405. // Release particles
  20406. while (this.particleSystems.length) {
  20407. this.particleSystems[0].dispose();
  20408. }
  20409. // Release sprites
  20410. while (this.spriteManagers.length) {
  20411. this.spriteManagers[0].dispose();
  20412. }
  20413. // Release postProcesses
  20414. while (this.postProcesses.length) {
  20415. this.postProcesses[0].dispose();
  20416. }
  20417. // Release layers
  20418. while (this.layers.length) {
  20419. this.layers[0].dispose();
  20420. }
  20421. while (this.highlightLayers.length) {
  20422. this.highlightLayers[0].dispose();
  20423. }
  20424. // Release textures
  20425. while (this.textures.length) {
  20426. this.textures[0].dispose();
  20427. }
  20428. // Release UBO
  20429. this._sceneUbo.dispose();
  20430. if (this._alternateSceneUbo) {
  20431. this._alternateSceneUbo.dispose();
  20432. }
  20433. // Post-processes
  20434. this.postProcessManager.dispose();
  20435. if (this._postProcessRenderPipelineManager) {
  20436. this._postProcessRenderPipelineManager.dispose();
  20437. }
  20438. // Physics
  20439. if (this._physicsEngine) {
  20440. this.disablePhysicsEngine();
  20441. }
  20442. // Remove from engine
  20443. index = this._engine.scenes.indexOf(this);
  20444. if (index > -1) {
  20445. this._engine.scenes.splice(index, 1);
  20446. }
  20447. this._engine.wipeCaches();
  20448. this._isDisposed = true;
  20449. };
  20450. Object.defineProperty(Scene.prototype, "isDisposed", {
  20451. get: function () {
  20452. return this._isDisposed;
  20453. },
  20454. enumerable: true,
  20455. configurable: true
  20456. });
  20457. // Release sounds & sounds tracks
  20458. Scene.prototype.disposeSounds = function () {
  20459. if (!this._mainSoundTrack) {
  20460. return;
  20461. }
  20462. this.mainSoundTrack.dispose();
  20463. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20464. this.soundTracks[scIndex].dispose();
  20465. }
  20466. };
  20467. // Octrees
  20468. Scene.prototype.getWorldExtends = function () {
  20469. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20470. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20471. for (var index = 0; index < this.meshes.length; index++) {
  20472. var mesh = this.meshes[index];
  20473. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20474. continue;
  20475. }
  20476. mesh.computeWorldMatrix(true);
  20477. var boundingInfo = mesh.getBoundingInfo();
  20478. if (boundingInfo) {
  20479. var minBox = boundingInfo.boundingBox.minimumWorld;
  20480. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20481. BABYLON.Tools.CheckExtends(minBox, min, max);
  20482. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20483. }
  20484. }
  20485. return {
  20486. min: min,
  20487. max: max
  20488. };
  20489. };
  20490. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20491. if (maxCapacity === void 0) { maxCapacity = 64; }
  20492. if (maxDepth === void 0) { maxDepth = 2; }
  20493. if (!this._selectionOctree) {
  20494. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20495. }
  20496. var worldExtends = this.getWorldExtends();
  20497. // Update octree
  20498. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20499. return this._selectionOctree;
  20500. };
  20501. // Picking
  20502. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20503. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20504. var engine = this._engine;
  20505. if (!camera) {
  20506. if (!this.activeCamera)
  20507. throw new Error("Active camera not set");
  20508. camera = this.activeCamera;
  20509. }
  20510. var cameraViewport = camera.viewport;
  20511. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20512. // Moving coordinates to local viewport world
  20513. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20514. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20515. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20516. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20517. };
  20518. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20519. if (!BABYLON.PickingInfo) {
  20520. return null;
  20521. }
  20522. var engine = this._engine;
  20523. if (!camera) {
  20524. if (!this.activeCamera)
  20525. throw new Error("Active camera not set");
  20526. camera = this.activeCamera;
  20527. }
  20528. var cameraViewport = camera.viewport;
  20529. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20530. var identity = BABYLON.Matrix.Identity();
  20531. // Moving coordinates to local viewport world
  20532. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20533. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20534. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20535. };
  20536. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20537. if (!BABYLON.PickingInfo) {
  20538. return null;
  20539. }
  20540. var pickingInfo = null;
  20541. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20542. var mesh = this.meshes[meshIndex];
  20543. if (predicate) {
  20544. if (!predicate(mesh)) {
  20545. continue;
  20546. }
  20547. }
  20548. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20549. continue;
  20550. }
  20551. var world = mesh.getWorldMatrix();
  20552. var ray = rayFunction(world);
  20553. var result = mesh.intersects(ray, fastCheck);
  20554. if (!result || !result.hit)
  20555. continue;
  20556. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20557. continue;
  20558. pickingInfo = result;
  20559. if (fastCheck) {
  20560. break;
  20561. }
  20562. }
  20563. return pickingInfo || new BABYLON.PickingInfo();
  20564. };
  20565. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20566. if (!BABYLON.PickingInfo) {
  20567. return null;
  20568. }
  20569. var pickingInfos = new Array();
  20570. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20571. var mesh = this.meshes[meshIndex];
  20572. if (predicate) {
  20573. if (!predicate(mesh)) {
  20574. continue;
  20575. }
  20576. }
  20577. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20578. continue;
  20579. }
  20580. var world = mesh.getWorldMatrix();
  20581. var ray = rayFunction(world);
  20582. var result = mesh.intersects(ray, false);
  20583. if (!result || !result.hit)
  20584. continue;
  20585. pickingInfos.push(result);
  20586. }
  20587. return pickingInfos;
  20588. };
  20589. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20590. if (!BABYLON.PickingInfo) {
  20591. return null;
  20592. }
  20593. var pickingInfo = null;
  20594. if (!camera) {
  20595. if (!this.activeCamera) {
  20596. return null;
  20597. }
  20598. camera = this.activeCamera;
  20599. }
  20600. if (this.spriteManagers.length > 0) {
  20601. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20602. var spriteManager = this.spriteManagers[spriteIndex];
  20603. if (!spriteManager.isPickable) {
  20604. continue;
  20605. }
  20606. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20607. if (!result || !result.hit)
  20608. continue;
  20609. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20610. continue;
  20611. pickingInfo = result;
  20612. if (fastCheck) {
  20613. break;
  20614. }
  20615. }
  20616. }
  20617. return pickingInfo || new BABYLON.PickingInfo();
  20618. };
  20619. /** Launch a ray to try to pick a mesh in the scene
  20620. * @param x position on screen
  20621. * @param y position on screen
  20622. * @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
  20623. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20624. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20625. */
  20626. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20627. var _this = this;
  20628. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20629. };
  20630. /** Launch a ray to try to pick a sprite in the scene
  20631. * @param x position on screen
  20632. * @param y position on screen
  20633. * @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
  20634. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20635. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20636. */
  20637. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20638. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20639. if (!ray) {
  20640. return null;
  20641. }
  20642. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20643. };
  20644. /** Use the given ray to pick a mesh in the scene
  20645. * @param ray The ray to use to pick meshes
  20646. * @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
  20647. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20648. */
  20649. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20650. var _this = this;
  20651. return this._internalPick(function (world) {
  20652. if (!_this._pickWithRayInverseMatrix) {
  20653. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20654. }
  20655. world.invertToRef(_this._pickWithRayInverseMatrix);
  20656. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20657. }, predicate, fastCheck);
  20658. };
  20659. /**
  20660. * Launch a ray to try to pick a mesh in the scene
  20661. * @param x X position on screen
  20662. * @param y Y position on screen
  20663. * @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
  20664. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20665. */
  20666. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20667. var _this = this;
  20668. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20669. };
  20670. /**
  20671. * Launch a ray to try to pick a mesh in the scene
  20672. * @param ray Ray to use
  20673. * @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
  20674. */
  20675. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20676. var _this = this;
  20677. return this._internalMultiPick(function (world) {
  20678. if (!_this._pickWithRayInverseMatrix) {
  20679. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20680. }
  20681. world.invertToRef(_this._pickWithRayInverseMatrix);
  20682. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20683. }, predicate);
  20684. };
  20685. Scene.prototype.setPointerOverMesh = function (mesh) {
  20686. if (this._pointerOverMesh === mesh) {
  20687. return;
  20688. }
  20689. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20690. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20691. }
  20692. this._pointerOverMesh = mesh;
  20693. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20694. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20695. }
  20696. };
  20697. Scene.prototype.getPointerOverMesh = function () {
  20698. return this._pointerOverMesh;
  20699. };
  20700. Scene.prototype.setPointerOverSprite = function (sprite) {
  20701. if (this._pointerOverSprite === sprite) {
  20702. return;
  20703. }
  20704. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20705. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20706. }
  20707. this._pointerOverSprite = sprite;
  20708. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20709. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20710. }
  20711. };
  20712. Scene.prototype.getPointerOverSprite = function () {
  20713. return this._pointerOverSprite;
  20714. };
  20715. // Physics
  20716. Scene.prototype.getPhysicsEngine = function () {
  20717. return this._physicsEngine;
  20718. };
  20719. /**
  20720. * Enables physics to the current scene
  20721. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20722. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20723. * @return {boolean} was the physics engine initialized
  20724. */
  20725. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20726. if (gravity === void 0) { gravity = null; }
  20727. if (this._physicsEngine) {
  20728. return true;
  20729. }
  20730. try {
  20731. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20732. return true;
  20733. }
  20734. catch (e) {
  20735. BABYLON.Tools.Error(e.message);
  20736. return false;
  20737. }
  20738. };
  20739. Scene.prototype.disablePhysicsEngine = function () {
  20740. if (!this._physicsEngine) {
  20741. return;
  20742. }
  20743. this._physicsEngine.dispose();
  20744. this._physicsEngine = null;
  20745. };
  20746. Scene.prototype.isPhysicsEnabled = function () {
  20747. return this._physicsEngine !== undefined;
  20748. };
  20749. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20750. var mesh = compound.parts[0].mesh;
  20751. if (mesh.physicsImpostor) {
  20752. mesh.physicsImpostor.dispose();
  20753. mesh.physicsImpostor = null;
  20754. }
  20755. };
  20756. // Misc.
  20757. Scene.prototype._rebuildGeometries = function () {
  20758. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20759. var geometry = _a[_i];
  20760. geometry._rebuild();
  20761. }
  20762. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20763. var mesh = _c[_b];
  20764. mesh._rebuild();
  20765. }
  20766. if (this.postProcessManager) {
  20767. this.postProcessManager._rebuild();
  20768. }
  20769. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20770. var layer = _e[_d];
  20771. layer._rebuild();
  20772. }
  20773. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20774. var highlightLayer = _g[_f];
  20775. highlightLayer._rebuild();
  20776. }
  20777. if (this._boundingBoxRenderer) {
  20778. this._boundingBoxRenderer._rebuild();
  20779. }
  20780. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20781. var system = _j[_h];
  20782. system.rebuild();
  20783. }
  20784. if (this._postProcessRenderPipelineManager) {
  20785. this._postProcessRenderPipelineManager._rebuild();
  20786. }
  20787. };
  20788. Scene.prototype._rebuildTextures = function () {
  20789. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20790. var texture = _a[_i];
  20791. texture._rebuild();
  20792. }
  20793. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20794. };
  20795. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20796. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20797. if (replace === void 0) { replace = false; }
  20798. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20799. // Dispose existing camera or light in replace mode.
  20800. if (replace) {
  20801. if (this.activeCamera) {
  20802. this.activeCamera.dispose();
  20803. this.activeCamera = null;
  20804. }
  20805. if (this.lights) {
  20806. for (var i = 0; i < this.lights.length; i++) {
  20807. this.lights[i].dispose();
  20808. }
  20809. }
  20810. }
  20811. // Light
  20812. if (this.lights.length === 0) {
  20813. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20814. }
  20815. // Camera
  20816. if (!this.activeCamera) {
  20817. var worldExtends = this.getWorldExtends();
  20818. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20819. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20820. var camera;
  20821. var radius = worldSize.length() * 1.5;
  20822. if (createArcRotateCamera) {
  20823. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20824. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20825. arcRotateCamera.wheelPrecision = 100 / radius;
  20826. camera = arcRotateCamera;
  20827. }
  20828. else {
  20829. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20830. freeCamera.setTarget(worldCenter);
  20831. camera = freeCamera;
  20832. }
  20833. camera.minZ = radius * 0.01;
  20834. camera.maxZ = radius * 100;
  20835. camera.speed = radius * 0.2;
  20836. this.activeCamera = camera;
  20837. var canvas = this.getEngine().getRenderingCanvas();
  20838. if (attachCameraControls && canvas) {
  20839. camera.attachControl(canvas);
  20840. }
  20841. }
  20842. };
  20843. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20844. if (pbr === void 0) { pbr = false; }
  20845. if (scale === void 0) { scale = 1000; }
  20846. if (blur === void 0) { blur = 0; }
  20847. if (environmentTexture) {
  20848. this.environmentTexture = environmentTexture;
  20849. }
  20850. if (!this.environmentTexture) {
  20851. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20852. return null;
  20853. }
  20854. // Skybox
  20855. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20856. if (pbr) {
  20857. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20858. hdrSkyboxMaterial.backFaceCulling = false;
  20859. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20860. if (hdrSkyboxMaterial.reflectionTexture) {
  20861. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20862. }
  20863. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20864. hdrSkyboxMaterial.disableLighting = true;
  20865. hdrSkyboxMaterial.twoSidedLighting = true;
  20866. hdrSkybox.infiniteDistance = true;
  20867. hdrSkybox.material = hdrSkyboxMaterial;
  20868. }
  20869. else {
  20870. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20871. skyboxMaterial.backFaceCulling = false;
  20872. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20873. if (skyboxMaterial.reflectionTexture) {
  20874. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20875. }
  20876. skyboxMaterial.disableLighting = true;
  20877. hdrSkybox.infiniteDistance = true;
  20878. hdrSkybox.material = skyboxMaterial;
  20879. }
  20880. return hdrSkybox;
  20881. };
  20882. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20883. if (webVROptions === void 0) { webVROptions = {}; }
  20884. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20885. };
  20886. // Tags
  20887. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20888. if (tagsQuery === undefined) {
  20889. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20890. return list;
  20891. }
  20892. var listByTags = [];
  20893. forEach = forEach || (function (item) { return; });
  20894. for (var i in list) {
  20895. var item = list[i];
  20896. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20897. listByTags.push(item);
  20898. forEach(item);
  20899. }
  20900. }
  20901. return listByTags;
  20902. };
  20903. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20904. return this._getByTags(this.meshes, tagsQuery, forEach);
  20905. };
  20906. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20907. return this._getByTags(this.cameras, tagsQuery, forEach);
  20908. };
  20909. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20910. return this._getByTags(this.lights, tagsQuery, forEach);
  20911. };
  20912. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20913. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20914. };
  20915. /**
  20916. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20917. * This allowed control for front to back rendering or reversly depending of the special needs.
  20918. *
  20919. * @param renderingGroupId The rendering group id corresponding to its index
  20920. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20921. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20922. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20923. */
  20924. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20925. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20926. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20927. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20928. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20929. };
  20930. /**
  20931. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20932. *
  20933. * @param renderingGroupId The rendering group id corresponding to its index
  20934. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20935. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20936. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20937. */
  20938. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20939. if (depth === void 0) { depth = true; }
  20940. if (stencil === void 0) { stencil = true; }
  20941. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20942. };
  20943. /**
  20944. * Will flag all materials as dirty to trigger new shader compilation
  20945. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20946. */
  20947. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20948. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20949. var material = _a[_i];
  20950. if (predicate && !predicate(material)) {
  20951. continue;
  20952. }
  20953. material.markAsDirty(flag);
  20954. }
  20955. };
  20956. // Statics
  20957. Scene._FOGMODE_NONE = 0;
  20958. Scene._FOGMODE_EXP = 1;
  20959. Scene._FOGMODE_EXP2 = 2;
  20960. Scene._FOGMODE_LINEAR = 3;
  20961. Scene._uniqueIdCounter = 0;
  20962. Scene.MinDeltaTime = 1.0;
  20963. Scene.MaxDeltaTime = 1000.0;
  20964. /** The distance in pixel that you have to move to prevent some events */
  20965. Scene.DragMovementThreshold = 10; // in pixels
  20966. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20967. Scene.LongPressDelay = 500; // in milliseconds
  20968. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20969. Scene.DoubleClickDelay = 300; // in milliseconds
  20970. /** If you need to check double click without raising a single click at first click, enable this flag */
  20971. Scene.ExclusiveDoubleClickMode = false;
  20972. return Scene;
  20973. }());
  20974. BABYLON.Scene = Scene;
  20975. })(BABYLON || (BABYLON = {}));
  20976. //# sourceMappingURL=babylon.scene.js.map
  20977. var BABYLON;
  20978. (function (BABYLON) {
  20979. var Buffer = /** @class */ (function () {
  20980. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20981. if (instanced === void 0) { instanced = false; }
  20982. if (engine instanceof BABYLON.Mesh) {
  20983. this._engine = engine.getScene().getEngine();
  20984. }
  20985. else {
  20986. this._engine = engine;
  20987. }
  20988. this._updatable = updatable;
  20989. this._data = data;
  20990. this._strideSize = stride;
  20991. if (!postponeInternalCreation) {
  20992. this.create();
  20993. }
  20994. this._instanced = instanced;
  20995. this._instanceDivisor = instanced ? 1 : 0;
  20996. }
  20997. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20998. // a lot of these parameters are ignored as they are overriden by the buffer
  20999. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21000. };
  21001. // Properties
  21002. Buffer.prototype.isUpdatable = function () {
  21003. return this._updatable;
  21004. };
  21005. Buffer.prototype.getData = function () {
  21006. return this._data;
  21007. };
  21008. Buffer.prototype.getBuffer = function () {
  21009. return this._buffer;
  21010. };
  21011. Buffer.prototype.getStrideSize = function () {
  21012. return this._strideSize;
  21013. };
  21014. Buffer.prototype.getIsInstanced = function () {
  21015. return this._instanced;
  21016. };
  21017. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21018. get: function () {
  21019. return this._instanceDivisor;
  21020. },
  21021. set: function (value) {
  21022. this._instanceDivisor = value;
  21023. if (value == 0) {
  21024. this._instanced = false;
  21025. }
  21026. else {
  21027. this._instanced = true;
  21028. }
  21029. },
  21030. enumerable: true,
  21031. configurable: true
  21032. });
  21033. // Methods
  21034. Buffer.prototype.create = function (data) {
  21035. if (data === void 0) { data = null; }
  21036. if (!data && this._buffer) {
  21037. return; // nothing to do
  21038. }
  21039. data = data || this._data;
  21040. if (!data) {
  21041. return;
  21042. }
  21043. if (!this._buffer) {
  21044. if (this._updatable) {
  21045. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21046. this._data = data;
  21047. }
  21048. else {
  21049. this._buffer = this._engine.createVertexBuffer(data);
  21050. }
  21051. }
  21052. else if (this._updatable) {
  21053. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21054. this._data = data;
  21055. }
  21056. };
  21057. Buffer.prototype._rebuild = function () {
  21058. this._buffer = null;
  21059. this.create(this._data);
  21060. };
  21061. Buffer.prototype.update = function (data) {
  21062. this.create(data);
  21063. };
  21064. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21065. if (!this._buffer) {
  21066. return;
  21067. }
  21068. if (this._updatable) {
  21069. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21070. this._data = null;
  21071. }
  21072. };
  21073. Buffer.prototype.dispose = function () {
  21074. if (!this._buffer) {
  21075. return;
  21076. }
  21077. if (this._engine._releaseBuffer(this._buffer)) {
  21078. this._buffer = null;
  21079. }
  21080. };
  21081. return Buffer;
  21082. }());
  21083. BABYLON.Buffer = Buffer;
  21084. })(BABYLON || (BABYLON = {}));
  21085. //# sourceMappingURL=babylon.buffer.js.map
  21086. var BABYLON;
  21087. (function (BABYLON) {
  21088. var VertexBuffer = /** @class */ (function () {
  21089. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21090. if (!stride) {
  21091. // Deduce stride from kind
  21092. switch (kind) {
  21093. case VertexBuffer.PositionKind:
  21094. stride = 3;
  21095. break;
  21096. case VertexBuffer.NormalKind:
  21097. stride = 3;
  21098. break;
  21099. case VertexBuffer.UVKind:
  21100. case VertexBuffer.UV2Kind:
  21101. case VertexBuffer.UV3Kind:
  21102. case VertexBuffer.UV4Kind:
  21103. case VertexBuffer.UV5Kind:
  21104. case VertexBuffer.UV6Kind:
  21105. stride = 2;
  21106. break;
  21107. case VertexBuffer.TangentKind:
  21108. case VertexBuffer.ColorKind:
  21109. stride = 4;
  21110. break;
  21111. case VertexBuffer.MatricesIndicesKind:
  21112. case VertexBuffer.MatricesIndicesExtraKind:
  21113. stride = 4;
  21114. break;
  21115. case VertexBuffer.MatricesWeightsKind:
  21116. case VertexBuffer.MatricesWeightsExtraKind:
  21117. default:
  21118. stride = 4;
  21119. break;
  21120. }
  21121. }
  21122. if (data instanceof BABYLON.Buffer) {
  21123. if (!stride) {
  21124. stride = data.getStrideSize();
  21125. }
  21126. this._buffer = data;
  21127. this._ownsBuffer = false;
  21128. }
  21129. else {
  21130. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21131. this._ownsBuffer = true;
  21132. }
  21133. this._stride = stride;
  21134. this._offset = offset ? offset : 0;
  21135. this._size = size ? size : stride;
  21136. this._kind = kind;
  21137. }
  21138. VertexBuffer.prototype._rebuild = function () {
  21139. if (!this._buffer) {
  21140. return;
  21141. }
  21142. this._buffer._rebuild();
  21143. };
  21144. /**
  21145. * Returns the kind of the VertexBuffer (string).
  21146. */
  21147. VertexBuffer.prototype.getKind = function () {
  21148. return this._kind;
  21149. };
  21150. // Properties
  21151. /**
  21152. * Boolean : is the VertexBuffer updatable ?
  21153. */
  21154. VertexBuffer.prototype.isUpdatable = function () {
  21155. return this._buffer.isUpdatable();
  21156. };
  21157. /**
  21158. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21159. */
  21160. VertexBuffer.prototype.getData = function () {
  21161. return this._buffer.getData();
  21162. };
  21163. /**
  21164. * Returns the WebGLBuffer associated to the VertexBuffer.
  21165. */
  21166. VertexBuffer.prototype.getBuffer = function () {
  21167. return this._buffer.getBuffer();
  21168. };
  21169. /**
  21170. * Returns the stride of the VertexBuffer (integer).
  21171. */
  21172. VertexBuffer.prototype.getStrideSize = function () {
  21173. return this._stride;
  21174. };
  21175. /**
  21176. * Returns the offset (integer).
  21177. */
  21178. VertexBuffer.prototype.getOffset = function () {
  21179. return this._offset;
  21180. };
  21181. /**
  21182. * Returns the VertexBuffer total size (integer).
  21183. */
  21184. VertexBuffer.prototype.getSize = function () {
  21185. return this._size;
  21186. };
  21187. /**
  21188. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21189. */
  21190. VertexBuffer.prototype.getIsInstanced = function () {
  21191. return this._buffer.getIsInstanced();
  21192. };
  21193. /**
  21194. * Returns the instancing divisor, zero for non-instanced (integer).
  21195. */
  21196. VertexBuffer.prototype.getInstanceDivisor = function () {
  21197. return this._buffer.instanceDivisor;
  21198. };
  21199. // Methods
  21200. /**
  21201. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21202. * Returns the created WebGLBuffer.
  21203. */
  21204. VertexBuffer.prototype.create = function (data) {
  21205. return this._buffer.create(data);
  21206. };
  21207. /**
  21208. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21209. * Returns the updated WebGLBuffer.
  21210. */
  21211. VertexBuffer.prototype.update = function (data) {
  21212. return this._buffer.update(data);
  21213. };
  21214. /**
  21215. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21216. * Returns the directly updated WebGLBuffer.
  21217. */
  21218. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21219. return this._buffer.updateDirectly(data, offset);
  21220. };
  21221. /**
  21222. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21223. */
  21224. VertexBuffer.prototype.dispose = function () {
  21225. if (this._ownsBuffer) {
  21226. this._buffer.dispose();
  21227. }
  21228. };
  21229. Object.defineProperty(VertexBuffer, "PositionKind", {
  21230. get: function () {
  21231. return VertexBuffer._PositionKind;
  21232. },
  21233. enumerable: true,
  21234. configurable: true
  21235. });
  21236. Object.defineProperty(VertexBuffer, "NormalKind", {
  21237. get: function () {
  21238. return VertexBuffer._NormalKind;
  21239. },
  21240. enumerable: true,
  21241. configurable: true
  21242. });
  21243. Object.defineProperty(VertexBuffer, "TangentKind", {
  21244. get: function () {
  21245. return VertexBuffer._TangentKind;
  21246. },
  21247. enumerable: true,
  21248. configurable: true
  21249. });
  21250. Object.defineProperty(VertexBuffer, "UVKind", {
  21251. get: function () {
  21252. return VertexBuffer._UVKind;
  21253. },
  21254. enumerable: true,
  21255. configurable: true
  21256. });
  21257. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21258. get: function () {
  21259. return VertexBuffer._UV2Kind;
  21260. },
  21261. enumerable: true,
  21262. configurable: true
  21263. });
  21264. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21265. get: function () {
  21266. return VertexBuffer._UV3Kind;
  21267. },
  21268. enumerable: true,
  21269. configurable: true
  21270. });
  21271. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21272. get: function () {
  21273. return VertexBuffer._UV4Kind;
  21274. },
  21275. enumerable: true,
  21276. configurable: true
  21277. });
  21278. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21279. get: function () {
  21280. return VertexBuffer._UV5Kind;
  21281. },
  21282. enumerable: true,
  21283. configurable: true
  21284. });
  21285. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21286. get: function () {
  21287. return VertexBuffer._UV6Kind;
  21288. },
  21289. enumerable: true,
  21290. configurable: true
  21291. });
  21292. Object.defineProperty(VertexBuffer, "ColorKind", {
  21293. get: function () {
  21294. return VertexBuffer._ColorKind;
  21295. },
  21296. enumerable: true,
  21297. configurable: true
  21298. });
  21299. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21300. get: function () {
  21301. return VertexBuffer._MatricesIndicesKind;
  21302. },
  21303. enumerable: true,
  21304. configurable: true
  21305. });
  21306. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21307. get: function () {
  21308. return VertexBuffer._MatricesWeightsKind;
  21309. },
  21310. enumerable: true,
  21311. configurable: true
  21312. });
  21313. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21314. get: function () {
  21315. return VertexBuffer._MatricesIndicesExtraKind;
  21316. },
  21317. enumerable: true,
  21318. configurable: true
  21319. });
  21320. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21321. get: function () {
  21322. return VertexBuffer._MatricesWeightsExtraKind;
  21323. },
  21324. enumerable: true,
  21325. configurable: true
  21326. });
  21327. // Enums
  21328. VertexBuffer._PositionKind = "position";
  21329. VertexBuffer._NormalKind = "normal";
  21330. VertexBuffer._TangentKind = "tangent";
  21331. VertexBuffer._UVKind = "uv";
  21332. VertexBuffer._UV2Kind = "uv2";
  21333. VertexBuffer._UV3Kind = "uv3";
  21334. VertexBuffer._UV4Kind = "uv4";
  21335. VertexBuffer._UV5Kind = "uv5";
  21336. VertexBuffer._UV6Kind = "uv6";
  21337. VertexBuffer._ColorKind = "color";
  21338. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21339. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21340. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21341. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21342. return VertexBuffer;
  21343. }());
  21344. BABYLON.VertexBuffer = VertexBuffer;
  21345. })(BABYLON || (BABYLON = {}));
  21346. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21347. var BABYLON;
  21348. (function (BABYLON) {
  21349. var InternalTexture = /** @class */ (function () {
  21350. function InternalTexture(engine, dataSource) {
  21351. this.onLoadedObservable = new BABYLON.Observable();
  21352. // Private
  21353. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21354. this._references = 1;
  21355. this._engine = engine;
  21356. this._dataSource = dataSource;
  21357. this._webGLTexture = engine._createTexture();
  21358. }
  21359. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21360. get: function () {
  21361. return this._dataSource;
  21362. },
  21363. enumerable: true,
  21364. configurable: true
  21365. });
  21366. InternalTexture.prototype.incrementReferences = function () {
  21367. this._references++;
  21368. };
  21369. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21370. if (depth === void 0) { depth = 1; }
  21371. this.width = width;
  21372. this.height = height;
  21373. this.depth = depth;
  21374. this.baseWidth = width;
  21375. this.baseHeight = height;
  21376. this.baseDepth = depth;
  21377. this._size = width * height * depth;
  21378. };
  21379. InternalTexture.prototype._rebuild = function () {
  21380. var _this = this;
  21381. var proxy;
  21382. this.isReady = false;
  21383. this._cachedCoordinatesMode = null;
  21384. this._cachedWrapU = null;
  21385. this._cachedWrapV = null;
  21386. this._cachedAnisotropicFilteringLevel = null;
  21387. switch (this._dataSource) {
  21388. case InternalTexture.DATASOURCE_TEMP:
  21389. return;
  21390. case InternalTexture.DATASOURCE_URL:
  21391. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21392. _this.isReady = true;
  21393. }, null, this._buffer, undefined, this.format);
  21394. proxy._swapAndDie(this);
  21395. return;
  21396. case InternalTexture.DATASOURCE_RAW:
  21397. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21398. proxy._swapAndDie(this);
  21399. this.isReady = true;
  21400. return;
  21401. case InternalTexture.DATASOURCE_RAW3D:
  21402. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21403. proxy._swapAndDie(this);
  21404. this.isReady = true;
  21405. return;
  21406. case InternalTexture.DATASOURCE_DYNAMIC:
  21407. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21408. proxy._swapAndDie(this);
  21409. // The engine will make sure to update content so no need to flag it as isReady = true
  21410. return;
  21411. case InternalTexture.DATASOURCE_RENDERTARGET:
  21412. var options = new BABYLON.RenderTargetCreationOptions();
  21413. options.generateDepthBuffer = this._generateDepthBuffer;
  21414. options.generateMipMaps = this.generateMipMaps;
  21415. options.generateStencilBuffer = this._generateStencilBuffer;
  21416. options.samplingMode = this.samplingMode;
  21417. options.type = this.type;
  21418. if (this.isCube) {
  21419. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21420. }
  21421. else {
  21422. var size = {
  21423. width: this.width,
  21424. height: this.height
  21425. };
  21426. proxy = this._engine.createRenderTargetTexture(size, options);
  21427. }
  21428. proxy._swapAndDie(this);
  21429. this.isReady = true;
  21430. return;
  21431. case InternalTexture.DATASOURCE_CUBE:
  21432. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21433. _this.isReady = true;
  21434. }, null, this.format, this._extension);
  21435. proxy._swapAndDie(this);
  21436. return;
  21437. case InternalTexture.DATASOURCE_CUBERAW:
  21438. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21439. proxy._swapAndDie(this);
  21440. this.isReady = true;
  21441. return;
  21442. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21443. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21444. if (proxy) {
  21445. proxy._swapAndDie(_this);
  21446. }
  21447. _this.isReady = true;
  21448. }, null, this.format, this._extension);
  21449. return;
  21450. }
  21451. };
  21452. InternalTexture.prototype._swapAndDie = function (target) {
  21453. target._webGLTexture = this._webGLTexture;
  21454. if (this._framebuffer) {
  21455. target._framebuffer = this._framebuffer;
  21456. }
  21457. if (this._depthStencilBuffer) {
  21458. target._depthStencilBuffer = this._depthStencilBuffer;
  21459. }
  21460. if (this._lodTextureHigh) {
  21461. if (target._lodTextureHigh) {
  21462. target._lodTextureHigh.dispose();
  21463. }
  21464. target._lodTextureHigh = this._lodTextureHigh;
  21465. }
  21466. if (this._lodTextureMid) {
  21467. if (target._lodTextureMid) {
  21468. target._lodTextureMid.dispose();
  21469. }
  21470. target._lodTextureMid = this._lodTextureMid;
  21471. }
  21472. if (this._lodTextureLow) {
  21473. if (target._lodTextureLow) {
  21474. target._lodTextureLow.dispose();
  21475. }
  21476. target._lodTextureLow = this._lodTextureLow;
  21477. }
  21478. var cache = this._engine.getLoadedTexturesCache();
  21479. var index = cache.indexOf(this);
  21480. if (index !== -1) {
  21481. cache.splice(index, 1);
  21482. }
  21483. };
  21484. InternalTexture.prototype.dispose = function () {
  21485. if (!this._webGLTexture) {
  21486. return;
  21487. }
  21488. this._references--;
  21489. if (this._references === 0) {
  21490. this._engine._releaseTexture(this);
  21491. this._webGLTexture = null;
  21492. }
  21493. };
  21494. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21495. InternalTexture.DATASOURCE_URL = 1;
  21496. InternalTexture.DATASOURCE_TEMP = 2;
  21497. InternalTexture.DATASOURCE_RAW = 3;
  21498. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21499. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21500. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21501. InternalTexture.DATASOURCE_CUBE = 7;
  21502. InternalTexture.DATASOURCE_CUBERAW = 8;
  21503. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21504. InternalTexture.DATASOURCE_RAW3D = 10;
  21505. return InternalTexture;
  21506. }());
  21507. BABYLON.InternalTexture = InternalTexture;
  21508. })(BABYLON || (BABYLON = {}));
  21509. //# sourceMappingURL=babylon.internalTexture.js.map
  21510. var BABYLON;
  21511. (function (BABYLON) {
  21512. var BaseTexture = /** @class */ (function () {
  21513. function BaseTexture(scene) {
  21514. this._hasAlpha = false;
  21515. this.getAlphaFromRGB = false;
  21516. this.level = 1;
  21517. this.coordinatesIndex = 0;
  21518. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21519. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21520. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21521. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  21522. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21523. this.isCube = false;
  21524. this.is3D = false;
  21525. this.gammaSpace = true;
  21526. this.invertZ = false;
  21527. this.lodLevelInAlpha = false;
  21528. this.lodGenerationOffset = 0.0;
  21529. this.lodGenerationScale = 0.8;
  21530. this.isRenderTarget = false;
  21531. this.animations = new Array();
  21532. /**
  21533. * An event triggered when the texture is disposed.
  21534. * @type {BABYLON.Observable}
  21535. */
  21536. this.onDisposeObservable = new BABYLON.Observable();
  21537. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21538. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21539. if (this._scene) {
  21540. this._scene.textures.push(this);
  21541. }
  21542. this._uid = null;
  21543. }
  21544. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21545. get: function () {
  21546. return this._hasAlpha;
  21547. },
  21548. set: function (value) {
  21549. if (this._hasAlpha === value) {
  21550. return;
  21551. }
  21552. this._hasAlpha = value;
  21553. if (this._scene) {
  21554. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21555. }
  21556. },
  21557. enumerable: true,
  21558. configurable: true
  21559. });
  21560. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  21561. get: function () {
  21562. return this._coordinatesMode;
  21563. },
  21564. set: function (value) {
  21565. if (this._coordinatesMode === value) {
  21566. return;
  21567. }
  21568. this._coordinatesMode = value;
  21569. if (this._scene) {
  21570. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21571. }
  21572. },
  21573. enumerable: true,
  21574. configurable: true
  21575. });
  21576. Object.defineProperty(BaseTexture.prototype, "uid", {
  21577. get: function () {
  21578. if (!this._uid) {
  21579. this._uid = BABYLON.Tools.RandomId();
  21580. }
  21581. return this._uid;
  21582. },
  21583. enumerable: true,
  21584. configurable: true
  21585. });
  21586. BaseTexture.prototype.toString = function () {
  21587. return this.name;
  21588. };
  21589. BaseTexture.prototype.getClassName = function () {
  21590. return "BaseTexture";
  21591. };
  21592. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21593. set: function (callback) {
  21594. if (this._onDisposeObserver) {
  21595. this.onDisposeObservable.remove(this._onDisposeObserver);
  21596. }
  21597. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21598. },
  21599. enumerable: true,
  21600. configurable: true
  21601. });
  21602. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21603. get: function () {
  21604. return true;
  21605. },
  21606. enumerable: true,
  21607. configurable: true
  21608. });
  21609. BaseTexture.prototype.getScene = function () {
  21610. return this._scene;
  21611. };
  21612. BaseTexture.prototype.getTextureMatrix = function () {
  21613. return BABYLON.Matrix.IdentityReadOnly;
  21614. };
  21615. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21616. return BABYLON.Matrix.IdentityReadOnly;
  21617. };
  21618. BaseTexture.prototype.getInternalTexture = function () {
  21619. return this._texture;
  21620. };
  21621. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21622. return !this.isBlocking || this.isReady();
  21623. };
  21624. BaseTexture.prototype.isReady = function () {
  21625. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21626. this.delayLoad();
  21627. return false;
  21628. }
  21629. if (this._texture) {
  21630. return this._texture.isReady;
  21631. }
  21632. return false;
  21633. };
  21634. BaseTexture.prototype.getSize = function () {
  21635. if (this._texture && this._texture.width) {
  21636. return new BABYLON.Size(this._texture.width, this._texture.height);
  21637. }
  21638. if (this._texture && this._texture._size) {
  21639. return new BABYLON.Size(this._texture._size, this._texture._size);
  21640. }
  21641. return BABYLON.Size.Zero();
  21642. };
  21643. BaseTexture.prototype.getBaseSize = function () {
  21644. if (!this.isReady() || !this._texture)
  21645. return BABYLON.Size.Zero();
  21646. if (this._texture._size) {
  21647. return new BABYLON.Size(this._texture._size, this._texture._size);
  21648. }
  21649. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21650. };
  21651. BaseTexture.prototype.scale = function (ratio) {
  21652. };
  21653. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21654. get: function () {
  21655. return false;
  21656. },
  21657. enumerable: true,
  21658. configurable: true
  21659. });
  21660. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21661. if (!this._scene) {
  21662. return null;
  21663. }
  21664. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21665. for (var index = 0; index < texturesCache.length; index++) {
  21666. var texturesCacheEntry = texturesCache[index];
  21667. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21668. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21669. texturesCacheEntry.incrementReferences();
  21670. return texturesCacheEntry;
  21671. }
  21672. }
  21673. }
  21674. return null;
  21675. };
  21676. BaseTexture.prototype._rebuild = function () {
  21677. };
  21678. BaseTexture.prototype.delayLoad = function () {
  21679. };
  21680. BaseTexture.prototype.clone = function () {
  21681. return null;
  21682. };
  21683. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21684. get: function () {
  21685. if (!this._texture) {
  21686. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21687. }
  21688. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21694. get: function () {
  21695. if (!this._texture) {
  21696. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21697. }
  21698. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21699. },
  21700. enumerable: true,
  21701. configurable: true
  21702. });
  21703. BaseTexture.prototype.readPixels = function (faceIndex) {
  21704. if (faceIndex === void 0) { faceIndex = 0; }
  21705. if (!this._texture) {
  21706. return null;
  21707. }
  21708. var size = this.getSize();
  21709. var scene = this.getScene();
  21710. if (!scene) {
  21711. return null;
  21712. }
  21713. var engine = scene.getEngine();
  21714. if (this._texture.isCube) {
  21715. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21716. }
  21717. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21718. };
  21719. BaseTexture.prototype.releaseInternalTexture = function () {
  21720. if (this._texture) {
  21721. this._texture.dispose();
  21722. this._texture = null;
  21723. }
  21724. };
  21725. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21726. get: function () {
  21727. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21728. return null;
  21729. }
  21730. if (!this._texture._sphericalPolynomial) {
  21731. this._texture._sphericalPolynomial =
  21732. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21733. }
  21734. return this._texture._sphericalPolynomial;
  21735. },
  21736. set: function (value) {
  21737. if (this._texture) {
  21738. this._texture._sphericalPolynomial = value;
  21739. }
  21740. },
  21741. enumerable: true,
  21742. configurable: true
  21743. });
  21744. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21745. get: function () {
  21746. if (this._texture) {
  21747. return this._texture._lodTextureHigh;
  21748. }
  21749. return null;
  21750. },
  21751. enumerable: true,
  21752. configurable: true
  21753. });
  21754. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21755. get: function () {
  21756. if (this._texture) {
  21757. return this._texture._lodTextureMid;
  21758. }
  21759. return null;
  21760. },
  21761. enumerable: true,
  21762. configurable: true
  21763. });
  21764. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21765. get: function () {
  21766. if (this._texture) {
  21767. return this._texture._lodTextureLow;
  21768. }
  21769. return null;
  21770. },
  21771. enumerable: true,
  21772. configurable: true
  21773. });
  21774. BaseTexture.prototype.dispose = function () {
  21775. if (!this._scene) {
  21776. return;
  21777. }
  21778. // Animations
  21779. this._scene.stopAnimation(this);
  21780. // Remove from scene
  21781. this._scene._removePendingData(this);
  21782. var index = this._scene.textures.indexOf(this);
  21783. if (index >= 0) {
  21784. this._scene.textures.splice(index, 1);
  21785. }
  21786. if (this._texture === undefined) {
  21787. return;
  21788. }
  21789. // Release
  21790. this.releaseInternalTexture();
  21791. // Callback
  21792. this.onDisposeObservable.notifyObservers(this);
  21793. this.onDisposeObservable.clear();
  21794. };
  21795. BaseTexture.prototype.serialize = function () {
  21796. if (!this.name) {
  21797. return null;
  21798. }
  21799. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21800. // Animations
  21801. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21802. return serializationObject;
  21803. };
  21804. BaseTexture.WhenAllReady = function (textures, callback) {
  21805. var numRemaining = textures.length;
  21806. if (numRemaining === 0) {
  21807. callback();
  21808. return;
  21809. }
  21810. var _loop_1 = function () {
  21811. texture = textures[i];
  21812. if (texture.isReady()) {
  21813. if (--numRemaining === 0) {
  21814. callback();
  21815. }
  21816. }
  21817. else {
  21818. onLoadObservable = texture.onLoadObservable;
  21819. var onLoadCallback_1 = function () {
  21820. onLoadObservable.removeCallback(onLoadCallback_1);
  21821. if (--numRemaining === 0) {
  21822. callback();
  21823. }
  21824. };
  21825. onLoadObservable.add(onLoadCallback_1);
  21826. }
  21827. };
  21828. var texture, onLoadObservable;
  21829. for (var i = 0; i < textures.length; i++) {
  21830. _loop_1();
  21831. }
  21832. };
  21833. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21834. __decorate([
  21835. BABYLON.serialize()
  21836. ], BaseTexture.prototype, "name", void 0);
  21837. __decorate([
  21838. BABYLON.serialize("hasAlpha")
  21839. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21840. __decorate([
  21841. BABYLON.serialize()
  21842. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21843. __decorate([
  21844. BABYLON.serialize()
  21845. ], BaseTexture.prototype, "level", void 0);
  21846. __decorate([
  21847. BABYLON.serialize()
  21848. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21849. __decorate([
  21850. BABYLON.serialize("coordinatesMode")
  21851. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21852. __decorate([
  21853. BABYLON.serialize()
  21854. ], BaseTexture.prototype, "wrapU", void 0);
  21855. __decorate([
  21856. BABYLON.serialize()
  21857. ], BaseTexture.prototype, "wrapV", void 0);
  21858. __decorate([
  21859. BABYLON.serialize()
  21860. ], BaseTexture.prototype, "wrapR", void 0);
  21861. __decorate([
  21862. BABYLON.serialize()
  21863. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21864. __decorate([
  21865. BABYLON.serialize()
  21866. ], BaseTexture.prototype, "isCube", void 0);
  21867. __decorate([
  21868. BABYLON.serialize()
  21869. ], BaseTexture.prototype, "is3D", void 0);
  21870. __decorate([
  21871. BABYLON.serialize()
  21872. ], BaseTexture.prototype, "gammaSpace", void 0);
  21873. __decorate([
  21874. BABYLON.serialize()
  21875. ], BaseTexture.prototype, "invertZ", void 0);
  21876. __decorate([
  21877. BABYLON.serialize()
  21878. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21879. __decorate([
  21880. BABYLON.serialize()
  21881. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21882. __decorate([
  21883. BABYLON.serialize()
  21884. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21885. __decorate([
  21886. BABYLON.serialize()
  21887. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21888. return BaseTexture;
  21889. }());
  21890. BABYLON.BaseTexture = BaseTexture;
  21891. })(BABYLON || (BABYLON = {}));
  21892. //# sourceMappingURL=babylon.baseTexture.js.map
  21893. var BABYLON;
  21894. (function (BABYLON) {
  21895. var Texture = /** @class */ (function (_super) {
  21896. __extends(Texture, _super);
  21897. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21898. if (noMipmap === void 0) { noMipmap = false; }
  21899. if (invertY === void 0) { invertY = true; }
  21900. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21901. if (onLoad === void 0) { onLoad = null; }
  21902. if (onError === void 0) { onError = null; }
  21903. if (buffer === void 0) { buffer = null; }
  21904. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21905. var _this = _super.call(this, scene) || this;
  21906. _this.uOffset = 0;
  21907. _this.vOffset = 0;
  21908. _this.uScale = 1.0;
  21909. _this.vScale = 1.0;
  21910. _this.uAng = 0;
  21911. _this.vAng = 0;
  21912. _this.wAng = 0;
  21913. _this._isBlocking = true;
  21914. _this.name = url || "";
  21915. _this.url = url;
  21916. _this._noMipmap = noMipmap;
  21917. _this._invertY = invertY;
  21918. _this._samplingMode = samplingMode;
  21919. _this._buffer = buffer;
  21920. _this._deleteBuffer = deleteBuffer;
  21921. if (format) {
  21922. _this._format = format;
  21923. }
  21924. scene = _this.getScene();
  21925. if (!scene) {
  21926. return _this;
  21927. }
  21928. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21929. var load = function () {
  21930. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21931. _this.onLoadObservable.notifyObservers(_this);
  21932. }
  21933. if (onLoad) {
  21934. onLoad();
  21935. }
  21936. if (!_this.isBlocking && scene) {
  21937. scene.resetCachedMaterial();
  21938. }
  21939. };
  21940. if (!_this.url) {
  21941. _this._delayedOnLoad = load;
  21942. _this._delayedOnError = onError;
  21943. return _this;
  21944. }
  21945. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21946. if (!_this._texture) {
  21947. if (!scene.useDelayedTextureLoading) {
  21948. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  21949. if (deleteBuffer) {
  21950. delete _this._buffer;
  21951. }
  21952. }
  21953. else {
  21954. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21955. _this._delayedOnLoad = load;
  21956. _this._delayedOnError = onError;
  21957. }
  21958. }
  21959. else {
  21960. if (_this._texture.isReady) {
  21961. BABYLON.Tools.SetImmediate(function () { return load(); });
  21962. }
  21963. else {
  21964. _this._texture.onLoadedObservable.add(load);
  21965. }
  21966. }
  21967. return _this;
  21968. }
  21969. Object.defineProperty(Texture.prototype, "noMipmap", {
  21970. get: function () {
  21971. return this._noMipmap;
  21972. },
  21973. enumerable: true,
  21974. configurable: true
  21975. });
  21976. Object.defineProperty(Texture.prototype, "isBlocking", {
  21977. get: function () {
  21978. return this._isBlocking;
  21979. },
  21980. set: function (value) {
  21981. this._isBlocking = value;
  21982. },
  21983. enumerable: true,
  21984. configurable: true
  21985. });
  21986. Object.defineProperty(Texture.prototype, "samplingMode", {
  21987. get: function () {
  21988. return this._samplingMode;
  21989. },
  21990. enumerable: true,
  21991. configurable: true
  21992. });
  21993. Texture.prototype.updateURL = function (url) {
  21994. this.url = url;
  21995. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21996. this.delayLoad();
  21997. };
  21998. Texture.prototype.delayLoad = function () {
  21999. var _this = this;
  22000. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22001. return;
  22002. }
  22003. var scene = this.getScene();
  22004. if (!scene) {
  22005. return;
  22006. }
  22007. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22008. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22009. if (!this._texture) {
  22010. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22011. if (this._deleteBuffer) {
  22012. delete this._buffer;
  22013. }
  22014. }
  22015. else {
  22016. if (this._texture.isReady) {
  22017. BABYLON.Tools.SetImmediate(function () {
  22018. if (!_this._delayedOnLoad) {
  22019. return;
  22020. }
  22021. _this._delayedOnLoad();
  22022. });
  22023. }
  22024. else {
  22025. if (this._delayedOnLoad) {
  22026. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22027. }
  22028. }
  22029. }
  22030. };
  22031. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22032. if (!this._texture) {
  22033. return;
  22034. }
  22035. var scene = this.getScene();
  22036. if (!scene) {
  22037. return;
  22038. }
  22039. this._samplingMode = samplingMode;
  22040. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22041. };
  22042. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22043. x *= this.uScale;
  22044. y *= this.vScale;
  22045. x -= 0.5 * this.uScale;
  22046. y -= 0.5 * this.vScale;
  22047. z -= 0.5;
  22048. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22049. t.x += 0.5 * this.uScale + this.uOffset;
  22050. t.y += 0.5 * this.vScale + this.vOffset;
  22051. t.z += 0.5;
  22052. };
  22053. Texture.prototype.getTextureMatrix = function () {
  22054. var _this = this;
  22055. if (this.uOffset === this._cachedUOffset &&
  22056. this.vOffset === this._cachedVOffset &&
  22057. this.uScale === this._cachedUScale &&
  22058. this.vScale === this._cachedVScale &&
  22059. this.uAng === this._cachedUAng &&
  22060. this.vAng === this._cachedVAng &&
  22061. this.wAng === this._cachedWAng) {
  22062. return this._cachedTextureMatrix;
  22063. }
  22064. this._cachedUOffset = this.uOffset;
  22065. this._cachedVOffset = this.vOffset;
  22066. this._cachedUScale = this.uScale;
  22067. this._cachedVScale = this.vScale;
  22068. this._cachedUAng = this.uAng;
  22069. this._cachedVAng = this.vAng;
  22070. this._cachedWAng = this.wAng;
  22071. if (!this._cachedTextureMatrix) {
  22072. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22073. this._rowGenerationMatrix = new BABYLON.Matrix();
  22074. this._t0 = BABYLON.Vector3.Zero();
  22075. this._t1 = BABYLON.Vector3.Zero();
  22076. this._t2 = BABYLON.Vector3.Zero();
  22077. }
  22078. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22079. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22080. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22081. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22082. this._t1.subtractInPlace(this._t0);
  22083. this._t2.subtractInPlace(this._t0);
  22084. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22085. this._cachedTextureMatrix.m[0] = this._t1.x;
  22086. this._cachedTextureMatrix.m[1] = this._t1.y;
  22087. this._cachedTextureMatrix.m[2] = this._t1.z;
  22088. this._cachedTextureMatrix.m[4] = this._t2.x;
  22089. this._cachedTextureMatrix.m[5] = this._t2.y;
  22090. this._cachedTextureMatrix.m[6] = this._t2.z;
  22091. this._cachedTextureMatrix.m[8] = this._t0.x;
  22092. this._cachedTextureMatrix.m[9] = this._t0.y;
  22093. this._cachedTextureMatrix.m[10] = this._t0.z;
  22094. var scene = this.getScene();
  22095. if (!scene) {
  22096. return this._cachedTextureMatrix;
  22097. }
  22098. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22099. return mat.hasTexture(_this);
  22100. });
  22101. return this._cachedTextureMatrix;
  22102. };
  22103. Texture.prototype.getReflectionTextureMatrix = function () {
  22104. var _this = this;
  22105. var scene = this.getScene();
  22106. if (!scene) {
  22107. return this._cachedTextureMatrix;
  22108. }
  22109. if (this.uOffset === this._cachedUOffset &&
  22110. this.vOffset === this._cachedVOffset &&
  22111. this.uScale === this._cachedUScale &&
  22112. this.vScale === this._cachedVScale &&
  22113. this.coordinatesMode === this._cachedCoordinatesMode) {
  22114. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22115. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22116. return this._cachedTextureMatrix;
  22117. }
  22118. }
  22119. else {
  22120. return this._cachedTextureMatrix;
  22121. }
  22122. }
  22123. if (!this._cachedTextureMatrix) {
  22124. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22125. }
  22126. if (!this._projectionModeMatrix) {
  22127. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22128. }
  22129. this._cachedUOffset = this.uOffset;
  22130. this._cachedVOffset = this.vOffset;
  22131. this._cachedUScale = this.uScale;
  22132. this._cachedVScale = this.vScale;
  22133. this._cachedCoordinatesMode = this.coordinatesMode;
  22134. switch (this.coordinatesMode) {
  22135. case Texture.PLANAR_MODE:
  22136. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22137. this._cachedTextureMatrix[0] = this.uScale;
  22138. this._cachedTextureMatrix[5] = this.vScale;
  22139. this._cachedTextureMatrix[12] = this.uOffset;
  22140. this._cachedTextureMatrix[13] = this.vOffset;
  22141. break;
  22142. case Texture.PROJECTION_MODE:
  22143. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22144. this._projectionModeMatrix.m[0] = 0.5;
  22145. this._projectionModeMatrix.m[5] = -0.5;
  22146. this._projectionModeMatrix.m[10] = 0.0;
  22147. this._projectionModeMatrix.m[12] = 0.5;
  22148. this._projectionModeMatrix.m[13] = 0.5;
  22149. this._projectionModeMatrix.m[14] = 1.0;
  22150. this._projectionModeMatrix.m[15] = 1.0;
  22151. var projectionMatrix = scene.getProjectionMatrix();
  22152. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22153. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22154. break;
  22155. default:
  22156. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22157. break;
  22158. }
  22159. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22160. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22161. });
  22162. return this._cachedTextureMatrix;
  22163. };
  22164. Texture.prototype.clone = function () {
  22165. var _this = this;
  22166. return BABYLON.SerializationHelper.Clone(function () {
  22167. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22168. }, this);
  22169. };
  22170. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22171. get: function () {
  22172. if (!this._onLoadObservable) {
  22173. this._onLoadObservable = new BABYLON.Observable();
  22174. }
  22175. return this._onLoadObservable;
  22176. },
  22177. enumerable: true,
  22178. configurable: true
  22179. });
  22180. Texture.prototype.serialize = function () {
  22181. var serializationObject = _super.prototype.serialize.call(this);
  22182. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22183. serializationObject.base64String = this._buffer;
  22184. serializationObject.name = serializationObject.name.replace("data:", "");
  22185. }
  22186. return serializationObject;
  22187. };
  22188. Texture.prototype.getClassName = function () {
  22189. return "Texture";
  22190. };
  22191. Texture.prototype.dispose = function () {
  22192. _super.prototype.dispose.call(this);
  22193. if (this.onLoadObservable) {
  22194. this.onLoadObservable.clear();
  22195. this._onLoadObservable = null;
  22196. }
  22197. this._delayedOnLoad = null;
  22198. this._delayedOnError = null;
  22199. };
  22200. // Statics
  22201. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22202. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22203. if (onLoad === void 0) { onLoad = null; }
  22204. if (onError === void 0) { onError = null; }
  22205. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22206. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22207. };
  22208. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22209. if (parsedTexture.customType) {
  22210. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22211. // Update Sampling Mode
  22212. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22213. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22214. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22215. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22216. }
  22217. }
  22218. return parsedCustomTexture;
  22219. }
  22220. if (parsedTexture.isCube) {
  22221. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22222. }
  22223. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22224. return null;
  22225. }
  22226. var texture = BABYLON.SerializationHelper.Parse(function () {
  22227. if (parsedTexture.mirrorPlane) {
  22228. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22229. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22230. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22231. return mirrorTexture;
  22232. }
  22233. else if (parsedTexture.isRenderTarget) {
  22234. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22235. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22236. return renderTargetTexture;
  22237. }
  22238. else {
  22239. var texture;
  22240. if (parsedTexture.base64String) {
  22241. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22242. }
  22243. else {
  22244. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22245. }
  22246. return texture;
  22247. }
  22248. }, parsedTexture, scene);
  22249. // Update Sampling Mode
  22250. if (parsedTexture.samplingMode) {
  22251. var sampling = parsedTexture.samplingMode;
  22252. if (texture._samplingMode !== sampling) {
  22253. texture.updateSamplingMode(sampling);
  22254. }
  22255. }
  22256. // Animations
  22257. if (parsedTexture.animations) {
  22258. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22259. var parsedAnimation = parsedTexture.animations[animationIndex];
  22260. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22261. }
  22262. }
  22263. return texture;
  22264. };
  22265. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22266. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22267. if (noMipmap === void 0) { noMipmap = false; }
  22268. if (invertY === void 0) { invertY = true; }
  22269. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22270. if (onLoad === void 0) { onLoad = null; }
  22271. if (onError === void 0) { onError = null; }
  22272. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22273. if (name.substr(0, 5) !== "data:") {
  22274. name = "data:" + name;
  22275. }
  22276. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22277. };
  22278. // Constants
  22279. Texture.NEAREST_SAMPLINGMODE = 1;
  22280. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22281. Texture.BILINEAR_SAMPLINGMODE = 2;
  22282. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22283. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22284. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22285. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22286. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22287. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22288. Texture.NEAREST_LINEAR = 7;
  22289. Texture.NEAREST_NEAREST = 8;
  22290. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22291. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22292. Texture.LINEAR_LINEAR = 11;
  22293. Texture.LINEAR_NEAREST = 12;
  22294. Texture.EXPLICIT_MODE = 0;
  22295. Texture.SPHERICAL_MODE = 1;
  22296. Texture.PLANAR_MODE = 2;
  22297. Texture.CUBIC_MODE = 3;
  22298. Texture.PROJECTION_MODE = 4;
  22299. Texture.SKYBOX_MODE = 5;
  22300. Texture.INVCUBIC_MODE = 6;
  22301. Texture.EQUIRECTANGULAR_MODE = 7;
  22302. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22303. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22304. Texture.CLAMP_ADDRESSMODE = 0;
  22305. Texture.WRAP_ADDRESSMODE = 1;
  22306. Texture.MIRROR_ADDRESSMODE = 2;
  22307. __decorate([
  22308. BABYLON.serialize()
  22309. ], Texture.prototype, "url", void 0);
  22310. __decorate([
  22311. BABYLON.serialize()
  22312. ], Texture.prototype, "uOffset", void 0);
  22313. __decorate([
  22314. BABYLON.serialize()
  22315. ], Texture.prototype, "vOffset", void 0);
  22316. __decorate([
  22317. BABYLON.serialize()
  22318. ], Texture.prototype, "uScale", void 0);
  22319. __decorate([
  22320. BABYLON.serialize()
  22321. ], Texture.prototype, "vScale", void 0);
  22322. __decorate([
  22323. BABYLON.serialize()
  22324. ], Texture.prototype, "uAng", void 0);
  22325. __decorate([
  22326. BABYLON.serialize()
  22327. ], Texture.prototype, "vAng", void 0);
  22328. __decorate([
  22329. BABYLON.serialize()
  22330. ], Texture.prototype, "wAng", void 0);
  22331. __decorate([
  22332. BABYLON.serialize()
  22333. ], Texture.prototype, "isBlocking", null);
  22334. return Texture;
  22335. }(BABYLON.BaseTexture));
  22336. BABYLON.Texture = Texture;
  22337. })(BABYLON || (BABYLON = {}));
  22338. //# sourceMappingURL=babylon.texture.js.map
  22339. var BABYLON;
  22340. (function (BABYLON) {
  22341. var _InstancesBatch = /** @class */ (function () {
  22342. function _InstancesBatch() {
  22343. this.mustReturn = false;
  22344. this.visibleInstances = new Array();
  22345. this.renderSelf = new Array();
  22346. }
  22347. return _InstancesBatch;
  22348. }());
  22349. BABYLON._InstancesBatch = _InstancesBatch;
  22350. var Mesh = /** @class */ (function (_super) {
  22351. __extends(Mesh, _super);
  22352. /**
  22353. * @constructor
  22354. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22355. * @param {Scene} scene The scene to add this mesh to.
  22356. * @param {Node} parent The parent of this mesh, if it has one
  22357. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22358. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22359. * When false, achieved by calling a clone(), also passing False.
  22360. * This will make creation of children, recursive.
  22361. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22362. */
  22363. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22364. if (scene === void 0) { scene = null; }
  22365. if (parent === void 0) { parent = null; }
  22366. if (source === void 0) { source = null; }
  22367. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22368. var _this = _super.call(this, name, scene) || this;
  22369. // Events
  22370. /**
  22371. * An event triggered before rendering the mesh
  22372. * @type {BABYLON.Observable}
  22373. */
  22374. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22375. /**
  22376. * An event triggered after rendering the mesh
  22377. * @type {BABYLON.Observable}
  22378. */
  22379. _this.onAfterRenderObservable = new BABYLON.Observable();
  22380. /**
  22381. * An event triggered before drawing the mesh
  22382. * @type {BABYLON.Observable}
  22383. */
  22384. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22385. // Members
  22386. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22387. _this.instances = new Array();
  22388. _this._LODLevels = new Array();
  22389. _this._visibleInstances = {};
  22390. _this._renderIdForInstances = new Array();
  22391. _this._batchCache = new _InstancesBatch();
  22392. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22393. // Use by builder only to know what orientation were the mesh build in.
  22394. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22395. _this.overrideMaterialSideOrientation = null;
  22396. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22397. // Will be used to save a source mesh reference, If any
  22398. _this._source = null;
  22399. scene = _this.getScene();
  22400. if (source) {
  22401. // Source mesh
  22402. _this._source = source;
  22403. // Geometry
  22404. if (source._geometry) {
  22405. source._geometry.applyToMesh(_this);
  22406. }
  22407. // Deep copy
  22408. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  22409. // Tags
  22410. if (BABYLON.Tags.HasTags(source)) {
  22411. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22412. }
  22413. _this.metadata = source.metadata;
  22414. // Parent
  22415. _this.parent = source.parent;
  22416. // Pivot
  22417. _this.setPivotMatrix(source.getPivotMatrix());
  22418. _this.id = name + "." + source.id;
  22419. // Material
  22420. _this.material = source.material;
  22421. var index;
  22422. if (!doNotCloneChildren) {
  22423. // Children
  22424. for (index = 0; index < scene.meshes.length; index++) {
  22425. var mesh = scene.meshes[index];
  22426. if (mesh.parent === source) {
  22427. // doNotCloneChildren is always going to be False
  22428. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22429. }
  22430. }
  22431. }
  22432. // Physics clone
  22433. var physicsEngine = _this.getScene().getPhysicsEngine();
  22434. if (clonePhysicsImpostor && physicsEngine) {
  22435. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22436. if (impostor) {
  22437. _this.physicsImpostor = impostor.clone(_this);
  22438. }
  22439. }
  22440. // Particles
  22441. for (index = 0; index < scene.particleSystems.length; index++) {
  22442. var system = scene.particleSystems[index];
  22443. if (system.emitter === source) {
  22444. system.clone(system.name, _this);
  22445. }
  22446. }
  22447. _this.computeWorldMatrix(true);
  22448. }
  22449. // Parent
  22450. if (parent !== null) {
  22451. _this.parent = parent;
  22452. }
  22453. return _this;
  22454. }
  22455. Object.defineProperty(Mesh, "FRONTSIDE", {
  22456. /**
  22457. * Mesh side orientation : usually the external or front surface
  22458. */
  22459. get: function () {
  22460. return Mesh._FRONTSIDE;
  22461. },
  22462. enumerable: true,
  22463. configurable: true
  22464. });
  22465. Object.defineProperty(Mesh, "BACKSIDE", {
  22466. /**
  22467. * Mesh side orientation : usually the internal or back surface
  22468. */
  22469. get: function () {
  22470. return Mesh._BACKSIDE;
  22471. },
  22472. enumerable: true,
  22473. configurable: true
  22474. });
  22475. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22476. /**
  22477. * Mesh side orientation : both internal and external or front and back surfaces
  22478. */
  22479. get: function () {
  22480. return Mesh._DOUBLESIDE;
  22481. },
  22482. enumerable: true,
  22483. configurable: true
  22484. });
  22485. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22486. /**
  22487. * Mesh side orientation : by default, `FRONTSIDE`
  22488. */
  22489. get: function () {
  22490. return Mesh._DEFAULTSIDE;
  22491. },
  22492. enumerable: true,
  22493. configurable: true
  22494. });
  22495. Object.defineProperty(Mesh, "NO_CAP", {
  22496. /**
  22497. * Mesh cap setting : no cap
  22498. */
  22499. get: function () {
  22500. return Mesh._NO_CAP;
  22501. },
  22502. enumerable: true,
  22503. configurable: true
  22504. });
  22505. Object.defineProperty(Mesh, "CAP_START", {
  22506. /**
  22507. * Mesh cap setting : one cap at the beginning of the mesh
  22508. */
  22509. get: function () {
  22510. return Mesh._CAP_START;
  22511. },
  22512. enumerable: true,
  22513. configurable: true
  22514. });
  22515. Object.defineProperty(Mesh, "CAP_END", {
  22516. /**
  22517. * Mesh cap setting : one cap at the end of the mesh
  22518. */
  22519. get: function () {
  22520. return Mesh._CAP_END;
  22521. },
  22522. enumerable: true,
  22523. configurable: true
  22524. });
  22525. Object.defineProperty(Mesh, "CAP_ALL", {
  22526. /**
  22527. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22528. */
  22529. get: function () {
  22530. return Mesh._CAP_ALL;
  22531. },
  22532. enumerable: true,
  22533. configurable: true
  22534. });
  22535. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22536. set: function (callback) {
  22537. if (this._onBeforeDrawObserver) {
  22538. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22539. }
  22540. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22541. },
  22542. enumerable: true,
  22543. configurable: true
  22544. });
  22545. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22546. get: function () {
  22547. return this._morphTargetManager;
  22548. },
  22549. set: function (value) {
  22550. if (this._morphTargetManager === value) {
  22551. return;
  22552. }
  22553. this._morphTargetManager = value;
  22554. this._syncGeometryWithMorphTargetManager();
  22555. },
  22556. enumerable: true,
  22557. configurable: true
  22558. });
  22559. Object.defineProperty(Mesh.prototype, "source", {
  22560. get: function () {
  22561. return this._source;
  22562. },
  22563. enumerable: true,
  22564. configurable: true
  22565. });
  22566. // Methods
  22567. /**
  22568. * Returns the string "Mesh".
  22569. */
  22570. Mesh.prototype.getClassName = function () {
  22571. return "Mesh";
  22572. };
  22573. /**
  22574. * Returns a string.
  22575. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22576. */
  22577. Mesh.prototype.toString = function (fullDetails) {
  22578. var ret = _super.prototype.toString.call(this, fullDetails);
  22579. ret += ", n vertices: " + this.getTotalVertices();
  22580. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22581. if (this.animations) {
  22582. for (var i = 0; i < this.animations.length; i++) {
  22583. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22584. }
  22585. }
  22586. if (fullDetails) {
  22587. if (this._geometry) {
  22588. var ib = this.getIndices();
  22589. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22590. if (vb && ib) {
  22591. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  22592. }
  22593. }
  22594. else {
  22595. ret += ", flat shading: UNKNOWN";
  22596. }
  22597. }
  22598. return ret;
  22599. };
  22600. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22601. /**
  22602. * True if the mesh has some Levels Of Details (LOD).
  22603. * Returns a boolean.
  22604. */
  22605. get: function () {
  22606. return this._LODLevels.length > 0;
  22607. },
  22608. enumerable: true,
  22609. configurable: true
  22610. });
  22611. Mesh.prototype._sortLODLevels = function () {
  22612. this._LODLevels.sort(function (a, b) {
  22613. if (a.distance < b.distance) {
  22614. return 1;
  22615. }
  22616. if (a.distance > b.distance) {
  22617. return -1;
  22618. }
  22619. return 0;
  22620. });
  22621. };
  22622. /**
  22623. * Add a mesh as LOD level triggered at the given distance.
  22624. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22625. * @param {number} distance The distance from the center of the object to show this level
  22626. * @param {Mesh} mesh The mesh to be added as LOD level
  22627. * @return {Mesh} This mesh (for chaining)
  22628. */
  22629. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22630. if (mesh && mesh._masterMesh) {
  22631. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22632. return this;
  22633. }
  22634. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22635. this._LODLevels.push(level);
  22636. if (mesh) {
  22637. mesh._masterMesh = this;
  22638. }
  22639. this._sortLODLevels();
  22640. return this;
  22641. };
  22642. /**
  22643. * Returns the LOD level mesh at the passed distance or null if not found.
  22644. * It is related to the method `addLODLevel(distance, mesh)`.
  22645. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22646. * Returns an object Mesh or `null`.
  22647. */
  22648. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22649. for (var index = 0; index < this._LODLevels.length; index++) {
  22650. var level = this._LODLevels[index];
  22651. if (level.distance === distance) {
  22652. return level.mesh;
  22653. }
  22654. }
  22655. return null;
  22656. };
  22657. /**
  22658. * Remove a mesh from the LOD array
  22659. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22660. * @param {Mesh} mesh The mesh to be removed.
  22661. * @return {Mesh} This mesh (for chaining)
  22662. */
  22663. Mesh.prototype.removeLODLevel = function (mesh) {
  22664. for (var index = 0; index < this._LODLevels.length; index++) {
  22665. if (this._LODLevels[index].mesh === mesh) {
  22666. this._LODLevels.splice(index, 1);
  22667. if (mesh) {
  22668. mesh._masterMesh = null;
  22669. }
  22670. }
  22671. }
  22672. this._sortLODLevels();
  22673. return this;
  22674. };
  22675. /**
  22676. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22677. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22678. */
  22679. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22680. if (!this._LODLevels || this._LODLevels.length === 0) {
  22681. return this;
  22682. }
  22683. var bSphere;
  22684. if (boundingSphere) {
  22685. bSphere = boundingSphere;
  22686. }
  22687. else {
  22688. var boundingInfo = this.getBoundingInfo();
  22689. if (!boundingInfo) {
  22690. return this;
  22691. }
  22692. bSphere = boundingInfo.boundingSphere;
  22693. }
  22694. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  22695. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22696. if (this.onLODLevelSelection) {
  22697. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22698. }
  22699. return this;
  22700. }
  22701. for (var index = 0; index < this._LODLevels.length; index++) {
  22702. var level = this._LODLevels[index];
  22703. if (level.distance < distanceToCamera) {
  22704. if (level.mesh) {
  22705. level.mesh._preActivate();
  22706. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22707. }
  22708. if (this.onLODLevelSelection) {
  22709. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22710. }
  22711. return level.mesh;
  22712. }
  22713. }
  22714. if (this.onLODLevelSelection) {
  22715. this.onLODLevelSelection(distanceToCamera, this, this);
  22716. }
  22717. return this;
  22718. };
  22719. Object.defineProperty(Mesh.prototype, "geometry", {
  22720. /**
  22721. * Returns the mesh internal Geometry object.
  22722. */
  22723. get: function () {
  22724. return this._geometry;
  22725. },
  22726. enumerable: true,
  22727. configurable: true
  22728. });
  22729. /**
  22730. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22731. */
  22732. Mesh.prototype.getTotalVertices = function () {
  22733. if (!this._geometry) {
  22734. return 0;
  22735. }
  22736. return this._geometry.getTotalVertices();
  22737. };
  22738. /**
  22739. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22740. * 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.
  22741. * You can force the copy with forceCopy === true
  22742. * Returns null if the mesh has no geometry or no vertex buffer.
  22743. * Possible `kind` values :
  22744. * - BABYLON.VertexBuffer.PositionKind
  22745. * - BABYLON.VertexBuffer.UVKind
  22746. * - BABYLON.VertexBuffer.UV2Kind
  22747. * - BABYLON.VertexBuffer.UV3Kind
  22748. * - BABYLON.VertexBuffer.UV4Kind
  22749. * - BABYLON.VertexBuffer.UV5Kind
  22750. * - BABYLON.VertexBuffer.UV6Kind
  22751. * - BABYLON.VertexBuffer.ColorKind
  22752. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22753. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22754. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22755. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22756. */
  22757. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22758. if (!this._geometry) {
  22759. return null;
  22760. }
  22761. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22762. };
  22763. /**
  22764. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22765. * Returns `null` if the mesh has no geometry.
  22766. * Possible `kind` values :
  22767. * - BABYLON.VertexBuffer.PositionKind
  22768. * - BABYLON.VertexBuffer.UVKind
  22769. * - BABYLON.VertexBuffer.UV2Kind
  22770. * - BABYLON.VertexBuffer.UV3Kind
  22771. * - BABYLON.VertexBuffer.UV4Kind
  22772. * - BABYLON.VertexBuffer.UV5Kind
  22773. * - BABYLON.VertexBuffer.UV6Kind
  22774. * - BABYLON.VertexBuffer.ColorKind
  22775. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22776. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22777. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22778. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22779. */
  22780. Mesh.prototype.getVertexBuffer = function (kind) {
  22781. if (!this._geometry) {
  22782. return null;
  22783. }
  22784. return this._geometry.getVertexBuffer(kind);
  22785. };
  22786. /**
  22787. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22788. * Possible `kind` values :
  22789. * - BABYLON.VertexBuffer.PositionKind
  22790. * - BABYLON.VertexBuffer.UVKind
  22791. * - BABYLON.VertexBuffer.UV2Kind
  22792. * - BABYLON.VertexBuffer.UV3Kind
  22793. * - BABYLON.VertexBuffer.UV4Kind
  22794. * - BABYLON.VertexBuffer.UV5Kind
  22795. * - BABYLON.VertexBuffer.UV6Kind
  22796. * - BABYLON.VertexBuffer.ColorKind
  22797. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22798. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22799. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22800. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22801. */
  22802. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22803. if (!this._geometry) {
  22804. if (this._delayInfo) {
  22805. return this._delayInfo.indexOf(kind) !== -1;
  22806. }
  22807. return false;
  22808. }
  22809. return this._geometry.isVerticesDataPresent(kind);
  22810. };
  22811. /**
  22812. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  22813. * Possible `kind` values :
  22814. * - BABYLON.VertexBuffer.PositionKind
  22815. * - BABYLON.VertexBuffer.UVKind
  22816. * - BABYLON.VertexBuffer.UV2Kind
  22817. * - BABYLON.VertexBuffer.UV3Kind
  22818. * - BABYLON.VertexBuffer.UV4Kind
  22819. * - BABYLON.VertexBuffer.UV5Kind
  22820. * - BABYLON.VertexBuffer.UV6Kind
  22821. * - BABYLON.VertexBuffer.ColorKind
  22822. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22823. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22824. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22825. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22826. */
  22827. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  22828. if (!this._geometry) {
  22829. if (this._delayInfo) {
  22830. return this._delayInfo.indexOf(kind) !== -1;
  22831. }
  22832. return false;
  22833. }
  22834. return this._geometry.isVertexBufferUpdatable(kind);
  22835. };
  22836. /**
  22837. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22838. * Possible `kind` values :
  22839. * - BABYLON.VertexBuffer.PositionKind
  22840. * - BABYLON.VertexBuffer.UVKind
  22841. * - BABYLON.VertexBuffer.UV2Kind
  22842. * - BABYLON.VertexBuffer.UV3Kind
  22843. * - BABYLON.VertexBuffer.UV4Kind
  22844. * - BABYLON.VertexBuffer.UV5Kind
  22845. * - BABYLON.VertexBuffer.UV6Kind
  22846. * - BABYLON.VertexBuffer.ColorKind
  22847. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22848. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22849. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22850. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22851. */
  22852. Mesh.prototype.getVerticesDataKinds = function () {
  22853. if (!this._geometry) {
  22854. var result = new Array();
  22855. if (this._delayInfo) {
  22856. this._delayInfo.forEach(function (kind, index, array) {
  22857. result.push(kind);
  22858. });
  22859. }
  22860. return result;
  22861. }
  22862. return this._geometry.getVerticesDataKinds();
  22863. };
  22864. /**
  22865. * Returns a positive integer : the total number of indices in this mesh geometry.
  22866. * Returns zero if the mesh has no geometry.
  22867. */
  22868. Mesh.prototype.getTotalIndices = function () {
  22869. if (!this._geometry) {
  22870. return 0;
  22871. }
  22872. return this._geometry.getTotalIndices();
  22873. };
  22874. /**
  22875. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22876. * 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.
  22877. * Returns an empty array if the mesh has no geometry.
  22878. */
  22879. Mesh.prototype.getIndices = function (copyWhenShared) {
  22880. if (!this._geometry) {
  22881. return [];
  22882. }
  22883. return this._geometry.getIndices(copyWhenShared);
  22884. };
  22885. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22886. get: function () {
  22887. return this._masterMesh !== null && this._masterMesh !== undefined;
  22888. },
  22889. enumerable: true,
  22890. configurable: true
  22891. });
  22892. /**
  22893. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22894. */
  22895. Mesh.prototype.isReady = function () {
  22896. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22897. return false;
  22898. }
  22899. return _super.prototype.isReady.call(this);
  22900. };
  22901. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22902. /**
  22903. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22904. * This property is pertinent only for updatable parametric shapes.
  22905. */
  22906. get: function () {
  22907. return this._areNormalsFrozen;
  22908. },
  22909. enumerable: true,
  22910. configurable: true
  22911. });
  22912. /**
  22913. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22914. * It has no effect at all on other shapes.
  22915. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22916. * Returns the Mesh.
  22917. */
  22918. Mesh.prototype.freezeNormals = function () {
  22919. this._areNormalsFrozen = true;
  22920. return this;
  22921. };
  22922. /**
  22923. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22924. * It has no effect at all on other shapes.
  22925. * It reactivates the mesh normals computation if it was previously frozen.
  22926. * Returns the Mesh.
  22927. */
  22928. Mesh.prototype.unfreezeNormals = function () {
  22929. this._areNormalsFrozen = false;
  22930. return this;
  22931. };
  22932. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22933. /**
  22934. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22935. */
  22936. set: function (count) {
  22937. this._overridenInstanceCount = count;
  22938. },
  22939. enumerable: true,
  22940. configurable: true
  22941. });
  22942. // Methods
  22943. Mesh.prototype._preActivate = function () {
  22944. var sceneRenderId = this.getScene().getRenderId();
  22945. if (this._preActivateId === sceneRenderId) {
  22946. return this;
  22947. }
  22948. this._preActivateId = sceneRenderId;
  22949. this._visibleInstances = null;
  22950. return this;
  22951. };
  22952. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22953. if (this._visibleInstances) {
  22954. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22955. }
  22956. return this;
  22957. };
  22958. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22959. if (!this._visibleInstances) {
  22960. this._visibleInstances = {};
  22961. this._visibleInstances.defaultRenderId = renderId;
  22962. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22963. }
  22964. if (!this._visibleInstances[renderId]) {
  22965. this._visibleInstances[renderId] = new Array();
  22966. }
  22967. this._visibleInstances[renderId].push(instance);
  22968. return this;
  22969. };
  22970. /**
  22971. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22972. * This means the mesh underlying bounding box and sphere are recomputed.
  22973. * Returns the Mesh.
  22974. */
  22975. Mesh.prototype.refreshBoundingInfo = function () {
  22976. if (this._boundingInfo && this._boundingInfo.isLocked) {
  22977. return this;
  22978. }
  22979. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22980. if (data) {
  22981. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22982. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22983. }
  22984. if (this.subMeshes) {
  22985. for (var index = 0; index < this.subMeshes.length; index++) {
  22986. this.subMeshes[index].refreshBoundingInfo();
  22987. }
  22988. }
  22989. this._updateBoundingInfo();
  22990. return this;
  22991. };
  22992. Mesh.prototype._createGlobalSubMesh = function (force) {
  22993. var totalVertices = this.getTotalVertices();
  22994. if (!totalVertices || !this.getIndices()) {
  22995. return null;
  22996. }
  22997. // Check if we need to recreate the submeshes
  22998. if (this.subMeshes && this.subMeshes.length > 0) {
  22999. var ib = this.getIndices();
  23000. if (!ib) {
  23001. return null;
  23002. }
  23003. var totalIndices = ib.length;
  23004. var needToRecreate = false;
  23005. if (force) {
  23006. needToRecreate = true;
  23007. }
  23008. else {
  23009. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23010. var submesh = _a[_i];
  23011. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23012. needToRecreate = true;
  23013. break;
  23014. }
  23015. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23016. needToRecreate = true;
  23017. break;
  23018. }
  23019. }
  23020. }
  23021. if (!needToRecreate) {
  23022. return this.subMeshes[0];
  23023. }
  23024. }
  23025. this.releaseSubMeshes();
  23026. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23027. };
  23028. Mesh.prototype.subdivide = function (count) {
  23029. if (count < 1) {
  23030. return;
  23031. }
  23032. var totalIndices = this.getTotalIndices();
  23033. var subdivisionSize = (totalIndices / count) | 0;
  23034. var offset = 0;
  23035. // Ensure that subdivisionSize is a multiple of 3
  23036. while (subdivisionSize % 3 !== 0) {
  23037. subdivisionSize++;
  23038. }
  23039. this.releaseSubMeshes();
  23040. for (var index = 0; index < count; index++) {
  23041. if (offset >= totalIndices) {
  23042. break;
  23043. }
  23044. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23045. offset += subdivisionSize;
  23046. }
  23047. this.synchronizeInstances();
  23048. };
  23049. /**
  23050. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23051. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23052. * The `data` are either a numeric array either a Float32Array.
  23053. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23054. * 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).
  23055. * Note that a new underlying VertexBuffer object is created each call.
  23056. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23057. *
  23058. * Possible `kind` values :
  23059. * - BABYLON.VertexBuffer.PositionKind
  23060. * - BABYLON.VertexBuffer.UVKind
  23061. * - BABYLON.VertexBuffer.UV2Kind
  23062. * - BABYLON.VertexBuffer.UV3Kind
  23063. * - BABYLON.VertexBuffer.UV4Kind
  23064. * - BABYLON.VertexBuffer.UV5Kind
  23065. * - BABYLON.VertexBuffer.UV6Kind
  23066. * - BABYLON.VertexBuffer.ColorKind
  23067. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23068. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23069. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23070. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23071. *
  23072. * Returns the Mesh.
  23073. */
  23074. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23075. if (updatable === void 0) { updatable = false; }
  23076. if (!this._geometry) {
  23077. var vertexData = new BABYLON.VertexData();
  23078. vertexData.set(data, kind);
  23079. var scene = this.getScene();
  23080. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23081. }
  23082. else {
  23083. this._geometry.setVerticesData(kind, data, updatable, stride);
  23084. }
  23085. return this;
  23086. };
  23087. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23088. if (updatable === void 0) { updatable = true; }
  23089. var vb = this.getVertexBuffer(kind);
  23090. if (!vb || vb.isUpdatable() === updatable) {
  23091. return;
  23092. }
  23093. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23094. };
  23095. /**
  23096. * Sets the mesh VertexBuffer.
  23097. * Returns the Mesh.
  23098. */
  23099. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23100. if (!this._geometry) {
  23101. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23102. }
  23103. this._geometry.setVerticesBuffer(buffer);
  23104. return this;
  23105. };
  23106. /**
  23107. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23108. * If the mesh has no geometry, it is simply returned as it is.
  23109. * The `data` are either a numeric array either a Float32Array.
  23110. * No new underlying VertexBuffer object is created.
  23111. * 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.
  23112. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23113. *
  23114. * Possible `kind` values :
  23115. * - BABYLON.VertexBuffer.PositionKind
  23116. * - BABYLON.VertexBuffer.UVKind
  23117. * - BABYLON.VertexBuffer.UV2Kind
  23118. * - BABYLON.VertexBuffer.UV3Kind
  23119. * - BABYLON.VertexBuffer.UV4Kind
  23120. * - BABYLON.VertexBuffer.UV5Kind
  23121. * - BABYLON.VertexBuffer.UV6Kind
  23122. * - BABYLON.VertexBuffer.ColorKind
  23123. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23124. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23125. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23126. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23127. *
  23128. * Returns the Mesh.
  23129. */
  23130. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23131. if (!this._geometry) {
  23132. return this;
  23133. }
  23134. if (!makeItUnique) {
  23135. this._geometry.updateVerticesData(kind, data, updateExtends);
  23136. }
  23137. else {
  23138. this.makeGeometryUnique();
  23139. this.updateVerticesData(kind, data, updateExtends, false);
  23140. }
  23141. return this;
  23142. };
  23143. /**
  23144. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23145. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23146. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23147. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23148. * Returns the Mesh.
  23149. */
  23150. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23151. if (computeNormals === void 0) { computeNormals = true; }
  23152. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23153. if (!positions) {
  23154. return this;
  23155. }
  23156. positionFunction(positions);
  23157. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23158. if (computeNormals) {
  23159. var indices = this.getIndices();
  23160. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23161. if (!normals) {
  23162. return this;
  23163. }
  23164. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23165. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23166. }
  23167. return this;
  23168. };
  23169. /**
  23170. * Creates a un-shared specific occurence of the geometry for the mesh.
  23171. * Returns the Mesh.
  23172. */
  23173. Mesh.prototype.makeGeometryUnique = function () {
  23174. if (!this._geometry) {
  23175. return this;
  23176. }
  23177. var oldGeometry = this._geometry;
  23178. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23179. oldGeometry.releaseForMesh(this, true);
  23180. geometry.applyToMesh(this);
  23181. return this;
  23182. };
  23183. /**
  23184. * Sets the mesh indices.
  23185. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23186. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23187. * This method creates a new index buffer each call.
  23188. * Returns the Mesh.
  23189. */
  23190. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23191. if (totalVertices === void 0) { totalVertices = null; }
  23192. if (updatable === void 0) { updatable = false; }
  23193. if (!this._geometry) {
  23194. var vertexData = new BABYLON.VertexData();
  23195. vertexData.indices = indices;
  23196. var scene = this.getScene();
  23197. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23198. }
  23199. else {
  23200. this._geometry.setIndices(indices, totalVertices, updatable);
  23201. }
  23202. return this;
  23203. };
  23204. /**
  23205. * Update the current index buffer
  23206. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23207. * Returns the Mesh.
  23208. */
  23209. Mesh.prototype.updateIndices = function (indices, offset) {
  23210. if (!this._geometry) {
  23211. return this;
  23212. }
  23213. this._geometry.updateIndices(indices, offset);
  23214. return this;
  23215. };
  23216. /**
  23217. * Invert the geometry to move from a right handed system to a left handed one.
  23218. * Returns the Mesh.
  23219. */
  23220. Mesh.prototype.toLeftHanded = function () {
  23221. if (!this._geometry) {
  23222. return this;
  23223. }
  23224. this._geometry.toLeftHanded();
  23225. return this;
  23226. };
  23227. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23228. if (!this._geometry) {
  23229. return this;
  23230. }
  23231. var engine = this.getScene().getEngine();
  23232. // Wireframe
  23233. var indexToBind;
  23234. if (this._unIndexed) {
  23235. indexToBind = null;
  23236. }
  23237. else {
  23238. switch (fillMode) {
  23239. case BABYLON.Material.PointFillMode:
  23240. indexToBind = null;
  23241. break;
  23242. case BABYLON.Material.WireFrameFillMode:
  23243. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23244. break;
  23245. default:
  23246. case BABYLON.Material.TriangleFillMode:
  23247. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23248. break;
  23249. }
  23250. }
  23251. // VBOs
  23252. this._geometry._bind(effect, indexToBind);
  23253. return this;
  23254. };
  23255. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23256. if (alternate === void 0) { alternate = false; }
  23257. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23258. return this;
  23259. }
  23260. this.onBeforeDrawObservable.notifyObservers(this);
  23261. var scene = this.getScene();
  23262. var engine = scene.getEngine();
  23263. // Draw order
  23264. switch (fillMode) {
  23265. case BABYLON.Material.PointFillMode:
  23266. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23267. break;
  23268. case BABYLON.Material.WireFrameFillMode:
  23269. if (this._unIndexed) {
  23270. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23271. }
  23272. else {
  23273. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23274. }
  23275. break;
  23276. default:
  23277. if (this._unIndexed) {
  23278. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23279. }
  23280. else {
  23281. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23282. }
  23283. }
  23284. if (scene._isAlternateRenderingEnabled && !alternate) {
  23285. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23286. if (!effect || !scene.activeCamera) {
  23287. return this;
  23288. }
  23289. scene._switchToAlternateCameraConfiguration(true);
  23290. this._effectiveMaterial.bindView(effect);
  23291. this._effectiveMaterial.bindViewProjection(effect);
  23292. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23293. this._draw(subMesh, fillMode, instancesCount, true);
  23294. engine.setViewport(scene.activeCamera.viewport);
  23295. scene._switchToAlternateCameraConfiguration(false);
  23296. this._effectiveMaterial.bindView(effect);
  23297. this._effectiveMaterial.bindViewProjection(effect);
  23298. }
  23299. return this;
  23300. };
  23301. /**
  23302. * Registers for this mesh a javascript function called just before the rendering process.
  23303. * This function is passed the current mesh.
  23304. * Return the Mesh.
  23305. */
  23306. Mesh.prototype.registerBeforeRender = function (func) {
  23307. this.onBeforeRenderObservable.add(func);
  23308. return this;
  23309. };
  23310. /**
  23311. * Disposes a previously registered javascript function called before the rendering.
  23312. * This function is passed the current mesh.
  23313. * Returns the Mesh.
  23314. */
  23315. Mesh.prototype.unregisterBeforeRender = function (func) {
  23316. this.onBeforeRenderObservable.removeCallback(func);
  23317. return this;
  23318. };
  23319. /**
  23320. * Registers for this mesh a javascript function called just after the rendering is complete.
  23321. * This function is passed the current mesh.
  23322. * Returns the Mesh.
  23323. */
  23324. Mesh.prototype.registerAfterRender = function (func) {
  23325. this.onAfterRenderObservable.add(func);
  23326. return this;
  23327. };
  23328. /**
  23329. * Disposes a previously registered javascript function called after the rendering.
  23330. * This function is passed the current mesh.
  23331. * Return the Mesh.
  23332. */
  23333. Mesh.prototype.unregisterAfterRender = function (func) {
  23334. this.onAfterRenderObservable.removeCallback(func);
  23335. return this;
  23336. };
  23337. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23338. var scene = this.getScene();
  23339. this._batchCache.mustReturn = false;
  23340. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23341. this._batchCache.visibleInstances[subMeshId] = null;
  23342. if (this._visibleInstances) {
  23343. var currentRenderId = scene.getRenderId();
  23344. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23345. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23346. var selfRenderId = this._renderId;
  23347. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23348. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23349. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23350. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23351. }
  23352. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23353. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23354. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23355. this._batchCache.mustReturn = true;
  23356. return this._batchCache;
  23357. }
  23358. if (currentRenderId !== selfRenderId) {
  23359. this._batchCache.renderSelf[subMeshId] = false;
  23360. }
  23361. }
  23362. this._renderIdForInstances[subMeshId] = currentRenderId;
  23363. }
  23364. return this._batchCache;
  23365. };
  23366. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23367. var visibleInstances = batch.visibleInstances[subMesh._id];
  23368. if (!visibleInstances) {
  23369. return this;
  23370. }
  23371. var matricesCount = visibleInstances.length + 1;
  23372. var bufferSize = matricesCount * 16 * 4;
  23373. var currentInstancesBufferSize = this._instancesBufferSize;
  23374. var instancesBuffer = this._instancesBuffer;
  23375. while (this._instancesBufferSize < bufferSize) {
  23376. this._instancesBufferSize *= 2;
  23377. }
  23378. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23379. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23380. }
  23381. var offset = 0;
  23382. var instancesCount = 0;
  23383. var world = this.getWorldMatrix(true);
  23384. if (batch.renderSelf[subMesh._id]) {
  23385. world.copyToArray(this._instancesData, offset);
  23386. offset += 16;
  23387. instancesCount++;
  23388. }
  23389. if (visibleInstances) {
  23390. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23391. var instance = visibleInstances[instanceIndex];
  23392. instance.getWorldMatrix(true).copyToArray(this._instancesData, offset);
  23393. offset += 16;
  23394. instancesCount++;
  23395. }
  23396. }
  23397. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23398. if (instancesBuffer) {
  23399. instancesBuffer.dispose();
  23400. }
  23401. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23402. this._instancesBuffer = instancesBuffer;
  23403. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23404. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23405. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23406. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23407. }
  23408. else {
  23409. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23410. }
  23411. this._bind(subMesh, effect, fillMode);
  23412. this._draw(subMesh, fillMode, instancesCount);
  23413. engine.unbindInstanceAttributes();
  23414. return this;
  23415. };
  23416. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23417. var scene = this.getScene();
  23418. var engine = scene.getEngine();
  23419. if (hardwareInstancedRendering) {
  23420. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23421. }
  23422. else {
  23423. if (batch.renderSelf[subMesh._id]) {
  23424. // Draw
  23425. if (onBeforeDraw) {
  23426. onBeforeDraw(false, this.getWorldMatrix(true), effectiveMaterial);
  23427. }
  23428. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23429. }
  23430. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23431. if (visibleInstancesForSubMesh) {
  23432. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23433. var instance = visibleInstancesForSubMesh[instanceIndex];
  23434. // World
  23435. var world = instance.getWorldMatrix(true);
  23436. if (onBeforeDraw) {
  23437. onBeforeDraw(true, world, effectiveMaterial);
  23438. }
  23439. // Draw
  23440. this._draw(subMesh, fillMode);
  23441. }
  23442. }
  23443. }
  23444. return this;
  23445. };
  23446. /**
  23447. * Triggers the draw call for the mesh.
  23448. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23449. * Returns the Mesh.
  23450. */
  23451. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23452. this.checkOcclusionQuery();
  23453. if (this._isOccluded) {
  23454. return this;
  23455. }
  23456. var scene = this.getScene();
  23457. // Managing instances
  23458. var batch = this._getInstancesRenderList(subMesh._id);
  23459. if (batch.mustReturn) {
  23460. return this;
  23461. }
  23462. // Checking geometry state
  23463. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23464. return this;
  23465. }
  23466. this.onBeforeRenderObservable.notifyObservers(this);
  23467. var engine = scene.getEngine();
  23468. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23469. // Material
  23470. var material = subMesh.getMaterial();
  23471. if (!material) {
  23472. return this;
  23473. }
  23474. this._effectiveMaterial = material;
  23475. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23476. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23477. return this;
  23478. }
  23479. }
  23480. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23481. return this;
  23482. }
  23483. // Alpha mode
  23484. if (enableAlphaMode) {
  23485. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23486. }
  23487. // Outline - step 1
  23488. var savedDepthWrite = engine.getDepthWrite();
  23489. if (this.renderOutline) {
  23490. engine.setDepthWrite(false);
  23491. scene.getOutlineRenderer().render(subMesh, batch);
  23492. engine.setDepthWrite(savedDepthWrite);
  23493. }
  23494. var effect;
  23495. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23496. effect = subMesh.effect;
  23497. }
  23498. else {
  23499. effect = this._effectiveMaterial.getEffect();
  23500. }
  23501. if (!effect) {
  23502. return this;
  23503. }
  23504. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23505. if (this._effectiveMaterial.forceDepthWrite) {
  23506. engine.setDepthWrite(true);
  23507. }
  23508. // Bind
  23509. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  23510. if (!hardwareInstancedRendering) {
  23511. this._bind(subMesh, effect, fillMode);
  23512. }
  23513. var world = this.getWorldMatrix(true);
  23514. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23515. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  23516. }
  23517. else {
  23518. this._effectiveMaterial.bind(world, this);
  23519. }
  23520. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  23521. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  23522. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23523. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  23524. }
  23525. // Draw
  23526. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23527. // Unbind
  23528. this._effectiveMaterial.unbind();
  23529. // Outline - step 2
  23530. if (this.renderOutline && savedDepthWrite) {
  23531. engine.setDepthWrite(true);
  23532. engine.setColorWrite(false);
  23533. scene.getOutlineRenderer().render(subMesh, batch);
  23534. engine.setColorWrite(true);
  23535. }
  23536. // Overlay
  23537. if (this.renderOverlay) {
  23538. var currentMode = engine.getAlphaMode();
  23539. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23540. scene.getOutlineRenderer().render(subMesh, batch, true);
  23541. engine.setAlphaMode(currentMode);
  23542. }
  23543. this.onAfterRenderObservable.notifyObservers(this);
  23544. return this;
  23545. };
  23546. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23547. if (isInstance) {
  23548. effectiveMaterial.bindOnlyWorldMatrix(world);
  23549. }
  23550. return this;
  23551. };
  23552. /**
  23553. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23554. */
  23555. Mesh.prototype.getEmittedParticleSystems = function () {
  23556. var results = new Array();
  23557. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23558. var particleSystem = this.getScene().particleSystems[index];
  23559. if (particleSystem.emitter === this) {
  23560. results.push(particleSystem);
  23561. }
  23562. }
  23563. return results;
  23564. };
  23565. /**
  23566. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23567. */
  23568. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23569. var results = new Array();
  23570. var descendants = this.getDescendants();
  23571. descendants.push(this);
  23572. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23573. var particleSystem = this.getScene().particleSystems[index];
  23574. var emitter = particleSystem.emitter;
  23575. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23576. results.push(particleSystem);
  23577. }
  23578. }
  23579. return results;
  23580. };
  23581. Mesh.prototype._checkDelayState = function () {
  23582. var scene = this.getScene();
  23583. if (this._geometry) {
  23584. this._geometry.load(scene);
  23585. }
  23586. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23587. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23588. this._queueLoad(this, scene);
  23589. }
  23590. return this;
  23591. };
  23592. Mesh.prototype._queueLoad = function (mesh, scene) {
  23593. var _this = this;
  23594. scene._addPendingData(mesh);
  23595. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23596. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23597. if (data instanceof ArrayBuffer) {
  23598. _this._delayLoadingFunction(data, _this);
  23599. }
  23600. else {
  23601. _this._delayLoadingFunction(JSON.parse(data), _this);
  23602. }
  23603. _this.instances.forEach(function (instance) {
  23604. instance._syncSubMeshes();
  23605. });
  23606. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23607. scene._removePendingData(_this);
  23608. }, function () { }, scene.database, getBinaryData);
  23609. return this;
  23610. };
  23611. /**
  23612. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23613. */
  23614. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23615. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23616. return false;
  23617. }
  23618. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23619. return false;
  23620. }
  23621. this._checkDelayState();
  23622. return true;
  23623. };
  23624. /**
  23625. * Sets the mesh material by the material or multiMaterial `id` property.
  23626. * The material `id` is a string identifying the material or the multiMaterial.
  23627. * This method returns the Mesh.
  23628. */
  23629. Mesh.prototype.setMaterialByID = function (id) {
  23630. var materials = this.getScene().materials;
  23631. var index;
  23632. for (index = materials.length - 1; index > -1; index--) {
  23633. if (materials[index].id === id) {
  23634. this.material = materials[index];
  23635. return this;
  23636. }
  23637. }
  23638. // Multi
  23639. var multiMaterials = this.getScene().multiMaterials;
  23640. for (index = multiMaterials.length - 1; index > -1; index--) {
  23641. if (multiMaterials[index].id === id) {
  23642. this.material = multiMaterials[index];
  23643. return this;
  23644. }
  23645. }
  23646. return this;
  23647. };
  23648. /**
  23649. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23650. */
  23651. Mesh.prototype.getAnimatables = function () {
  23652. var results = new Array();
  23653. if (this.material) {
  23654. results.push(this.material);
  23655. }
  23656. if (this.skeleton) {
  23657. results.push(this.skeleton);
  23658. }
  23659. return results;
  23660. };
  23661. /**
  23662. * Modifies the mesh geometry according to the passed transformation matrix.
  23663. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23664. * The mesh normals are modified accordingly the same transformation.
  23665. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23666. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23667. * Returns the Mesh.
  23668. */
  23669. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23670. // Position
  23671. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23672. return this;
  23673. }
  23674. var submeshes = this.subMeshes.splice(0);
  23675. this._resetPointsArrayCache();
  23676. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23677. var temp = new Array();
  23678. var index;
  23679. for (index = 0; index < data.length; index += 3) {
  23680. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23681. }
  23682. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23683. // Normals
  23684. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23685. return this;
  23686. }
  23687. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23688. temp = [];
  23689. for (index = 0; index < data.length; index += 3) {
  23690. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23691. }
  23692. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23693. // flip faces?
  23694. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23695. this.flipFaces();
  23696. }
  23697. // Restore submeshes
  23698. this.releaseSubMeshes();
  23699. this.subMeshes = submeshes;
  23700. return this;
  23701. };
  23702. /**
  23703. * Modifies the mesh geometry according to its own current World Matrix.
  23704. * The mesh World Matrix is then reset.
  23705. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23706. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23707. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23708. * Returns the Mesh.
  23709. */
  23710. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23711. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23712. this.scaling.copyFromFloats(1, 1, 1);
  23713. this.position.copyFromFloats(0, 0, 0);
  23714. this.rotation.copyFromFloats(0, 0, 0);
  23715. //only if quaternion is already set
  23716. if (this.rotationQuaternion) {
  23717. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23718. }
  23719. this._worldMatrix = BABYLON.Matrix.Identity();
  23720. return this;
  23721. };
  23722. Object.defineProperty(Mesh.prototype, "_positions", {
  23723. // Cache
  23724. get: function () {
  23725. if (this._geometry) {
  23726. return this._geometry._positions;
  23727. }
  23728. return null;
  23729. },
  23730. enumerable: true,
  23731. configurable: true
  23732. });
  23733. Mesh.prototype._resetPointsArrayCache = function () {
  23734. if (this._geometry) {
  23735. this._geometry._resetPointsArrayCache();
  23736. }
  23737. return this;
  23738. };
  23739. Mesh.prototype._generatePointsArray = function () {
  23740. if (this._geometry) {
  23741. return this._geometry._generatePointsArray();
  23742. }
  23743. return false;
  23744. };
  23745. /**
  23746. * Returns a new Mesh object generated from the current mesh properties.
  23747. * This method must not get confused with createInstance().
  23748. * The parameter `name` is a string, the name given to the new mesh.
  23749. * The optional parameter `newParent` can be any Node object (default `null`).
  23750. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23751. * 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.
  23752. */
  23753. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23754. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23755. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23756. };
  23757. /**
  23758. * Disposes the mesh.
  23759. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23760. */
  23761. Mesh.prototype.dispose = function (doNotRecurse) {
  23762. var _this = this;
  23763. this.morphTargetManager = null;
  23764. if (this._geometry) {
  23765. this._geometry.releaseForMesh(this, true);
  23766. }
  23767. // Sources
  23768. var meshes = this.getScene().meshes;
  23769. meshes.forEach(function (mesh) {
  23770. if (mesh._source && mesh._source === _this) {
  23771. mesh._source = null;
  23772. }
  23773. });
  23774. this._source = null;
  23775. // Instances
  23776. if (this._instancesBuffer) {
  23777. this._instancesBuffer.dispose();
  23778. this._instancesBuffer = null;
  23779. }
  23780. while (this.instances.length) {
  23781. this.instances[0].dispose();
  23782. }
  23783. // Highlight layers.
  23784. var highlightLayers = this.getScene().highlightLayers;
  23785. for (var i = 0; i < highlightLayers.length; i++) {
  23786. var highlightLayer = highlightLayers[i];
  23787. if (highlightLayer) {
  23788. highlightLayer.removeMesh(this);
  23789. highlightLayer.removeExcludedMesh(this);
  23790. }
  23791. }
  23792. _super.prototype.dispose.call(this, doNotRecurse);
  23793. };
  23794. /**
  23795. * Modifies the mesh geometry according to a displacement map.
  23796. * 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.
  23797. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23798. * This method returns nothing.
  23799. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23800. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23801. * 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.
  23802. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23803. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23804. *
  23805. * Returns the Mesh.
  23806. */
  23807. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23808. var _this = this;
  23809. var scene = this.getScene();
  23810. var onload = function (img) {
  23811. // Getting height map data
  23812. var canvas = document.createElement("canvas");
  23813. var context = canvas.getContext("2d");
  23814. var heightMapWidth = img.width;
  23815. var heightMapHeight = img.height;
  23816. canvas.width = heightMapWidth;
  23817. canvas.height = heightMapHeight;
  23818. context.drawImage(img, 0, 0);
  23819. // Create VertexData from map data
  23820. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23821. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23822. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23823. //execute success callback, if set
  23824. if (onSuccess) {
  23825. onSuccess(_this);
  23826. }
  23827. };
  23828. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23829. return this;
  23830. };
  23831. /**
  23832. * Modifies the mesh geometry according to a displacementMap buffer.
  23833. * 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.
  23834. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23835. * This method returns nothing.
  23836. * 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.
  23837. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23838. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23839. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23840. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23841. *
  23842. * Returns the Mesh.
  23843. */
  23844. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23845. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23846. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23847. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23848. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23849. return this;
  23850. }
  23851. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23852. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23853. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23854. var position = BABYLON.Vector3.Zero();
  23855. var normal = BABYLON.Vector3.Zero();
  23856. var uv = BABYLON.Vector2.Zero();
  23857. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23858. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23859. for (var index = 0; index < positions.length; index += 3) {
  23860. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23861. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23862. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23863. // Compute height
  23864. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23865. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23866. var pos = (u + v * heightMapWidth) * 4;
  23867. var r = buffer[pos] / 255.0;
  23868. var g = buffer[pos + 1] / 255.0;
  23869. var b = buffer[pos + 2] / 255.0;
  23870. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23871. normal.normalize();
  23872. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23873. position = position.add(normal);
  23874. position.toArray(positions, index);
  23875. }
  23876. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23877. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23878. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23879. return this;
  23880. };
  23881. /**
  23882. * Modify the mesh to get a flat shading rendering.
  23883. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23884. * This method returns the Mesh.
  23885. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23886. */
  23887. Mesh.prototype.convertToFlatShadedMesh = function () {
  23888. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23889. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23890. var kinds = this.getVerticesDataKinds();
  23891. var vbs = {};
  23892. var data = {};
  23893. var newdata = {};
  23894. var updatableNormals = false;
  23895. var kindIndex;
  23896. var kind;
  23897. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23898. kind = kinds[kindIndex];
  23899. var vertexBuffer = this.getVertexBuffer(kind);
  23900. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23901. updatableNormals = vertexBuffer.isUpdatable();
  23902. kinds.splice(kindIndex, 1);
  23903. kindIndex--;
  23904. continue;
  23905. }
  23906. vbs[kind] = vertexBuffer;
  23907. data[kind] = vbs[kind].getData();
  23908. newdata[kind] = [];
  23909. }
  23910. // Save previous submeshes
  23911. var previousSubmeshes = this.subMeshes.slice(0);
  23912. var indices = this.getIndices();
  23913. var totalIndices = this.getTotalIndices();
  23914. // Generating unique vertices per face
  23915. var index;
  23916. for (index = 0; index < totalIndices; index++) {
  23917. var vertexIndex = indices[index];
  23918. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23919. kind = kinds[kindIndex];
  23920. var stride = vbs[kind].getStrideSize();
  23921. for (var offset = 0; offset < stride; offset++) {
  23922. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23923. }
  23924. }
  23925. }
  23926. // Updating faces & normal
  23927. var normals = [];
  23928. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23929. for (index = 0; index < totalIndices; index += 3) {
  23930. indices[index] = index;
  23931. indices[index + 1] = index + 1;
  23932. indices[index + 2] = index + 2;
  23933. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23934. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23935. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23936. var p1p2 = p1.subtract(p2);
  23937. var p3p2 = p3.subtract(p2);
  23938. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23939. // Store same normals for every vertex
  23940. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23941. normals.push(normal.x);
  23942. normals.push(normal.y);
  23943. normals.push(normal.z);
  23944. }
  23945. }
  23946. this.setIndices(indices);
  23947. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23948. // Updating vertex buffers
  23949. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23950. kind = kinds[kindIndex];
  23951. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23952. }
  23953. // Updating submeshes
  23954. this.releaseSubMeshes();
  23955. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23956. var previousOne = previousSubmeshes[submeshIndex];
  23957. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23958. }
  23959. this.synchronizeInstances();
  23960. return this;
  23961. };
  23962. /**
  23963. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23964. * In other words, more vertices, no more indices and a single bigger VBO.
  23965. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23966. * Returns the Mesh.
  23967. */
  23968. Mesh.prototype.convertToUnIndexedMesh = function () {
  23969. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23970. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23971. var kinds = this.getVerticesDataKinds();
  23972. var vbs = {};
  23973. var data = {};
  23974. var newdata = {};
  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. vbs[kind] = vertexBuffer;
  23981. data[kind] = vbs[kind].getData();
  23982. newdata[kind] = [];
  23983. }
  23984. // Save previous submeshes
  23985. var previousSubmeshes = this.subMeshes.slice(0);
  23986. var indices = this.getIndices();
  23987. var totalIndices = this.getTotalIndices();
  23988. // Generating unique vertices per face
  23989. var index;
  23990. for (index = 0; index < totalIndices; index++) {
  23991. var vertexIndex = indices[index];
  23992. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23993. kind = kinds[kindIndex];
  23994. var stride = vbs[kind].getStrideSize();
  23995. for (var offset = 0; offset < stride; offset++) {
  23996. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23997. }
  23998. }
  23999. }
  24000. // Updating indices
  24001. for (index = 0; index < totalIndices; index += 3) {
  24002. indices[index] = index;
  24003. indices[index + 1] = index + 1;
  24004. indices[index + 2] = index + 2;
  24005. }
  24006. this.setIndices(indices);
  24007. // Updating vertex buffers
  24008. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24009. kind = kinds[kindIndex];
  24010. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24011. }
  24012. // Updating submeshes
  24013. this.releaseSubMeshes();
  24014. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24015. var previousOne = previousSubmeshes[submeshIndex];
  24016. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24017. }
  24018. this._unIndexed = true;
  24019. this.synchronizeInstances();
  24020. return this;
  24021. };
  24022. /**
  24023. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24024. * This method returns the Mesh.
  24025. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24026. */
  24027. Mesh.prototype.flipFaces = function (flipNormals) {
  24028. if (flipNormals === void 0) { flipNormals = false; }
  24029. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24030. var i;
  24031. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24032. for (i = 0; i < vertex_data.normals.length; i++) {
  24033. vertex_data.normals[i] *= -1;
  24034. }
  24035. }
  24036. if (vertex_data.indices) {
  24037. var temp;
  24038. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24039. // reassign indices
  24040. temp = vertex_data.indices[i + 1];
  24041. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24042. vertex_data.indices[i + 2] = temp;
  24043. }
  24044. }
  24045. vertex_data.applyToMesh(this);
  24046. return this;
  24047. };
  24048. // Instances
  24049. /**
  24050. * Creates a new InstancedMesh object from the mesh model.
  24051. * An instance shares the same properties and the same material than its model.
  24052. * Only these properties of each instance can then be set individually :
  24053. * - position
  24054. * - rotation
  24055. * - rotationQuaternion
  24056. * - setPivotMatrix
  24057. * - scaling
  24058. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24059. * Warning : this method is not supported for Line mesh and LineSystem
  24060. */
  24061. Mesh.prototype.createInstance = function (name) {
  24062. return new BABYLON.InstancedMesh(name, this);
  24063. };
  24064. /**
  24065. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24066. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24067. * This method returns the Mesh.
  24068. */
  24069. Mesh.prototype.synchronizeInstances = function () {
  24070. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24071. var instance = this.instances[instanceIndex];
  24072. instance._syncSubMeshes();
  24073. }
  24074. return this;
  24075. };
  24076. /**
  24077. * Simplify the mesh according to the given array of settings.
  24078. * Function will return immediately and will simplify async. It returns the Mesh.
  24079. * @param settings a collection of simplification settings.
  24080. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24081. * @param type the type of simplification to run.
  24082. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24083. */
  24084. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24085. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24086. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24087. this.getScene().simplificationQueue.addTask({
  24088. settings: settings,
  24089. parallelProcessing: parallelProcessing,
  24090. mesh: this,
  24091. simplificationType: simplificationType,
  24092. successCallback: successCallback
  24093. });
  24094. return this;
  24095. };
  24096. /**
  24097. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24098. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24099. * This should be used together with the simplification to avoid disappearing triangles.
  24100. * Returns the Mesh.
  24101. * @param successCallback an optional success callback to be called after the optimization finished.
  24102. */
  24103. Mesh.prototype.optimizeIndices = function (successCallback) {
  24104. var _this = this;
  24105. var indices = this.getIndices();
  24106. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24107. if (!positions || !indices) {
  24108. return this;
  24109. }
  24110. var vectorPositions = new Array();
  24111. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24112. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24113. }
  24114. var dupes = new Array();
  24115. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24116. var realPos = vectorPositions.length - 1 - iteration;
  24117. var testedPosition = vectorPositions[realPos];
  24118. for (var j = 0; j < realPos; ++j) {
  24119. var againstPosition = vectorPositions[j];
  24120. if (testedPosition.equals(againstPosition)) {
  24121. dupes[realPos] = j;
  24122. break;
  24123. }
  24124. }
  24125. }, function () {
  24126. for (var i = 0; i < indices.length; ++i) {
  24127. indices[i] = dupes[indices[i]] || indices[i];
  24128. }
  24129. //indices are now reordered
  24130. var originalSubMeshes = _this.subMeshes.slice(0);
  24131. _this.setIndices(indices);
  24132. _this.subMeshes = originalSubMeshes;
  24133. if (successCallback) {
  24134. successCallback(_this);
  24135. }
  24136. });
  24137. return this;
  24138. };
  24139. Mesh.prototype.serialize = function (serializationObject) {
  24140. serializationObject.name = this.name;
  24141. serializationObject.id = this.id;
  24142. serializationObject.type = this.getClassName();
  24143. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24144. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24145. }
  24146. serializationObject.position = this.position.asArray();
  24147. if (this.rotationQuaternion) {
  24148. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24149. }
  24150. else if (this.rotation) {
  24151. serializationObject.rotation = this.rotation.asArray();
  24152. }
  24153. serializationObject.scaling = this.scaling.asArray();
  24154. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24155. serializationObject.isEnabled = this.isEnabled();
  24156. serializationObject.isVisible = this.isVisible;
  24157. serializationObject.infiniteDistance = this.infiniteDistance;
  24158. serializationObject.pickable = this.isPickable;
  24159. serializationObject.receiveShadows = this.receiveShadows;
  24160. serializationObject.billboardMode = this.billboardMode;
  24161. serializationObject.visibility = this.visibility;
  24162. serializationObject.checkCollisions = this.checkCollisions;
  24163. serializationObject.isBlocker = this.isBlocker;
  24164. // Parent
  24165. if (this.parent) {
  24166. serializationObject.parentId = this.parent.id;
  24167. }
  24168. // Geometry
  24169. var geometry = this._geometry;
  24170. if (geometry) {
  24171. var geometryId = geometry.id;
  24172. serializationObject.geometryId = geometryId;
  24173. // SubMeshes
  24174. serializationObject.subMeshes = [];
  24175. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24176. var subMesh = this.subMeshes[subIndex];
  24177. serializationObject.subMeshes.push({
  24178. materialIndex: subMesh.materialIndex,
  24179. verticesStart: subMesh.verticesStart,
  24180. verticesCount: subMesh.verticesCount,
  24181. indexStart: subMesh.indexStart,
  24182. indexCount: subMesh.indexCount
  24183. });
  24184. }
  24185. }
  24186. // Material
  24187. if (this.material) {
  24188. serializationObject.materialId = this.material.id;
  24189. }
  24190. else {
  24191. this.material = null;
  24192. }
  24193. // Morph targets
  24194. if (this.morphTargetManager) {
  24195. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24196. }
  24197. // Skeleton
  24198. if (this.skeleton) {
  24199. serializationObject.skeletonId = this.skeleton.id;
  24200. }
  24201. // Physics
  24202. //TODO implement correct serialization for physics impostors.
  24203. var impostor = this.getPhysicsImpostor();
  24204. if (impostor) {
  24205. serializationObject.physicsMass = impostor.getParam("mass");
  24206. serializationObject.physicsFriction = impostor.getParam("friction");
  24207. serializationObject.physicsRestitution = impostor.getParam("mass");
  24208. serializationObject.physicsImpostor = impostor.type;
  24209. }
  24210. // Metadata
  24211. if (this.metadata) {
  24212. serializationObject.metadata = this.metadata;
  24213. }
  24214. // Instances
  24215. serializationObject.instances = [];
  24216. for (var index = 0; index < this.instances.length; index++) {
  24217. var instance = this.instances[index];
  24218. var serializationInstance = {
  24219. name: instance.name,
  24220. position: instance.position.asArray(),
  24221. scaling: instance.scaling.asArray()
  24222. };
  24223. if (instance.rotationQuaternion) {
  24224. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24225. }
  24226. else if (instance.rotation) {
  24227. serializationInstance.rotation = instance.rotation.asArray();
  24228. }
  24229. serializationObject.instances.push(serializationInstance);
  24230. // Animations
  24231. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24232. serializationInstance.ranges = instance.serializeAnimationRanges();
  24233. }
  24234. //
  24235. // Animations
  24236. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24237. serializationObject.ranges = this.serializeAnimationRanges();
  24238. // Layer mask
  24239. serializationObject.layerMask = this.layerMask;
  24240. // Alpha
  24241. serializationObject.alphaIndex = this.alphaIndex;
  24242. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24243. // Overlay
  24244. serializationObject.overlayAlpha = this.overlayAlpha;
  24245. serializationObject.overlayColor = this.overlayColor.asArray();
  24246. serializationObject.renderOverlay = this.renderOverlay;
  24247. // Fog
  24248. serializationObject.applyFog = this.applyFog;
  24249. // Action Manager
  24250. if (this.actionManager) {
  24251. serializationObject.actions = this.actionManager.serialize(this.name);
  24252. }
  24253. };
  24254. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24255. if (!this.geometry) {
  24256. return;
  24257. }
  24258. this._markSubMeshesAsAttributesDirty();
  24259. var morphTargetManager = this._morphTargetManager;
  24260. if (morphTargetManager && morphTargetManager.vertexCount) {
  24261. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24262. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24263. this.morphTargetManager = null;
  24264. return;
  24265. }
  24266. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24267. var morphTarget = morphTargetManager.getActiveTarget(index);
  24268. var positions = morphTarget.getPositions();
  24269. if (!positions) {
  24270. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24271. return;
  24272. }
  24273. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24274. var normals = morphTarget.getNormals();
  24275. if (normals) {
  24276. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24277. }
  24278. var tangents = morphTarget.getTangents();
  24279. if (tangents) {
  24280. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24281. }
  24282. }
  24283. }
  24284. else {
  24285. var index = 0;
  24286. // Positions
  24287. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24288. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24289. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24290. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24291. }
  24292. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24293. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24294. }
  24295. index++;
  24296. }
  24297. }
  24298. };
  24299. // Statics
  24300. /**
  24301. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24302. * The parameter `parsedMesh` is the mesh to be copied.
  24303. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24304. */
  24305. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24306. var mesh;
  24307. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24308. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24309. }
  24310. else {
  24311. mesh = new Mesh(parsedMesh.name, scene);
  24312. }
  24313. mesh.id = parsedMesh.id;
  24314. if (BABYLON.Tags) {
  24315. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24316. }
  24317. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24318. if (parsedMesh.metadata !== undefined) {
  24319. mesh.metadata = parsedMesh.metadata;
  24320. }
  24321. if (parsedMesh.rotationQuaternion) {
  24322. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24323. }
  24324. else if (parsedMesh.rotation) {
  24325. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24326. }
  24327. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24328. if (parsedMesh.localMatrix) {
  24329. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24330. }
  24331. else if (parsedMesh.pivotMatrix) {
  24332. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24333. }
  24334. mesh.setEnabled(parsedMesh.isEnabled);
  24335. mesh.isVisible = parsedMesh.isVisible;
  24336. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24337. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24338. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24339. if (parsedMesh.applyFog !== undefined) {
  24340. mesh.applyFog = parsedMesh.applyFog;
  24341. }
  24342. if (parsedMesh.pickable !== undefined) {
  24343. mesh.isPickable = parsedMesh.pickable;
  24344. }
  24345. if (parsedMesh.alphaIndex !== undefined) {
  24346. mesh.alphaIndex = parsedMesh.alphaIndex;
  24347. }
  24348. mesh.receiveShadows = parsedMesh.receiveShadows;
  24349. mesh.billboardMode = parsedMesh.billboardMode;
  24350. if (parsedMesh.visibility !== undefined) {
  24351. mesh.visibility = parsedMesh.visibility;
  24352. }
  24353. mesh.checkCollisions = parsedMesh.checkCollisions;
  24354. if (parsedMesh.isBlocker !== undefined) {
  24355. mesh.isBlocker = parsedMesh.isBlocker;
  24356. }
  24357. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24358. // freezeWorldMatrix
  24359. if (parsedMesh.freezeWorldMatrix) {
  24360. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24361. }
  24362. // Parent
  24363. if (parsedMesh.parentId) {
  24364. mesh._waitingParentId = parsedMesh.parentId;
  24365. }
  24366. // Actions
  24367. if (parsedMesh.actions !== undefined) {
  24368. mesh._waitingActions = parsedMesh.actions;
  24369. }
  24370. // Overlay
  24371. if (parsedMesh.overlayAlpha !== undefined) {
  24372. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24373. }
  24374. if (parsedMesh.overlayColor !== undefined) {
  24375. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24376. }
  24377. if (parsedMesh.renderOverlay !== undefined) {
  24378. mesh.renderOverlay = parsedMesh.renderOverlay;
  24379. }
  24380. // Geometry
  24381. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24382. if (parsedMesh.delayLoadingFile) {
  24383. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24384. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24385. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24386. if (parsedMesh._binaryInfo) {
  24387. mesh._binaryInfo = parsedMesh._binaryInfo;
  24388. }
  24389. mesh._delayInfo = [];
  24390. if (parsedMesh.hasUVs) {
  24391. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24392. }
  24393. if (parsedMesh.hasUVs2) {
  24394. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24395. }
  24396. if (parsedMesh.hasUVs3) {
  24397. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24398. }
  24399. if (parsedMesh.hasUVs4) {
  24400. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24401. }
  24402. if (parsedMesh.hasUVs5) {
  24403. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24404. }
  24405. if (parsedMesh.hasUVs6) {
  24406. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24407. }
  24408. if (parsedMesh.hasColors) {
  24409. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24410. }
  24411. if (parsedMesh.hasMatricesIndices) {
  24412. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24413. }
  24414. if (parsedMesh.hasMatricesWeights) {
  24415. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24416. }
  24417. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24418. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24419. mesh._checkDelayState();
  24420. }
  24421. }
  24422. else {
  24423. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24424. }
  24425. // Material
  24426. if (parsedMesh.materialId) {
  24427. mesh.setMaterialByID(parsedMesh.materialId);
  24428. }
  24429. else {
  24430. mesh.material = null;
  24431. }
  24432. // Morph targets
  24433. if (parsedMesh.morphTargetManagerId > -1) {
  24434. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24435. }
  24436. // Skeleton
  24437. if (parsedMesh.skeletonId > -1) {
  24438. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24439. if (parsedMesh.numBoneInfluencers) {
  24440. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24441. }
  24442. }
  24443. // Animations
  24444. if (parsedMesh.animations) {
  24445. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24446. var parsedAnimation = parsedMesh.animations[animationIndex];
  24447. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24448. }
  24449. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24450. }
  24451. if (parsedMesh.autoAnimate) {
  24452. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24453. }
  24454. // Layer Mask
  24455. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24456. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24457. }
  24458. else {
  24459. mesh.layerMask = 0x0FFFFFFF;
  24460. }
  24461. // Physics
  24462. if (parsedMesh.physicsImpostor) {
  24463. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24464. mass: parsedMesh.physicsMass,
  24465. friction: parsedMesh.physicsFriction,
  24466. restitution: parsedMesh.physicsRestitution
  24467. }, scene);
  24468. }
  24469. // Instances
  24470. if (parsedMesh.instances) {
  24471. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24472. var parsedInstance = parsedMesh.instances[index];
  24473. var instance = mesh.createInstance(parsedInstance.name);
  24474. if (BABYLON.Tags) {
  24475. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24476. }
  24477. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24478. if (parsedInstance.parentId) {
  24479. instance._waitingParentId = parsedInstance.parentId;
  24480. }
  24481. if (parsedInstance.rotationQuaternion) {
  24482. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24483. }
  24484. else if (parsedInstance.rotation) {
  24485. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24486. }
  24487. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24488. instance.checkCollisions = mesh.checkCollisions;
  24489. if (parsedMesh.animations) {
  24490. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24491. parsedAnimation = parsedMesh.animations[animationIndex];
  24492. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24493. }
  24494. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24495. }
  24496. }
  24497. }
  24498. return mesh;
  24499. };
  24500. /**
  24501. * Creates a ribbon mesh.
  24502. * Please consider using the same method from the MeshBuilder class instead.
  24503. * 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.
  24504. *
  24505. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24506. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24507. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24508. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24509. * 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.
  24510. * 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.
  24511. * 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
  24512. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24513. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24514. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24515. */
  24516. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24517. if (closeArray === void 0) { closeArray = false; }
  24518. if (updatable === void 0) { updatable = false; }
  24519. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24520. pathArray: pathArray,
  24521. closeArray: closeArray,
  24522. closePath: closePath,
  24523. offset: offset,
  24524. updatable: updatable,
  24525. sideOrientation: sideOrientation,
  24526. instance: instance
  24527. }, scene);
  24528. };
  24529. /**
  24530. * Creates a plane polygonal mesh. By default, this is a disc.
  24531. * Please consider using the same method from the MeshBuilder class instead.
  24532. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24533. * 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.
  24534. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24535. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24537. */
  24538. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24539. if (scene === void 0) { scene = null; }
  24540. var options = {
  24541. radius: radius,
  24542. tessellation: tessellation,
  24543. sideOrientation: sideOrientation,
  24544. updatable: updatable
  24545. };
  24546. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24547. };
  24548. /**
  24549. * Creates a box mesh.
  24550. * Please consider using the same method from the MeshBuilder class instead.
  24551. * The parameter `size` sets the size (float) of each box side (default 1).
  24552. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24553. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24554. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24555. */
  24556. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24557. if (scene === void 0) { scene = null; }
  24558. var options = {
  24559. size: size,
  24560. sideOrientation: sideOrientation,
  24561. updatable: updatable
  24562. };
  24563. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24564. };
  24565. /**
  24566. * Creates a sphere mesh.
  24567. * Please consider using the same method from the MeshBuilder class instead.
  24568. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24569. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24570. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24571. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24572. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24573. */
  24574. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24575. var options = {
  24576. segments: segments,
  24577. diameterX: diameter,
  24578. diameterY: diameter,
  24579. diameterZ: diameter,
  24580. sideOrientation: sideOrientation,
  24581. updatable: updatable
  24582. };
  24583. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24584. };
  24585. /**
  24586. * Creates a cylinder or a cone mesh.
  24587. * Please consider using the same method from the MeshBuilder class instead.
  24588. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24589. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24590. * 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.
  24591. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24592. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24593. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24594. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24596. */
  24597. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24598. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24599. if (scene !== undefined) {
  24600. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24601. updatable = scene;
  24602. }
  24603. scene = subdivisions;
  24604. subdivisions = 1;
  24605. }
  24606. var options = {
  24607. height: height,
  24608. diameterTop: diameterTop,
  24609. diameterBottom: diameterBottom,
  24610. tessellation: tessellation,
  24611. subdivisions: subdivisions,
  24612. sideOrientation: sideOrientation,
  24613. updatable: updatable
  24614. };
  24615. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24616. };
  24617. // Torus (Code from SharpDX.org)
  24618. /**
  24619. * Creates a torus mesh.
  24620. * Please consider using the same method from the MeshBuilder class instead.
  24621. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24622. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24623. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24624. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24625. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24626. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24627. */
  24628. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24629. var options = {
  24630. diameter: diameter,
  24631. thickness: thickness,
  24632. tessellation: tessellation,
  24633. sideOrientation: sideOrientation,
  24634. updatable: updatable
  24635. };
  24636. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24637. };
  24638. /**
  24639. * Creates a torus knot mesh.
  24640. * Please consider using the same method from the MeshBuilder class instead.
  24641. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24642. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24643. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24644. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24645. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24646. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24648. */
  24649. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24650. var options = {
  24651. radius: radius,
  24652. tube: tube,
  24653. radialSegments: radialSegments,
  24654. tubularSegments: tubularSegments,
  24655. p: p,
  24656. q: q,
  24657. sideOrientation: sideOrientation,
  24658. updatable: updatable
  24659. };
  24660. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24661. };
  24662. /**
  24663. * Creates a line mesh.
  24664. * Please consider using the same method from the MeshBuilder class instead.
  24665. * 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.
  24666. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24667. * The parameter `points` is an array successive Vector3.
  24668. * 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
  24669. * When updating an instance, remember that only point positions can change, not the number of points.
  24670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24671. */
  24672. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24673. if (scene === void 0) { scene = null; }
  24674. if (updatable === void 0) { updatable = false; }
  24675. if (instance === void 0) { instance = null; }
  24676. var options = {
  24677. points: points,
  24678. updatable: updatable,
  24679. instance: instance
  24680. };
  24681. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24682. };
  24683. /**
  24684. * Creates a dashed line mesh.
  24685. * Please consider using the same method from the MeshBuilder class instead.
  24686. * 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.
  24687. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24688. * The parameter `points` is an array successive Vector3.
  24689. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24690. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24691. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24692. * 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
  24693. * When updating an instance, remember that only point positions can change, not the number of points.
  24694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24695. */
  24696. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24697. if (scene === void 0) { scene = null; }
  24698. var options = {
  24699. points: points,
  24700. dashSize: dashSize,
  24701. gapSize: gapSize,
  24702. dashNb: dashNb,
  24703. updatable: updatable,
  24704. instance: instance
  24705. };
  24706. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24707. };
  24708. /**
  24709. * Creates a polygon mesh.
  24710. * Please consider using the same method from the MeshBuilder class instead.
  24711. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24712. * 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.
  24713. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24714. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24715. * Remember you can only change the shape positions, not their number when updating a polygon.
  24716. */
  24717. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24718. var options = {
  24719. shape: shape,
  24720. holes: holes,
  24721. updatable: updatable,
  24722. sideOrientation: sideOrientation
  24723. };
  24724. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24725. };
  24726. /**
  24727. * Creates an extruded polygon mesh, with depth in the Y direction.
  24728. * Please consider using the same method from the MeshBuilder class instead.
  24729. */
  24730. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24731. var options = {
  24732. shape: shape,
  24733. holes: holes,
  24734. depth: depth,
  24735. updatable: updatable,
  24736. sideOrientation: sideOrientation
  24737. };
  24738. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24739. };
  24740. /**
  24741. * Creates an extruded shape mesh.
  24742. * 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.
  24743. * Please consider using the same method from the MeshBuilder class instead.
  24744. *
  24745. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24746. * 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
  24747. * extruded along the Z axis.
  24748. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24749. * 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.
  24750. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24751. * 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
  24752. * 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
  24753. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24755. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24757. */
  24758. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24759. if (scene === void 0) { scene = null; }
  24760. var options = {
  24761. shape: shape,
  24762. path: path,
  24763. scale: scale,
  24764. rotation: rotation,
  24765. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24766. sideOrientation: sideOrientation,
  24767. instance: instance,
  24768. updatable: updatable
  24769. };
  24770. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24771. };
  24772. /**
  24773. * Creates an custom extruded shape mesh.
  24774. * 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.
  24775. * Please consider using the same method from the MeshBuilder class instead.
  24776. *
  24777. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24778. * 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
  24779. * extruded along the Z axis.
  24780. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24781. * 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
  24782. * and the distance of this point from the begining of the path :
  24783. * ```javascript
  24784. * var rotationFunction = function(i, distance) {
  24785. * // do things
  24786. * return rotationValue; }
  24787. * ```
  24788. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24789. * 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
  24790. * and the distance of this point from the begining of the path :
  24791. * ```javascript
  24792. * var scaleFunction = function(i, distance) {
  24793. * // do things
  24794. * return scaleValue;}
  24795. * ```
  24796. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24797. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24798. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24799. * 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
  24800. * 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
  24801. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24802. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24803. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24804. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24805. */
  24806. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24807. var options = {
  24808. shape: shape,
  24809. path: path,
  24810. scaleFunction: scaleFunction,
  24811. rotationFunction: rotationFunction,
  24812. ribbonCloseArray: ribbonCloseArray,
  24813. ribbonClosePath: ribbonClosePath,
  24814. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24815. sideOrientation: sideOrientation,
  24816. instance: instance,
  24817. updatable: updatable
  24818. };
  24819. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24820. };
  24821. /**
  24822. * Creates lathe mesh.
  24823. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24824. * Please consider using the same method from the MeshBuilder class instead.
  24825. * 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
  24826. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24827. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24828. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24829. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24830. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24831. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24832. */
  24833. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24834. var options = {
  24835. shape: shape,
  24836. radius: radius,
  24837. tessellation: tessellation,
  24838. sideOrientation: sideOrientation,
  24839. updatable: updatable
  24840. };
  24841. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24842. };
  24843. /**
  24844. * Creates a plane mesh.
  24845. * Please consider using the same method from the MeshBuilder class instead.
  24846. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24847. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24848. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24850. */
  24851. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24852. var options = {
  24853. size: size,
  24854. width: size,
  24855. height: size,
  24856. sideOrientation: sideOrientation,
  24857. updatable: updatable
  24858. };
  24859. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24860. };
  24861. /**
  24862. * Creates a ground mesh.
  24863. * Please consider using the same method from the MeshBuilder class instead.
  24864. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24865. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24867. */
  24868. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24869. var options = {
  24870. width: width,
  24871. height: height,
  24872. subdivisions: subdivisions,
  24873. updatable: updatable
  24874. };
  24875. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24876. };
  24877. /**
  24878. * Creates a tiled ground mesh.
  24879. * Please consider using the same method from the MeshBuilder class instead.
  24880. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24881. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24882. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24883. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24884. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24885. * numbers of subdivisions on the ground width and height of each tile.
  24886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24887. */
  24888. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24889. var options = {
  24890. xmin: xmin,
  24891. zmin: zmin,
  24892. xmax: xmax,
  24893. zmax: zmax,
  24894. subdivisions: subdivisions,
  24895. precision: precision,
  24896. updatable: updatable
  24897. };
  24898. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24899. };
  24900. /**
  24901. * Creates a ground mesh from a height map.
  24902. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24903. * Please consider using the same method from the MeshBuilder class instead.
  24904. * The parameter `url` sets the URL of the height map image resource.
  24905. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24906. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24907. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24908. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24909. * 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).
  24910. * This function is passed the newly built mesh :
  24911. * ```javascript
  24912. * function(mesh) { // do things
  24913. * return; }
  24914. * ```
  24915. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24916. */
  24917. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24918. var options = {
  24919. width: width,
  24920. height: height,
  24921. subdivisions: subdivisions,
  24922. minHeight: minHeight,
  24923. maxHeight: maxHeight,
  24924. updatable: updatable,
  24925. onReady: onReady
  24926. };
  24927. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24928. };
  24929. /**
  24930. * Creates a tube mesh.
  24931. * 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.
  24932. * Please consider using the same method from the MeshBuilder class instead.
  24933. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24934. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24935. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24936. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24937. * 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.
  24938. * It must return a radius value (positive float) :
  24939. * ```javascript
  24940. * var radiusFunction = function(i, distance) {
  24941. * // do things
  24942. * return radius; }
  24943. * ```
  24944. * 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
  24945. * 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
  24946. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24947. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24949. */
  24950. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24951. var options = {
  24952. path: path,
  24953. radius: radius,
  24954. tessellation: tessellation,
  24955. radiusFunction: radiusFunction,
  24956. arc: 1,
  24957. cap: cap,
  24958. updatable: updatable,
  24959. sideOrientation: sideOrientation,
  24960. instance: instance
  24961. };
  24962. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24963. };
  24964. /**
  24965. * Creates a polyhedron mesh.
  24966. * Please consider using the same method from the MeshBuilder class instead.
  24967. * 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
  24968. * to choose the wanted type.
  24969. * The parameter `size` (positive float, default 1) sets the polygon size.
  24970. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24971. * 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`.
  24972. * 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
  24973. * 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)`).
  24974. * 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
  24975. * 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.
  24976. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24977. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24979. */
  24980. Mesh.CreatePolyhedron = function (name, options, scene) {
  24981. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24982. };
  24983. /**
  24984. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24985. * Please consider using the same method from the MeshBuilder class instead.
  24986. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24987. * 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`).
  24988. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24989. * 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.
  24990. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24991. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24993. */
  24994. Mesh.CreateIcoSphere = function (name, options, scene) {
  24995. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24996. };
  24997. /**
  24998. * Creates a decal mesh.
  24999. * Please consider using the same method from the MeshBuilder class instead.
  25000. * 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.
  25001. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25002. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25003. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25004. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25005. */
  25006. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25007. var options = {
  25008. position: position,
  25009. normal: normal,
  25010. size: size,
  25011. angle: angle
  25012. };
  25013. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25014. };
  25015. // Skeletons
  25016. /**
  25017. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25018. */
  25019. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25020. if (!this._sourcePositions) {
  25021. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25022. if (!source) {
  25023. return this._sourcePositions;
  25024. }
  25025. this._sourcePositions = new Float32Array(source);
  25026. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25027. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25028. }
  25029. }
  25030. return this._sourcePositions;
  25031. };
  25032. /**
  25033. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25034. */
  25035. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25036. if (!this._sourceNormals) {
  25037. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25038. if (!source) {
  25039. return this._sourceNormals;
  25040. }
  25041. this._sourceNormals = new Float32Array(source);
  25042. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25043. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25044. }
  25045. }
  25046. return this._sourceNormals;
  25047. };
  25048. /**
  25049. * Updates the vertex buffer by applying transformation from the bones.
  25050. * Returns the Mesh.
  25051. *
  25052. * @param {skeleton} skeleton to apply
  25053. */
  25054. Mesh.prototype.applySkeleton = function (skeleton) {
  25055. if (!this.geometry) {
  25056. return this;
  25057. }
  25058. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25059. return this;
  25060. }
  25061. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25062. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25063. return this;
  25064. }
  25065. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25066. return this;
  25067. }
  25068. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25069. return this;
  25070. }
  25071. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25072. return this;
  25073. }
  25074. if (!this._sourcePositions) {
  25075. var submeshes = this.subMeshes.slice();
  25076. this.setPositionsForCPUSkinning();
  25077. this.subMeshes = submeshes;
  25078. }
  25079. if (!this._sourceNormals) {
  25080. this.setNormalsForCPUSkinning();
  25081. }
  25082. // positionsData checks for not being Float32Array will only pass at most once
  25083. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25084. if (!positionsData) {
  25085. return this;
  25086. }
  25087. if (!(positionsData instanceof Float32Array)) {
  25088. positionsData = new Float32Array(positionsData);
  25089. }
  25090. // normalsData checks for not being Float32Array will only pass at most once
  25091. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25092. if (!normalsData) {
  25093. return this;
  25094. }
  25095. if (!(normalsData instanceof Float32Array)) {
  25096. normalsData = new Float32Array(normalsData);
  25097. }
  25098. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25099. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25100. if (!matricesWeightsData || !matricesIndicesData) {
  25101. return this;
  25102. }
  25103. var needExtras = this.numBoneInfluencers > 4;
  25104. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25105. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25106. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  25107. return this;
  25108. }
  25109. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25110. var tempVector3 = BABYLON.Vector3.Zero();
  25111. var finalMatrix = new BABYLON.Matrix();
  25112. var tempMatrix = new BABYLON.Matrix();
  25113. var matWeightIdx = 0;
  25114. var inf;
  25115. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25116. var weight;
  25117. for (inf = 0; inf < 4; inf++) {
  25118. weight = matricesWeightsData[matWeightIdx + inf];
  25119. if (weight > 0) {
  25120. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25121. finalMatrix.addToSelf(tempMatrix);
  25122. }
  25123. else
  25124. break;
  25125. }
  25126. if (needExtras) {
  25127. for (inf = 0; inf < 4; inf++) {
  25128. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25129. if (weight > 0) {
  25130. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25131. finalMatrix.addToSelf(tempMatrix);
  25132. }
  25133. else
  25134. break;
  25135. }
  25136. }
  25137. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25138. tempVector3.toArray(positionsData, index);
  25139. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25140. tempVector3.toArray(normalsData, index);
  25141. finalMatrix.reset();
  25142. }
  25143. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25144. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25145. return this;
  25146. };
  25147. // Tools
  25148. /**
  25149. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25150. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25151. */
  25152. Mesh.MinMax = function (meshes) {
  25153. var minVector = null;
  25154. var maxVector = null;
  25155. meshes.forEach(function (mesh, index, array) {
  25156. var boundingInfo = mesh.getBoundingInfo();
  25157. if (!boundingInfo) {
  25158. return;
  25159. }
  25160. var boundingBox = boundingInfo.boundingBox;
  25161. if (!minVector || !maxVector) {
  25162. minVector = boundingBox.minimumWorld;
  25163. maxVector = boundingBox.maximumWorld;
  25164. }
  25165. else {
  25166. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25167. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25168. }
  25169. });
  25170. if (!minVector || !maxVector) {
  25171. return {
  25172. min: BABYLON.Vector3.Zero(),
  25173. max: BABYLON.Vector3.Zero()
  25174. };
  25175. }
  25176. return {
  25177. min: minVector,
  25178. max: maxVector
  25179. };
  25180. };
  25181. /**
  25182. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25183. */
  25184. Mesh.Center = function (meshesOrMinMaxVector) {
  25185. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25186. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25187. };
  25188. /**
  25189. * Merge the array of meshes into a single mesh for performance reasons.
  25190. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25191. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25192. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25193. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25194. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25195. */
  25196. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25197. if (disposeSource === void 0) { disposeSource = true; }
  25198. var index;
  25199. if (!allow32BitsIndices) {
  25200. var totalVertices = 0;
  25201. // Counting vertices
  25202. for (index = 0; index < meshes.length; index++) {
  25203. if (meshes[index]) {
  25204. totalVertices += meshes[index].getTotalVertices();
  25205. if (totalVertices > 65536) {
  25206. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25207. return null;
  25208. }
  25209. }
  25210. }
  25211. }
  25212. // Merge
  25213. var vertexData = null;
  25214. var otherVertexData;
  25215. var indiceArray = new Array();
  25216. var source = null;
  25217. for (index = 0; index < meshes.length; index++) {
  25218. if (meshes[index]) {
  25219. meshes[index].computeWorldMatrix(true);
  25220. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25221. otherVertexData.transform(meshes[index].getWorldMatrix());
  25222. if (vertexData) {
  25223. vertexData.merge(otherVertexData);
  25224. }
  25225. else {
  25226. vertexData = otherVertexData;
  25227. source = meshes[index];
  25228. }
  25229. if (subdivideWithSubMeshes) {
  25230. indiceArray.push(meshes[index].getTotalIndices());
  25231. }
  25232. }
  25233. }
  25234. source = source;
  25235. if (!meshSubclass) {
  25236. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25237. }
  25238. vertexData.applyToMesh(meshSubclass);
  25239. // Setting properties
  25240. meshSubclass.material = source.material;
  25241. meshSubclass.checkCollisions = source.checkCollisions;
  25242. // Cleaning
  25243. if (disposeSource) {
  25244. for (index = 0; index < meshes.length; index++) {
  25245. if (meshes[index]) {
  25246. meshes[index].dispose();
  25247. }
  25248. }
  25249. }
  25250. // Subdivide
  25251. if (subdivideWithSubMeshes) {
  25252. //-- Suppresions du submesh global
  25253. meshSubclass.releaseSubMeshes();
  25254. index = 0;
  25255. var offset = 0;
  25256. //-- aplique la subdivision en fonction du tableau d'indices
  25257. while (index < indiceArray.length) {
  25258. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25259. offset += indiceArray[index];
  25260. index++;
  25261. }
  25262. }
  25263. return meshSubclass;
  25264. };
  25265. // Consts
  25266. Mesh._FRONTSIDE = 0;
  25267. Mesh._BACKSIDE = 1;
  25268. Mesh._DOUBLESIDE = 2;
  25269. Mesh._DEFAULTSIDE = 0;
  25270. Mesh._NO_CAP = 0;
  25271. Mesh._CAP_START = 1;
  25272. Mesh._CAP_END = 2;
  25273. Mesh._CAP_ALL = 3;
  25274. return Mesh;
  25275. }(BABYLON.AbstractMesh));
  25276. BABYLON.Mesh = Mesh;
  25277. })(BABYLON || (BABYLON = {}));
  25278. //# sourceMappingURL=babylon.mesh.js.map
  25279. var BABYLON;
  25280. (function (BABYLON) {
  25281. var BaseSubMesh = /** @class */ (function () {
  25282. function BaseSubMesh() {
  25283. }
  25284. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25285. get: function () {
  25286. return this._materialEffect;
  25287. },
  25288. enumerable: true,
  25289. configurable: true
  25290. });
  25291. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25292. if (defines === void 0) { defines = null; }
  25293. if (this._materialEffect === effect) {
  25294. if (!effect) {
  25295. this._materialDefines = null;
  25296. }
  25297. return;
  25298. }
  25299. this._materialDefines = defines;
  25300. this._materialEffect = effect;
  25301. };
  25302. return BaseSubMesh;
  25303. }());
  25304. BABYLON.BaseSubMesh = BaseSubMesh;
  25305. var SubMesh = /** @class */ (function (_super) {
  25306. __extends(SubMesh, _super);
  25307. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25308. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25309. var _this = _super.call(this) || this;
  25310. _this.materialIndex = materialIndex;
  25311. _this.verticesStart = verticesStart;
  25312. _this.verticesCount = verticesCount;
  25313. _this.indexStart = indexStart;
  25314. _this.indexCount = indexCount;
  25315. _this._renderId = 0;
  25316. _this._mesh = mesh;
  25317. _this._renderingMesh = renderingMesh || mesh;
  25318. mesh.subMeshes.push(_this);
  25319. _this._trianglePlanes = [];
  25320. _this._id = mesh.subMeshes.length - 1;
  25321. if (createBoundingBox) {
  25322. _this.refreshBoundingInfo();
  25323. mesh.computeWorldMatrix(true);
  25324. }
  25325. return _this;
  25326. }
  25327. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25328. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25329. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25330. };
  25331. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25332. get: function () {
  25333. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25334. },
  25335. enumerable: true,
  25336. configurable: true
  25337. });
  25338. /**
  25339. * Returns the submesh BoudingInfo object.
  25340. */
  25341. SubMesh.prototype.getBoundingInfo = function () {
  25342. if (this.IsGlobal) {
  25343. return this._mesh.getBoundingInfo();
  25344. }
  25345. return this._boundingInfo;
  25346. };
  25347. /**
  25348. * Sets the submesh BoundingInfo.
  25349. * Return the SubMesh.
  25350. */
  25351. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25352. this._boundingInfo = boundingInfo;
  25353. return this;
  25354. };
  25355. /**
  25356. * Returns the mesh of the current submesh.
  25357. */
  25358. SubMesh.prototype.getMesh = function () {
  25359. return this._mesh;
  25360. };
  25361. /**
  25362. * Returns the rendering mesh of the submesh.
  25363. */
  25364. SubMesh.prototype.getRenderingMesh = function () {
  25365. return this._renderingMesh;
  25366. };
  25367. /**
  25368. * Returns the submesh material.
  25369. */
  25370. SubMesh.prototype.getMaterial = function () {
  25371. var rootMaterial = this._renderingMesh.material;
  25372. if (rootMaterial && rootMaterial.getSubMaterial) {
  25373. var multiMaterial = rootMaterial;
  25374. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25375. if (this._currentMaterial !== effectiveMaterial) {
  25376. this._currentMaterial = effectiveMaterial;
  25377. this._materialDefines = null;
  25378. }
  25379. return effectiveMaterial;
  25380. }
  25381. if (!rootMaterial) {
  25382. return this._mesh.getScene().defaultMaterial;
  25383. }
  25384. return rootMaterial;
  25385. };
  25386. // Methods
  25387. /**
  25388. * Sets a new updated BoundingInfo object to the submesh.
  25389. * Returns the SubMesh.
  25390. */
  25391. SubMesh.prototype.refreshBoundingInfo = function () {
  25392. this._lastColliderWorldVertices = null;
  25393. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25394. return this;
  25395. }
  25396. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25397. if (!data) {
  25398. this._boundingInfo = this._mesh._boundingInfo;
  25399. return this;
  25400. }
  25401. var indices = this._renderingMesh.getIndices();
  25402. var extend;
  25403. //is this the only submesh?
  25404. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25405. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25406. if (!boundingInfo) {
  25407. return this;
  25408. }
  25409. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25410. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25411. }
  25412. else {
  25413. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25414. }
  25415. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25416. return this;
  25417. };
  25418. SubMesh.prototype._checkCollision = function (collider) {
  25419. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25420. if (!boundingInfo) {
  25421. return false;
  25422. }
  25423. return boundingInfo._checkCollision(collider);
  25424. };
  25425. /**
  25426. * Updates the submesh BoundingInfo.
  25427. * Returns the Submesh.
  25428. */
  25429. SubMesh.prototype.updateBoundingInfo = function (world) {
  25430. var boundingInfo = this.getBoundingInfo();
  25431. if (!boundingInfo) {
  25432. this.refreshBoundingInfo();
  25433. }
  25434. boundingInfo.update(world);
  25435. return this;
  25436. };
  25437. /**
  25438. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25439. * Boolean returned.
  25440. */
  25441. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25442. var boundingInfo = this.getBoundingInfo();
  25443. if (!boundingInfo) {
  25444. return false;
  25445. }
  25446. return boundingInfo.isInFrustum(frustumPlanes);
  25447. };
  25448. /**
  25449. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25450. * Boolean returned.
  25451. */
  25452. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25453. var boundingInfo = this.getBoundingInfo();
  25454. if (!boundingInfo) {
  25455. return false;
  25456. }
  25457. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25458. };
  25459. /**
  25460. * Renders the submesh.
  25461. * Returns it.
  25462. */
  25463. SubMesh.prototype.render = function (enableAlphaMode) {
  25464. this._renderingMesh.render(this, enableAlphaMode);
  25465. return this;
  25466. };
  25467. /**
  25468. * Returns a new Index Buffer.
  25469. * Type returned : WebGLBuffer.
  25470. */
  25471. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25472. if (!this._linesIndexBuffer) {
  25473. var linesIndices = [];
  25474. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25475. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25476. }
  25477. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25478. this.linesIndexCount = linesIndices.length;
  25479. }
  25480. return this._linesIndexBuffer;
  25481. };
  25482. /**
  25483. * True is the passed Ray intersects the submesh bounding box.
  25484. * Boolean returned.
  25485. */
  25486. SubMesh.prototype.canIntersects = function (ray) {
  25487. var boundingInfo = this.getBoundingInfo();
  25488. if (!boundingInfo) {
  25489. return false;
  25490. }
  25491. return ray.intersectsBox(boundingInfo.boundingBox);
  25492. };
  25493. /**
  25494. * Returns an object IntersectionInfo.
  25495. */
  25496. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25497. var intersectInfo = null;
  25498. // LineMesh first as it's also a Mesh...
  25499. if (this._mesh instanceof BABYLON.LinesMesh) {
  25500. var lineMesh = this._mesh;
  25501. // Line test
  25502. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25503. var p0 = positions[indices[index]];
  25504. var p1 = positions[indices[index + 1]];
  25505. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25506. if (length < 0) {
  25507. continue;
  25508. }
  25509. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25510. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25511. if (fastCheck) {
  25512. break;
  25513. }
  25514. }
  25515. }
  25516. }
  25517. else {
  25518. // Triangles test
  25519. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25520. var p0 = positions[indices[index]];
  25521. var p1 = positions[indices[index + 1]];
  25522. var p2 = positions[indices[index + 2]];
  25523. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25524. if (currentIntersectInfo) {
  25525. if (currentIntersectInfo.distance < 0) {
  25526. continue;
  25527. }
  25528. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25529. intersectInfo = currentIntersectInfo;
  25530. intersectInfo.faceId = index / 3;
  25531. if (fastCheck) {
  25532. break;
  25533. }
  25534. }
  25535. }
  25536. }
  25537. }
  25538. return intersectInfo;
  25539. };
  25540. SubMesh.prototype._rebuild = function () {
  25541. if (this._linesIndexBuffer) {
  25542. this._linesIndexBuffer = null;
  25543. }
  25544. };
  25545. // Clone
  25546. /**
  25547. * Creates a new Submesh from the passed Mesh.
  25548. */
  25549. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25550. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25551. if (!this.IsGlobal) {
  25552. var boundingInfo = this.getBoundingInfo();
  25553. if (!boundingInfo) {
  25554. return result;
  25555. }
  25556. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  25557. }
  25558. return result;
  25559. };
  25560. // Dispose
  25561. /**
  25562. * Disposes the Submesh.
  25563. * Returns nothing.
  25564. */
  25565. SubMesh.prototype.dispose = function () {
  25566. if (this._linesIndexBuffer) {
  25567. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25568. this._linesIndexBuffer = null;
  25569. }
  25570. // Remove from mesh
  25571. var index = this._mesh.subMeshes.indexOf(this);
  25572. this._mesh.subMeshes.splice(index, 1);
  25573. };
  25574. // Statics
  25575. /**
  25576. * Creates a new Submesh from the passed parameters :
  25577. * - materialIndex (integer) : the index of the main mesh material.
  25578. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25579. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25580. * - mesh (Mesh) : the main mesh to create the submesh from.
  25581. * - renderingMesh (optional Mesh) : rendering mesh.
  25582. */
  25583. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25584. var minVertexIndex = Number.MAX_VALUE;
  25585. var maxVertexIndex = -Number.MAX_VALUE;
  25586. renderingMesh = (renderingMesh || mesh);
  25587. var indices = renderingMesh.getIndices();
  25588. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25589. var vertexIndex = indices[index];
  25590. if (vertexIndex < minVertexIndex)
  25591. minVertexIndex = vertexIndex;
  25592. if (vertexIndex > maxVertexIndex)
  25593. maxVertexIndex = vertexIndex;
  25594. }
  25595. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25596. };
  25597. return SubMesh;
  25598. }(BaseSubMesh));
  25599. BABYLON.SubMesh = SubMesh;
  25600. })(BABYLON || (BABYLON = {}));
  25601. //# sourceMappingURL=babylon.subMesh.js.map
  25602. var BABYLON;
  25603. (function (BABYLON) {
  25604. var EffectFallbacks = /** @class */ (function () {
  25605. function EffectFallbacks() {
  25606. this._defines = {};
  25607. this._currentRank = 32;
  25608. this._maxRank = -1;
  25609. }
  25610. EffectFallbacks.prototype.unBindMesh = function () {
  25611. this._mesh = null;
  25612. };
  25613. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25614. if (!this._defines[rank]) {
  25615. if (rank < this._currentRank) {
  25616. this._currentRank = rank;
  25617. }
  25618. if (rank > this._maxRank) {
  25619. this._maxRank = rank;
  25620. }
  25621. this._defines[rank] = new Array();
  25622. }
  25623. this._defines[rank].push(define);
  25624. };
  25625. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25626. this._meshRank = rank;
  25627. this._mesh = mesh;
  25628. if (rank < this._currentRank) {
  25629. this._currentRank = rank;
  25630. }
  25631. if (rank > this._maxRank) {
  25632. this._maxRank = rank;
  25633. }
  25634. };
  25635. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25636. get: function () {
  25637. return this._currentRank <= this._maxRank;
  25638. },
  25639. enumerable: true,
  25640. configurable: true
  25641. });
  25642. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25643. // First we try to switch to CPU skinning
  25644. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25645. this._mesh.computeBonesUsingShaders = false;
  25646. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25647. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25648. var scene = this._mesh.getScene();
  25649. for (var index = 0; index < scene.meshes.length; index++) {
  25650. var otherMesh = scene.meshes[index];
  25651. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25652. otherMesh.computeBonesUsingShaders = false;
  25653. }
  25654. }
  25655. }
  25656. else {
  25657. var currentFallbacks = this._defines[this._currentRank];
  25658. if (currentFallbacks) {
  25659. for (var index = 0; index < currentFallbacks.length; index++) {
  25660. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25661. }
  25662. }
  25663. this._currentRank++;
  25664. }
  25665. return currentDefines;
  25666. };
  25667. return EffectFallbacks;
  25668. }());
  25669. BABYLON.EffectFallbacks = EffectFallbacks;
  25670. var EffectCreationOptions = /** @class */ (function () {
  25671. function EffectCreationOptions() {
  25672. }
  25673. return EffectCreationOptions;
  25674. }());
  25675. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25676. var Effect = /** @class */ (function () {
  25677. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25678. if (samplers === void 0) { samplers = null; }
  25679. if (defines === void 0) { defines = null; }
  25680. if (fallbacks === void 0) { fallbacks = null; }
  25681. if (onCompiled === void 0) { onCompiled = null; }
  25682. if (onError === void 0) { onError = null; }
  25683. var _this = this;
  25684. this.uniqueId = 0;
  25685. this.onCompileObservable = new BABYLON.Observable();
  25686. this.onErrorObservable = new BABYLON.Observable();
  25687. this.onBindObservable = new BABYLON.Observable();
  25688. this._uniformBuffersNames = {};
  25689. this._isReady = false;
  25690. this._compilationError = "";
  25691. this.name = baseName;
  25692. if (attributesNamesOrOptions.attributes) {
  25693. var options = attributesNamesOrOptions;
  25694. this._engine = uniformsNamesOrEngine;
  25695. this._attributesNames = options.attributes;
  25696. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25697. this._samplers = options.samplers;
  25698. this.defines = options.defines;
  25699. this.onError = options.onError;
  25700. this.onCompiled = options.onCompiled;
  25701. this._fallbacks = options.fallbacks;
  25702. this._indexParameters = options.indexParameters;
  25703. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  25704. if (options.uniformBuffersNames) {
  25705. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25706. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25707. }
  25708. }
  25709. }
  25710. else {
  25711. this._engine = engine;
  25712. this.defines = defines;
  25713. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25714. this._samplers = samplers;
  25715. this._attributesNames = attributesNamesOrOptions;
  25716. this.onError = onError;
  25717. this.onCompiled = onCompiled;
  25718. this._indexParameters = indexParameters;
  25719. this._fallbacks = fallbacks;
  25720. }
  25721. this.uniqueId = Effect._uniqueIdSeed++;
  25722. var vertexSource;
  25723. var fragmentSource;
  25724. if (baseName.vertexElement) {
  25725. vertexSource = document.getElementById(baseName.vertexElement);
  25726. if (!vertexSource) {
  25727. vertexSource = baseName.vertexElement;
  25728. }
  25729. }
  25730. else {
  25731. vertexSource = baseName.vertex || baseName;
  25732. }
  25733. if (baseName.fragmentElement) {
  25734. fragmentSource = document.getElementById(baseName.fragmentElement);
  25735. if (!fragmentSource) {
  25736. fragmentSource = baseName.fragmentElement;
  25737. }
  25738. }
  25739. else {
  25740. fragmentSource = baseName.fragment || baseName;
  25741. }
  25742. this._loadVertexShader(vertexSource, function (vertexCode) {
  25743. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25744. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25745. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25746. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25747. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25748. if (baseName) {
  25749. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25750. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25751. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25752. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25753. }
  25754. else {
  25755. _this._vertexSourceCode = migratedVertexCode;
  25756. _this._fragmentSourceCode = migratedFragmentCode;
  25757. }
  25758. _this._prepareEffect();
  25759. });
  25760. });
  25761. });
  25762. });
  25763. });
  25764. });
  25765. }
  25766. Object.defineProperty(Effect.prototype, "key", {
  25767. get: function () {
  25768. return this._key;
  25769. },
  25770. enumerable: true,
  25771. configurable: true
  25772. });
  25773. // Properties
  25774. Effect.prototype.isReady = function () {
  25775. return this._isReady;
  25776. };
  25777. Effect.prototype.getEngine = function () {
  25778. return this._engine;
  25779. };
  25780. Effect.prototype.getProgram = function () {
  25781. return this._program;
  25782. };
  25783. Effect.prototype.getAttributesNames = function () {
  25784. return this._attributesNames;
  25785. };
  25786. Effect.prototype.getAttributeLocation = function (index) {
  25787. return this._attributes[index];
  25788. };
  25789. Effect.prototype.getAttributeLocationByName = function (name) {
  25790. var index = this._attributesNames.indexOf(name);
  25791. return this._attributes[index];
  25792. };
  25793. Effect.prototype.getAttributesCount = function () {
  25794. return this._attributes.length;
  25795. };
  25796. Effect.prototype.getUniformIndex = function (uniformName) {
  25797. return this._uniformsNames.indexOf(uniformName);
  25798. };
  25799. Effect.prototype.getUniform = function (uniformName) {
  25800. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25801. };
  25802. Effect.prototype.getSamplers = function () {
  25803. return this._samplers;
  25804. };
  25805. Effect.prototype.getCompilationError = function () {
  25806. return this._compilationError;
  25807. };
  25808. // Methods
  25809. Effect.prototype.executeWhenCompiled = function (func) {
  25810. if (this.isReady()) {
  25811. func(this);
  25812. return;
  25813. }
  25814. this.onCompileObservable.add(function (effect) {
  25815. func(effect);
  25816. });
  25817. };
  25818. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25819. if (BABYLON.Tools.IsWindowObjectExist()) {
  25820. // DOM element ?
  25821. if (vertex instanceof HTMLElement) {
  25822. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25823. callback(vertexCode);
  25824. return;
  25825. }
  25826. }
  25827. // Base64 encoded ?
  25828. if (vertex.substr(0, 7) === "base64:") {
  25829. var vertexBinary = window.atob(vertex.substr(7));
  25830. callback(vertexBinary);
  25831. return;
  25832. }
  25833. // Is in local store ?
  25834. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25835. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25836. return;
  25837. }
  25838. var vertexShaderUrl;
  25839. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25840. vertexShaderUrl = vertex;
  25841. }
  25842. else {
  25843. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25844. }
  25845. // Vertex shader
  25846. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25847. };
  25848. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25849. if (BABYLON.Tools.IsWindowObjectExist()) {
  25850. // DOM element ?
  25851. if (fragment instanceof HTMLElement) {
  25852. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25853. callback(fragmentCode);
  25854. return;
  25855. }
  25856. }
  25857. // Base64 encoded ?
  25858. if (fragment.substr(0, 7) === "base64:") {
  25859. var fragmentBinary = window.atob(fragment.substr(7));
  25860. callback(fragmentBinary);
  25861. return;
  25862. }
  25863. // Is in local store ?
  25864. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25865. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25866. return;
  25867. }
  25868. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25869. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25870. return;
  25871. }
  25872. var fragmentShaderUrl;
  25873. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25874. fragmentShaderUrl = fragment;
  25875. }
  25876. else {
  25877. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25878. }
  25879. // Fragment shader
  25880. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25881. };
  25882. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  25883. // Rebuild shaders source code
  25884. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  25885. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  25886. vertexCode = prefix + vertexCode;
  25887. fragmentCode = prefix + fragmentCode;
  25888. // Number lines of shaders source code
  25889. var i = 2;
  25890. var regex = /\n/gm;
  25891. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25892. i = 2;
  25893. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25894. // Dump shaders name and formatted source code
  25895. if (this.name.vertexElement) {
  25896. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  25897. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  25898. }
  25899. else if (this.name.vertex) {
  25900. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  25901. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  25902. }
  25903. else {
  25904. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  25905. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  25906. }
  25907. };
  25908. ;
  25909. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25910. var preparedSourceCode = this._processPrecision(sourceCode);
  25911. if (this._engine.webGLVersion == 1) {
  25912. callback(preparedSourceCode);
  25913. return;
  25914. }
  25915. // Already converted
  25916. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25917. callback(preparedSourceCode.replace("#version 300 es", ""));
  25918. return;
  25919. }
  25920. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  25921. // Remove extensions
  25922. // #extension GL_OES_standard_derivatives : enable
  25923. // #extension GL_EXT_shader_texture_lod : enable
  25924. // #extension GL_EXT_frag_depth : enable
  25925. // #extension GL_EXT_draw_buffers : require
  25926. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  25927. var result = preparedSourceCode.replace(regex, "");
  25928. // Migrate to GLSL v300
  25929. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  25930. result = result.replace(/attribute[ \t]/g, "in ");
  25931. result = result.replace(/[ \t]attribute/g, " in");
  25932. if (isFragment) {
  25933. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  25934. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  25935. result = result.replace(/texture2D\s*\(/g, "texture(");
  25936. result = result.replace(/textureCube\s*\(/g, "texture(");
  25937. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25938. result = result.replace(/gl_FragColor/g, "glFragColor");
  25939. result = result.replace(/gl_FragData/g, "glFragData");
  25940. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  25941. }
  25942. callback(result);
  25943. };
  25944. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25945. var _this = this;
  25946. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25947. var match = regex.exec(sourceCode);
  25948. var returnValue = new String(sourceCode);
  25949. while (match != null) {
  25950. var includeFile = match[1];
  25951. // Uniform declaration
  25952. if (includeFile.indexOf("__decl__") !== -1) {
  25953. includeFile = includeFile.replace(/__decl__/, "");
  25954. if (this._engine.supportsUniformBuffers) {
  25955. includeFile = includeFile.replace(/Vertex/, "Ubo");
  25956. includeFile = includeFile.replace(/Fragment/, "Ubo");
  25957. }
  25958. includeFile = includeFile + "Declaration";
  25959. }
  25960. if (Effect.IncludesShadersStore[includeFile]) {
  25961. // Substitution
  25962. var includeContent = Effect.IncludesShadersStore[includeFile];
  25963. if (match[2]) {
  25964. var splits = match[3].split(",");
  25965. for (var index = 0; index < splits.length; index += 2) {
  25966. var source = new RegExp(splits[index], "g");
  25967. var dest = splits[index + 1];
  25968. includeContent = includeContent.replace(source, dest);
  25969. }
  25970. }
  25971. if (match[4]) {
  25972. var indexString = match[5];
  25973. if (indexString.indexOf("..") !== -1) {
  25974. var indexSplits = indexString.split("..");
  25975. var minIndex = parseInt(indexSplits[0]);
  25976. var maxIndex = parseInt(indexSplits[1]);
  25977. var sourceIncludeContent = includeContent.slice(0);
  25978. includeContent = "";
  25979. if (isNaN(maxIndex)) {
  25980. maxIndex = this._indexParameters[indexSplits[1]];
  25981. }
  25982. for (var i = minIndex; i < maxIndex; i++) {
  25983. if (!this._engine.supportsUniformBuffers) {
  25984. // Ubo replacement
  25985. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25986. return p1 + "{X}";
  25987. });
  25988. }
  25989. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  25990. }
  25991. }
  25992. else {
  25993. if (!this._engine.supportsUniformBuffers) {
  25994. // Ubo replacement
  25995. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25996. return p1 + "{X}";
  25997. });
  25998. }
  25999. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26000. }
  26001. }
  26002. // Replace
  26003. returnValue = returnValue.replace(match[0], includeContent);
  26004. }
  26005. else {
  26006. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26007. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26008. Effect.IncludesShadersStore[includeFile] = fileContent;
  26009. _this._processIncludes(returnValue, callback);
  26010. });
  26011. return;
  26012. }
  26013. match = regex.exec(sourceCode);
  26014. }
  26015. callback(returnValue);
  26016. };
  26017. Effect.prototype._processPrecision = function (source) {
  26018. if (source.indexOf("precision highp float") === -1) {
  26019. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26020. source = "precision mediump float;\n" + source;
  26021. }
  26022. else {
  26023. source = "precision highp float;\n" + source;
  26024. }
  26025. }
  26026. else {
  26027. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26028. source = source.replace("precision highp float", "precision mediump float");
  26029. }
  26030. }
  26031. return source;
  26032. };
  26033. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26034. var _this = this;
  26035. this._isReady = false;
  26036. this._vertexSourceCodeOverride = vertexSourceCode;
  26037. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26038. this.onError = function (effect, error) {
  26039. if (onError) {
  26040. onError(error);
  26041. }
  26042. };
  26043. this.onCompiled = function () {
  26044. var scenes = _this.getEngine().scenes;
  26045. for (var i = 0; i < scenes.length; i++) {
  26046. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26047. }
  26048. if (onCompiled) {
  26049. onCompiled(_this._program);
  26050. }
  26051. };
  26052. this._fallbacks = null;
  26053. this._prepareEffect();
  26054. };
  26055. Effect.prototype._prepareEffect = function () {
  26056. var attributesNames = this._attributesNames;
  26057. var defines = this.defines;
  26058. var fallbacks = this._fallbacks;
  26059. this._valueCache = {};
  26060. var previousProgram = this._program;
  26061. try {
  26062. var engine = this._engine;
  26063. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26064. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26065. }
  26066. else {
  26067. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26068. }
  26069. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26070. if (engine.webGLVersion > 1) {
  26071. for (var name in this._uniformBuffersNames) {
  26072. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26073. }
  26074. }
  26075. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26076. this._attributes = engine.getAttributes(this._program, attributesNames);
  26077. var index;
  26078. for (index = 0; index < this._samplers.length; index++) {
  26079. var sampler = this.getUniform(this._samplers[index]);
  26080. if (sampler == null) {
  26081. this._samplers.splice(index, 1);
  26082. index--;
  26083. }
  26084. }
  26085. engine.bindSamplers(this);
  26086. this._compilationError = "";
  26087. this._isReady = true;
  26088. if (this.onCompiled) {
  26089. this.onCompiled(this);
  26090. }
  26091. this.onCompileObservable.notifyObservers(this);
  26092. this.onCompileObservable.clear();
  26093. // Unbind mesh reference in fallbacks
  26094. if (this._fallbacks) {
  26095. this._fallbacks.unBindMesh();
  26096. }
  26097. if (previousProgram) {
  26098. this.getEngine()._deleteProgram(previousProgram);
  26099. }
  26100. }
  26101. catch (e) {
  26102. this._compilationError = e.message;
  26103. // Let's go through fallbacks then
  26104. BABYLON.Tools.Error("Unable to compile effect:");
  26105. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26106. return " " + uniform;
  26107. }));
  26108. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26109. return " " + attribute;
  26110. }));
  26111. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26112. BABYLON.Tools.Error("Error: " + this._compilationError);
  26113. if (previousProgram) {
  26114. this._program = previousProgram;
  26115. this._isReady = true;
  26116. if (this.onError) {
  26117. this.onError(this, this._compilationError);
  26118. }
  26119. this.onErrorObservable.notifyObservers(this);
  26120. }
  26121. if (fallbacks && fallbacks.isMoreFallbacks) {
  26122. BABYLON.Tools.Error("Trying next fallback.");
  26123. this.defines = fallbacks.reduce(this.defines);
  26124. this._prepareEffect();
  26125. }
  26126. else {
  26127. if (this.onError) {
  26128. this.onError(this, this._compilationError);
  26129. }
  26130. this.onErrorObservable.notifyObservers(this);
  26131. this.onErrorObservable.clear();
  26132. // Unbind mesh reference in fallbacks
  26133. if (this._fallbacks) {
  26134. this._fallbacks.unBindMesh();
  26135. }
  26136. }
  26137. }
  26138. };
  26139. Object.defineProperty(Effect.prototype, "isSupported", {
  26140. get: function () {
  26141. return this._compilationError === "";
  26142. },
  26143. enumerable: true,
  26144. configurable: true
  26145. });
  26146. Effect.prototype._bindTexture = function (channel, texture) {
  26147. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26148. };
  26149. Effect.prototype.setTexture = function (channel, texture) {
  26150. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26151. };
  26152. Effect.prototype.setTextureArray = function (channel, textures) {
  26153. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26154. var initialPos = this._samplers.indexOf(channel);
  26155. for (var index = 1; index < textures.length; index++) {
  26156. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26157. }
  26158. }
  26159. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26160. };
  26161. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26162. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26163. };
  26164. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26165. var cache = this._valueCache[uniformName];
  26166. var flag = matrix.updateFlag;
  26167. if (cache !== undefined && cache === flag) {
  26168. return false;
  26169. }
  26170. this._valueCache[uniformName] = flag;
  26171. return true;
  26172. };
  26173. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26174. var cache = this._valueCache[uniformName];
  26175. if (!cache) {
  26176. cache = [x, y];
  26177. this._valueCache[uniformName] = cache;
  26178. return true;
  26179. }
  26180. var changed = false;
  26181. if (cache[0] !== x) {
  26182. cache[0] = x;
  26183. changed = true;
  26184. }
  26185. if (cache[1] !== y) {
  26186. cache[1] = y;
  26187. changed = true;
  26188. }
  26189. return changed;
  26190. };
  26191. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26192. var cache = this._valueCache[uniformName];
  26193. if (!cache) {
  26194. cache = [x, y, z];
  26195. this._valueCache[uniformName] = cache;
  26196. return true;
  26197. }
  26198. var changed = false;
  26199. if (cache[0] !== x) {
  26200. cache[0] = x;
  26201. changed = true;
  26202. }
  26203. if (cache[1] !== y) {
  26204. cache[1] = y;
  26205. changed = true;
  26206. }
  26207. if (cache[2] !== z) {
  26208. cache[2] = z;
  26209. changed = true;
  26210. }
  26211. return changed;
  26212. };
  26213. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26214. var cache = this._valueCache[uniformName];
  26215. if (!cache) {
  26216. cache = [x, y, z, w];
  26217. this._valueCache[uniformName] = cache;
  26218. return true;
  26219. }
  26220. var changed = false;
  26221. if (cache[0] !== x) {
  26222. cache[0] = x;
  26223. changed = true;
  26224. }
  26225. if (cache[1] !== y) {
  26226. cache[1] = y;
  26227. changed = true;
  26228. }
  26229. if (cache[2] !== z) {
  26230. cache[2] = z;
  26231. changed = true;
  26232. }
  26233. if (cache[3] !== w) {
  26234. cache[3] = w;
  26235. changed = true;
  26236. }
  26237. return changed;
  26238. };
  26239. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26240. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  26241. return;
  26242. }
  26243. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  26244. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  26245. };
  26246. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26247. this._engine.bindUniformBlock(this._program, blockName, index);
  26248. };
  26249. Effect.prototype.setIntArray = function (uniformName, array) {
  26250. this._valueCache[uniformName] = null;
  26251. this._engine.setIntArray(this.getUniform(uniformName), array);
  26252. return this;
  26253. };
  26254. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26255. this._valueCache[uniformName] = null;
  26256. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26257. return this;
  26258. };
  26259. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26260. this._valueCache[uniformName] = null;
  26261. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26262. return this;
  26263. };
  26264. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26265. this._valueCache[uniformName] = null;
  26266. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26267. return this;
  26268. };
  26269. Effect.prototype.setFloatArray = function (uniformName, array) {
  26270. this._valueCache[uniformName] = null;
  26271. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26272. return this;
  26273. };
  26274. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26275. this._valueCache[uniformName] = null;
  26276. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26277. return this;
  26278. };
  26279. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26280. this._valueCache[uniformName] = null;
  26281. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26282. return this;
  26283. };
  26284. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26285. this._valueCache[uniformName] = null;
  26286. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26287. return this;
  26288. };
  26289. Effect.prototype.setArray = function (uniformName, array) {
  26290. this._valueCache[uniformName] = null;
  26291. this._engine.setArray(this.getUniform(uniformName), array);
  26292. return this;
  26293. };
  26294. Effect.prototype.setArray2 = function (uniformName, array) {
  26295. this._valueCache[uniformName] = null;
  26296. this._engine.setArray2(this.getUniform(uniformName), array);
  26297. return this;
  26298. };
  26299. Effect.prototype.setArray3 = function (uniformName, array) {
  26300. this._valueCache[uniformName] = null;
  26301. this._engine.setArray3(this.getUniform(uniformName), array);
  26302. return this;
  26303. };
  26304. Effect.prototype.setArray4 = function (uniformName, array) {
  26305. this._valueCache[uniformName] = null;
  26306. this._engine.setArray4(this.getUniform(uniformName), array);
  26307. return this;
  26308. };
  26309. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26310. if (!matrices) {
  26311. return this;
  26312. }
  26313. this._valueCache[uniformName] = null;
  26314. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26315. return this;
  26316. };
  26317. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26318. if (this._cacheMatrix(uniformName, matrix)) {
  26319. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26320. }
  26321. return this;
  26322. };
  26323. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26324. this._valueCache[uniformName] = null;
  26325. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26326. return this;
  26327. };
  26328. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26329. this._valueCache[uniformName] = null;
  26330. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26331. return this;
  26332. };
  26333. Effect.prototype.setFloat = function (uniformName, value) {
  26334. var cache = this._valueCache[uniformName];
  26335. if (cache !== undefined && cache === value)
  26336. return this;
  26337. this._valueCache[uniformName] = value;
  26338. this._engine.setFloat(this.getUniform(uniformName), value);
  26339. return this;
  26340. };
  26341. Effect.prototype.setBool = function (uniformName, bool) {
  26342. var cache = this._valueCache[uniformName];
  26343. if (cache !== undefined && cache === bool)
  26344. return this;
  26345. this._valueCache[uniformName] = bool;
  26346. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26347. return this;
  26348. };
  26349. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26350. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26351. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26352. }
  26353. return this;
  26354. };
  26355. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26356. if (this._cacheFloat2(uniformName, x, y)) {
  26357. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26358. }
  26359. return this;
  26360. };
  26361. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26362. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26363. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26364. }
  26365. return this;
  26366. };
  26367. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26368. if (this._cacheFloat3(uniformName, x, y, z)) {
  26369. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26370. }
  26371. return this;
  26372. };
  26373. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26374. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26375. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26376. }
  26377. return this;
  26378. };
  26379. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26380. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26381. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26382. }
  26383. return this;
  26384. };
  26385. Effect.prototype.setColor3 = function (uniformName, color3) {
  26386. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26387. this._engine.setColor3(this.getUniform(uniformName), color3);
  26388. }
  26389. return this;
  26390. };
  26391. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26392. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26393. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26394. }
  26395. return this;
  26396. };
  26397. Effect.ResetCache = function () {
  26398. Effect._baseCache = {};
  26399. };
  26400. Effect._uniqueIdSeed = 0;
  26401. Effect._baseCache = {};
  26402. // Statics
  26403. Effect.ShadersStore = {};
  26404. Effect.IncludesShadersStore = {};
  26405. return Effect;
  26406. }());
  26407. BABYLON.Effect = Effect;
  26408. })(BABYLON || (BABYLON = {}));
  26409. //# sourceMappingURL=babylon.effect.js.map
  26410. var BABYLON;
  26411. (function (BABYLON) {
  26412. var MaterialHelper = /** @class */ (function () {
  26413. function MaterialHelper() {
  26414. }
  26415. MaterialHelper.BindEyePosition = function (effect, scene) {
  26416. if (scene._forcedViewPosition) {
  26417. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26418. return;
  26419. }
  26420. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26421. };
  26422. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26423. defines._needUVs = true;
  26424. defines[key] = true;
  26425. if (texture.getTextureMatrix().isIdentity(true)) {
  26426. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26427. if (texture.coordinatesIndex === 0) {
  26428. defines["MAINUV1"] = true;
  26429. }
  26430. else {
  26431. defines["MAINUV2"] = true;
  26432. }
  26433. }
  26434. else {
  26435. defines[key + "DIRECTUV"] = 0;
  26436. }
  26437. };
  26438. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26439. var matrix = texture.getTextureMatrix();
  26440. if (!matrix.isIdentity(true)) {
  26441. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26442. }
  26443. };
  26444. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26445. if (defines._areMiscDirty) {
  26446. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26447. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26448. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26449. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26450. }
  26451. };
  26452. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26453. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26454. var changed = false;
  26455. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26456. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26457. changed = true;
  26458. }
  26459. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26460. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26461. changed = true;
  26462. }
  26463. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26464. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26465. changed = true;
  26466. }
  26467. if (defines["INSTANCES"] !== useInstances) {
  26468. defines["INSTANCES"] = useInstances;
  26469. changed = true;
  26470. }
  26471. if (changed) {
  26472. defines.markAsUnprocessed();
  26473. }
  26474. };
  26475. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  26476. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26477. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26478. return false;
  26479. }
  26480. defines._normals = defines._needNormals;
  26481. defines._uvs = defines._needUVs;
  26482. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26483. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26484. defines["TANGENT"] = true;
  26485. }
  26486. if (defines._needUVs) {
  26487. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26488. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26489. }
  26490. else {
  26491. defines["UV1"] = false;
  26492. defines["UV2"] = false;
  26493. }
  26494. if (useVertexColor) {
  26495. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26496. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  26497. }
  26498. if (useBones) {
  26499. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26500. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26501. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26502. }
  26503. else {
  26504. defines["NUM_BONE_INFLUENCERS"] = 0;
  26505. defines["BonesPerMesh"] = 0;
  26506. }
  26507. }
  26508. if (useMorphTargets) {
  26509. var manager = mesh.morphTargetManager;
  26510. if (manager) {
  26511. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  26512. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  26513. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  26514. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  26515. }
  26516. else {
  26517. defines["MORPHTARGETS_TANGENT"] = false;
  26518. defines["MORPHTARGETS_NORMAL"] = false;
  26519. defines["MORPHTARGETS"] = false;
  26520. defines["NUM_MORPH_INFLUENCERS"] = 0;
  26521. }
  26522. }
  26523. return true;
  26524. };
  26525. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  26526. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26527. if (disableLighting === void 0) { disableLighting = false; }
  26528. if (!defines._areLightsDirty) {
  26529. return defines._needNormals;
  26530. }
  26531. var lightIndex = 0;
  26532. var needNormals = false;
  26533. var needRebuild = false;
  26534. var lightmapMode = false;
  26535. var shadowEnabled = false;
  26536. var specularEnabled = false;
  26537. if (scene.lightsEnabled && !disableLighting) {
  26538. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26539. var light = _a[_i];
  26540. needNormals = true;
  26541. if (defines["LIGHT" + lightIndex] === undefined) {
  26542. needRebuild = true;
  26543. }
  26544. defines["LIGHT" + lightIndex] = true;
  26545. defines["SPOTLIGHT" + lightIndex] = false;
  26546. defines["HEMILIGHT" + lightIndex] = false;
  26547. defines["POINTLIGHT" + lightIndex] = false;
  26548. defines["DIRLIGHT" + lightIndex] = false;
  26549. var type;
  26550. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  26551. type = "SPOTLIGHT" + lightIndex;
  26552. }
  26553. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  26554. type = "HEMILIGHT" + lightIndex;
  26555. }
  26556. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  26557. type = "POINTLIGHT" + lightIndex;
  26558. }
  26559. else {
  26560. type = "DIRLIGHT" + lightIndex;
  26561. }
  26562. defines[type] = true;
  26563. // Specular
  26564. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  26565. specularEnabled = true;
  26566. }
  26567. // Shadows
  26568. defines["SHADOW" + lightIndex] = false;
  26569. defines["SHADOWPCF" + lightIndex] = false;
  26570. defines["SHADOWESM" + lightIndex] = false;
  26571. defines["SHADOWCUBE" + lightIndex] = false;
  26572. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  26573. var shadowGenerator = light.getShadowGenerator();
  26574. if (shadowGenerator) {
  26575. shadowEnabled = true;
  26576. shadowGenerator.prepareDefines(defines, lightIndex);
  26577. }
  26578. }
  26579. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26580. lightmapMode = true;
  26581. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26582. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  26583. }
  26584. else {
  26585. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  26586. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  26587. }
  26588. lightIndex++;
  26589. if (lightIndex === maxSimultaneousLights)
  26590. break;
  26591. }
  26592. }
  26593. defines["SPECULARTERM"] = specularEnabled;
  26594. defines["SHADOWS"] = shadowEnabled;
  26595. // Resetting all other lights if any
  26596. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26597. if (defines["LIGHT" + index] !== undefined) {
  26598. defines["LIGHT" + index] = false;
  26599. defines["HEMILIGHT" + lightIndex] = false;
  26600. defines["POINTLIGHT" + lightIndex] = false;
  26601. defines["DIRLIGHT" + lightIndex] = false;
  26602. defines["SPOTLIGHT" + lightIndex] = false;
  26603. defines["SHADOW" + lightIndex] = false;
  26604. }
  26605. }
  26606. var caps = scene.getEngine().getCaps();
  26607. if (defines["SHADOWFLOAT"] === undefined) {
  26608. needRebuild = true;
  26609. }
  26610. defines["SHADOWFLOAT"] = shadowEnabled &&
  26611. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26612. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26613. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26614. if (needRebuild) {
  26615. defines.rebuild();
  26616. }
  26617. return needNormals;
  26618. };
  26619. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26620. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26621. var uniformsList;
  26622. var uniformBuffersList = null;
  26623. if (uniformsListOrOptions.uniformsNames) {
  26624. var options = uniformsListOrOptions;
  26625. uniformsList = options.uniformsNames;
  26626. uniformBuffersList = options.uniformBuffersNames;
  26627. samplersList = options.samplers;
  26628. defines = options.defines;
  26629. maxSimultaneousLights = options.maxSimultaneousLights;
  26630. }
  26631. else {
  26632. uniformsList = uniformsListOrOptions;
  26633. if (!samplersList) {
  26634. samplersList = [];
  26635. }
  26636. }
  26637. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26638. if (!defines["LIGHT" + lightIndex]) {
  26639. break;
  26640. }
  26641. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26642. if (uniformBuffersList) {
  26643. uniformBuffersList.push("Light" + lightIndex);
  26644. }
  26645. samplersList.push("shadowSampler" + lightIndex);
  26646. }
  26647. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26648. uniformsList.push("morphTargetInfluences");
  26649. }
  26650. };
  26651. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  26652. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26653. if (rank === void 0) { rank = 0; }
  26654. var lightFallbackRank = 0;
  26655. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26656. if (!defines["LIGHT" + lightIndex]) {
  26657. break;
  26658. }
  26659. if (lightIndex > 0) {
  26660. lightFallbackRank = rank + lightIndex;
  26661. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  26662. }
  26663. if (!defines["SHADOWS"]) {
  26664. if (defines["SHADOW" + lightIndex]) {
  26665. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  26666. }
  26667. if (defines["SHADOWPCF" + lightIndex]) {
  26668. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  26669. }
  26670. if (defines["SHADOWESM" + lightIndex]) {
  26671. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  26672. }
  26673. }
  26674. }
  26675. return lightFallbackRank++;
  26676. };
  26677. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26678. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26679. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  26680. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26681. var manager = mesh.morphTargetManager;
  26682. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  26683. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  26684. for (var index = 0; index < influencers; index++) {
  26685. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26686. if (normal) {
  26687. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26688. }
  26689. if (tangent) {
  26690. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26691. }
  26692. if (attribs.length > maxAttributesCount) {
  26693. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26694. }
  26695. }
  26696. }
  26697. };
  26698. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26699. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26700. fallbacks.addCPUSkinningFallback(0, mesh);
  26701. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26702. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26703. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26704. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26705. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26706. }
  26707. }
  26708. };
  26709. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26710. if (defines["INSTANCES"]) {
  26711. attribs.push("world0");
  26712. attribs.push("world1");
  26713. attribs.push("world2");
  26714. attribs.push("world3");
  26715. }
  26716. };
  26717. // Bindings
  26718. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26719. if (light.shadowEnabled && mesh.receiveShadows) {
  26720. var shadowGenerator = light.getShadowGenerator();
  26721. if (shadowGenerator) {
  26722. shadowGenerator.bindShadowLight(lightIndex, effect);
  26723. }
  26724. }
  26725. };
  26726. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26727. light.transferToEffect(effect, lightIndex + "");
  26728. };
  26729. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26730. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26731. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26732. var lightIndex = 0;
  26733. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26734. var light = _a[_i];
  26735. var scaledIntensity = light.getScaledIntensity();
  26736. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26737. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26738. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26739. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26740. if (defines["SPECULARTERM"]) {
  26741. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26742. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26743. }
  26744. // Shadows
  26745. if (scene.shadowsEnabled) {
  26746. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26747. }
  26748. light._uniformBuffer.update();
  26749. lightIndex++;
  26750. if (lightIndex === maxSimultaneousLights)
  26751. break;
  26752. }
  26753. };
  26754. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26755. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26756. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26757. effect.setColor3("vFogColor", scene.fogColor);
  26758. }
  26759. };
  26760. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26761. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26762. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26763. if (matrices && effect) {
  26764. effect.setMatrices("mBones", matrices);
  26765. }
  26766. }
  26767. };
  26768. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26769. var manager = abstractMesh.morphTargetManager;
  26770. if (!abstractMesh || !manager) {
  26771. return;
  26772. }
  26773. effect.setFloatArray("morphTargetInfluences", manager.influences);
  26774. };
  26775. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26776. if (defines["LOGARITHMICDEPTH"]) {
  26777. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26778. }
  26779. };
  26780. MaterialHelper.BindClipPlane = function (effect, scene) {
  26781. if (scene.clipPlane) {
  26782. var clipPlane = scene.clipPlane;
  26783. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26784. }
  26785. };
  26786. return MaterialHelper;
  26787. }());
  26788. BABYLON.MaterialHelper = MaterialHelper;
  26789. })(BABYLON || (BABYLON = {}));
  26790. //# sourceMappingURL=babylon.materialHelper.js.map
  26791. var BABYLON;
  26792. (function (BABYLON) {
  26793. var MaterialDefines = /** @class */ (function () {
  26794. function MaterialDefines() {
  26795. this._isDirty = true;
  26796. this._areLightsDirty = true;
  26797. this._areAttributesDirty = true;
  26798. this._areTexturesDirty = true;
  26799. this._areFresnelDirty = true;
  26800. this._areMiscDirty = true;
  26801. this._areImageProcessingDirty = true;
  26802. this._normals = false;
  26803. this._uvs = false;
  26804. this._needNormals = false;
  26805. this._needUVs = false;
  26806. }
  26807. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26808. get: function () {
  26809. return this._isDirty;
  26810. },
  26811. enumerable: true,
  26812. configurable: true
  26813. });
  26814. MaterialDefines.prototype.markAsProcessed = function () {
  26815. this._isDirty = false;
  26816. this._areAttributesDirty = false;
  26817. this._areTexturesDirty = false;
  26818. this._areFresnelDirty = false;
  26819. this._areLightsDirty = false;
  26820. this._areMiscDirty = false;
  26821. this._areImageProcessingDirty = false;
  26822. };
  26823. MaterialDefines.prototype.markAsUnprocessed = function () {
  26824. this._isDirty = true;
  26825. };
  26826. MaterialDefines.prototype.markAllAsDirty = function () {
  26827. this._areTexturesDirty = true;
  26828. this._areAttributesDirty = true;
  26829. this._areLightsDirty = true;
  26830. this._areFresnelDirty = true;
  26831. this._areMiscDirty = true;
  26832. this._areImageProcessingDirty = true;
  26833. this._isDirty = true;
  26834. };
  26835. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  26836. this._areImageProcessingDirty = true;
  26837. this._isDirty = true;
  26838. };
  26839. MaterialDefines.prototype.markAsLightDirty = function () {
  26840. this._areLightsDirty = true;
  26841. this._isDirty = true;
  26842. };
  26843. MaterialDefines.prototype.markAsAttributesDirty = function () {
  26844. this._areAttributesDirty = true;
  26845. this._isDirty = true;
  26846. };
  26847. MaterialDefines.prototype.markAsTexturesDirty = function () {
  26848. this._areTexturesDirty = true;
  26849. this._isDirty = true;
  26850. };
  26851. MaterialDefines.prototype.markAsFresnelDirty = function () {
  26852. this._areFresnelDirty = true;
  26853. this._isDirty = true;
  26854. };
  26855. MaterialDefines.prototype.markAsMiscDirty = function () {
  26856. this._areMiscDirty = true;
  26857. this._isDirty = true;
  26858. };
  26859. MaterialDefines.prototype.rebuild = function () {
  26860. if (this._keys) {
  26861. delete this._keys;
  26862. }
  26863. this._keys = [];
  26864. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  26865. var key = _a[_i];
  26866. if (key[0] === "_") {
  26867. continue;
  26868. }
  26869. this._keys.push(key);
  26870. }
  26871. };
  26872. MaterialDefines.prototype.isEqual = function (other) {
  26873. if (this._keys.length !== other._keys.length) {
  26874. return false;
  26875. }
  26876. for (var index = 0; index < this._keys.length; index++) {
  26877. var prop = this._keys[index];
  26878. if (this[prop] !== other[prop]) {
  26879. return false;
  26880. }
  26881. }
  26882. return true;
  26883. };
  26884. MaterialDefines.prototype.cloneTo = function (other) {
  26885. if (this._keys.length !== other._keys.length) {
  26886. other._keys = this._keys.slice(0);
  26887. }
  26888. for (var index = 0; index < this._keys.length; index++) {
  26889. var prop = this._keys[index];
  26890. other[prop] = this[prop];
  26891. }
  26892. };
  26893. MaterialDefines.prototype.reset = function () {
  26894. for (var index = 0; index < this._keys.length; index++) {
  26895. var prop = this._keys[index];
  26896. if (typeof (this[prop]) === "number") {
  26897. this[prop] = 0;
  26898. }
  26899. else {
  26900. this[prop] = false;
  26901. }
  26902. }
  26903. };
  26904. MaterialDefines.prototype.toString = function () {
  26905. var result = "";
  26906. for (var index = 0; index < this._keys.length; index++) {
  26907. var prop = this._keys[index];
  26908. var value = this[prop];
  26909. if (typeof (value) === "number") {
  26910. result += "#define " + prop + " " + this[prop] + "\n";
  26911. }
  26912. else if (value) {
  26913. result += "#define " + prop + "\n";
  26914. }
  26915. }
  26916. return result;
  26917. };
  26918. return MaterialDefines;
  26919. }());
  26920. BABYLON.MaterialDefines = MaterialDefines;
  26921. var Material = /** @class */ (function () {
  26922. function Material(name, scene, doNotAdd) {
  26923. this.checkReadyOnEveryCall = false;
  26924. this.checkReadyOnlyOnce = false;
  26925. this.state = "";
  26926. this.alpha = 1.0;
  26927. this._backFaceCulling = true;
  26928. this.doNotSerialize = false;
  26929. this.storeEffectOnSubMeshes = false;
  26930. /**
  26931. * An event triggered when the material is disposed.
  26932. * @type {BABYLON.Observable}
  26933. */
  26934. this.onDisposeObservable = new BABYLON.Observable();
  26935. /**
  26936. * An event triggered when the material is bound.
  26937. * @type {BABYLON.Observable}
  26938. */
  26939. this.onBindObservable = new BABYLON.Observable();
  26940. /**
  26941. * An event triggered when the material is unbound.
  26942. * @type {BABYLON.Observable}
  26943. */
  26944. this.onUnBindObservable = new BABYLON.Observable();
  26945. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26946. this._needDepthPrePass = false;
  26947. this.disableDepthWrite = false;
  26948. this.forceDepthWrite = false;
  26949. this.separateCullingPass = false;
  26950. this._fogEnabled = true;
  26951. this.pointSize = 1.0;
  26952. this.zOffset = 0;
  26953. this._wasPreviouslyReady = false;
  26954. this._fillMode = Material.TriangleFillMode;
  26955. this.name = name;
  26956. this.id = name || BABYLON.Tools.RandomId();
  26957. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26958. if (this._scene.useRightHandedSystem) {
  26959. this.sideOrientation = Material.ClockWiseSideOrientation;
  26960. }
  26961. else {
  26962. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26963. }
  26964. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  26965. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  26966. if (!doNotAdd) {
  26967. this._scene.materials.push(this);
  26968. }
  26969. }
  26970. Object.defineProperty(Material, "TriangleFillMode", {
  26971. get: function () {
  26972. return Material._TriangleFillMode;
  26973. },
  26974. enumerable: true,
  26975. configurable: true
  26976. });
  26977. Object.defineProperty(Material, "WireFrameFillMode", {
  26978. get: function () {
  26979. return Material._WireFrameFillMode;
  26980. },
  26981. enumerable: true,
  26982. configurable: true
  26983. });
  26984. Object.defineProperty(Material, "PointFillMode", {
  26985. get: function () {
  26986. return Material._PointFillMode;
  26987. },
  26988. enumerable: true,
  26989. configurable: true
  26990. });
  26991. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26992. get: function () {
  26993. return Material._ClockWiseSideOrientation;
  26994. },
  26995. enumerable: true,
  26996. configurable: true
  26997. });
  26998. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26999. get: function () {
  27000. return Material._CounterClockWiseSideOrientation;
  27001. },
  27002. enumerable: true,
  27003. configurable: true
  27004. });
  27005. Object.defineProperty(Material, "TextureDirtyFlag", {
  27006. get: function () {
  27007. return Material._TextureDirtyFlag;
  27008. },
  27009. enumerable: true,
  27010. configurable: true
  27011. });
  27012. Object.defineProperty(Material, "LightDirtyFlag", {
  27013. get: function () {
  27014. return Material._LightDirtyFlag;
  27015. },
  27016. enumerable: true,
  27017. configurable: true
  27018. });
  27019. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27020. get: function () {
  27021. return Material._FresnelDirtyFlag;
  27022. },
  27023. enumerable: true,
  27024. configurable: true
  27025. });
  27026. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27027. get: function () {
  27028. return Material._AttributesDirtyFlag;
  27029. },
  27030. enumerable: true,
  27031. configurable: true
  27032. });
  27033. Object.defineProperty(Material, "MiscDirtyFlag", {
  27034. get: function () {
  27035. return Material._MiscDirtyFlag;
  27036. },
  27037. enumerable: true,
  27038. configurable: true
  27039. });
  27040. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27041. get: function () {
  27042. return this._backFaceCulling;
  27043. },
  27044. set: function (value) {
  27045. if (this._backFaceCulling === value) {
  27046. return;
  27047. }
  27048. this._backFaceCulling = value;
  27049. this.markAsDirty(Material.TextureDirtyFlag);
  27050. },
  27051. enumerable: true,
  27052. configurable: true
  27053. });
  27054. Object.defineProperty(Material.prototype, "onDispose", {
  27055. set: function (callback) {
  27056. if (this._onDisposeObserver) {
  27057. this.onDisposeObservable.remove(this._onDisposeObserver);
  27058. }
  27059. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27060. },
  27061. enumerable: true,
  27062. configurable: true
  27063. });
  27064. Object.defineProperty(Material.prototype, "onBind", {
  27065. set: function (callback) {
  27066. if (this._onBindObserver) {
  27067. this.onBindObservable.remove(this._onBindObserver);
  27068. }
  27069. this._onBindObserver = this.onBindObservable.add(callback);
  27070. },
  27071. enumerable: true,
  27072. configurable: true
  27073. });
  27074. Object.defineProperty(Material.prototype, "alphaMode", {
  27075. get: function () {
  27076. return this._alphaMode;
  27077. },
  27078. set: function (value) {
  27079. if (this._alphaMode === value) {
  27080. return;
  27081. }
  27082. this._alphaMode = value;
  27083. this.markAsDirty(Material.TextureDirtyFlag);
  27084. },
  27085. enumerable: true,
  27086. configurable: true
  27087. });
  27088. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27089. get: function () {
  27090. return this._needDepthPrePass;
  27091. },
  27092. set: function (value) {
  27093. if (this._needDepthPrePass === value) {
  27094. return;
  27095. }
  27096. this._needDepthPrePass = value;
  27097. if (this._needDepthPrePass) {
  27098. this.checkReadyOnEveryCall = true;
  27099. }
  27100. },
  27101. enumerable: true,
  27102. configurable: true
  27103. });
  27104. Object.defineProperty(Material.prototype, "fogEnabled", {
  27105. get: function () {
  27106. return this._fogEnabled;
  27107. },
  27108. set: function (value) {
  27109. if (this._fogEnabled === value) {
  27110. return;
  27111. }
  27112. this._fogEnabled = value;
  27113. this.markAsDirty(Material.MiscDirtyFlag);
  27114. },
  27115. enumerable: true,
  27116. configurable: true
  27117. });
  27118. Object.defineProperty(Material.prototype, "wireframe", {
  27119. get: function () {
  27120. return this._fillMode === Material.WireFrameFillMode;
  27121. },
  27122. set: function (value) {
  27123. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27124. },
  27125. enumerable: true,
  27126. configurable: true
  27127. });
  27128. Object.defineProperty(Material.prototype, "pointsCloud", {
  27129. get: function () {
  27130. return this._fillMode === Material.PointFillMode;
  27131. },
  27132. set: function (value) {
  27133. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27134. },
  27135. enumerable: true,
  27136. configurable: true
  27137. });
  27138. Object.defineProperty(Material.prototype, "fillMode", {
  27139. get: function () {
  27140. return this._fillMode;
  27141. },
  27142. set: function (value) {
  27143. if (this._fillMode === value) {
  27144. return;
  27145. }
  27146. this._fillMode = value;
  27147. this.markAsDirty(Material.MiscDirtyFlag);
  27148. },
  27149. enumerable: true,
  27150. configurable: true
  27151. });
  27152. /**
  27153. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27154. * subclasses should override adding information pertainent to themselves
  27155. */
  27156. Material.prototype.toString = function (fullDetails) {
  27157. var ret = "Name: " + this.name;
  27158. if (fullDetails) {
  27159. }
  27160. return ret;
  27161. };
  27162. /**
  27163. * Child classes can use it to update shaders
  27164. */
  27165. Material.prototype.getClassName = function () {
  27166. return "Material";
  27167. };
  27168. Object.defineProperty(Material.prototype, "isFrozen", {
  27169. get: function () {
  27170. return this.checkReadyOnlyOnce;
  27171. },
  27172. enumerable: true,
  27173. configurable: true
  27174. });
  27175. Material.prototype.freeze = function () {
  27176. this.checkReadyOnlyOnce = true;
  27177. };
  27178. Material.prototype.unfreeze = function () {
  27179. this.checkReadyOnlyOnce = false;
  27180. };
  27181. Material.prototype.isReady = function (mesh, useInstances) {
  27182. return true;
  27183. };
  27184. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27185. return false;
  27186. };
  27187. Material.prototype.getEffect = function () {
  27188. return this._effect;
  27189. };
  27190. Material.prototype.getScene = function () {
  27191. return this._scene;
  27192. };
  27193. Material.prototype.needAlphaBlending = function () {
  27194. return (this.alpha < 1.0);
  27195. };
  27196. Material.prototype.needAlphaTesting = function () {
  27197. return false;
  27198. };
  27199. Material.prototype.getAlphaTestTexture = function () {
  27200. return null;
  27201. };
  27202. Material.prototype.markDirty = function () {
  27203. this._wasPreviouslyReady = false;
  27204. };
  27205. Material.prototype._preBind = function (effect, overrideOrientation) {
  27206. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27207. var engine = this._scene.getEngine();
  27208. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27209. var reverse = orientation === Material.ClockWiseSideOrientation;
  27210. engine.enableEffect(effect ? effect : this._effect);
  27211. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27212. return reverse;
  27213. };
  27214. Material.prototype.bind = function (world, mesh) {
  27215. };
  27216. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27217. };
  27218. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27219. };
  27220. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27221. sceneUbo.bindToEffect(effect, "Scene");
  27222. };
  27223. Material.prototype.bindView = function (effect) {
  27224. if (!this._useUBO) {
  27225. effect.setMatrix("view", this.getScene().getViewMatrix());
  27226. }
  27227. else {
  27228. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27229. }
  27230. };
  27231. Material.prototype.bindViewProjection = function (effect) {
  27232. if (!this._useUBO) {
  27233. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27234. }
  27235. else {
  27236. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27237. }
  27238. };
  27239. Material.prototype._afterBind = function (mesh) {
  27240. this._scene._cachedMaterial = this;
  27241. if (mesh) {
  27242. this._scene._cachedVisibility = mesh.visibility;
  27243. }
  27244. else {
  27245. this._scene._cachedVisibility = 1;
  27246. }
  27247. if (mesh) {
  27248. this.onBindObservable.notifyObservers(mesh);
  27249. }
  27250. if (this.disableDepthWrite) {
  27251. var engine = this._scene.getEngine();
  27252. this._cachedDepthWriteState = engine.getDepthWrite();
  27253. engine.setDepthWrite(false);
  27254. }
  27255. };
  27256. Material.prototype.unbind = function () {
  27257. this.onUnBindObservable.notifyObservers(this);
  27258. if (this.disableDepthWrite) {
  27259. var engine = this._scene.getEngine();
  27260. engine.setDepthWrite(this._cachedDepthWriteState);
  27261. }
  27262. };
  27263. Material.prototype.getActiveTextures = function () {
  27264. return [];
  27265. };
  27266. Material.prototype.hasTexture = function (texture) {
  27267. return false;
  27268. };
  27269. Material.prototype.clone = function (name) {
  27270. return null;
  27271. };
  27272. Material.prototype.getBindedMeshes = function () {
  27273. var result = new Array();
  27274. for (var index = 0; index < this._scene.meshes.length; index++) {
  27275. var mesh = this._scene.meshes[index];
  27276. if (mesh.material === this) {
  27277. result.push(mesh);
  27278. }
  27279. }
  27280. return result;
  27281. };
  27282. /**
  27283. * Force shader compilation including textures ready check
  27284. */
  27285. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27286. var _this = this;
  27287. var subMesh = new BABYLON.BaseSubMesh();
  27288. var scene = this.getScene();
  27289. var engine = scene.getEngine();
  27290. var checkReady = function () {
  27291. if (!_this._scene || !_this._scene.getEngine()) {
  27292. return;
  27293. }
  27294. if (subMesh._materialDefines) {
  27295. subMesh._materialDefines._renderId = -1;
  27296. }
  27297. var alphaTestState = engine.getAlphaTesting();
  27298. var clipPlaneState = scene.clipPlane;
  27299. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  27300. if (options && options.clipPlane) {
  27301. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27302. }
  27303. if (_this.storeEffectOnSubMeshes) {
  27304. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27305. if (onCompiled) {
  27306. onCompiled(_this);
  27307. }
  27308. }
  27309. else {
  27310. setTimeout(checkReady, 16);
  27311. }
  27312. }
  27313. else {
  27314. if (_this.isReady(mesh)) {
  27315. if (onCompiled) {
  27316. onCompiled(_this);
  27317. }
  27318. }
  27319. else {
  27320. setTimeout(checkReady, 16);
  27321. }
  27322. }
  27323. engine.setAlphaTesting(alphaTestState);
  27324. if (options && options.clipPlane) {
  27325. scene.clipPlane = clipPlaneState;
  27326. }
  27327. };
  27328. checkReady();
  27329. };
  27330. Material.prototype.markAsDirty = function (flag) {
  27331. if (flag & Material.TextureDirtyFlag) {
  27332. this._markAllSubMeshesAsTexturesDirty();
  27333. }
  27334. if (flag & Material.LightDirtyFlag) {
  27335. this._markAllSubMeshesAsLightsDirty();
  27336. }
  27337. if (flag & Material.FresnelDirtyFlag) {
  27338. this._markAllSubMeshesAsFresnelDirty();
  27339. }
  27340. if (flag & Material.AttributesDirtyFlag) {
  27341. this._markAllSubMeshesAsAttributesDirty();
  27342. }
  27343. if (flag & Material.MiscDirtyFlag) {
  27344. this._markAllSubMeshesAsMiscDirty();
  27345. }
  27346. this.getScene().resetCachedMaterial();
  27347. };
  27348. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27349. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27350. var mesh = _a[_i];
  27351. if (!mesh.subMeshes) {
  27352. continue;
  27353. }
  27354. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27355. var subMesh = _c[_b];
  27356. if (subMesh.getMaterial() !== this) {
  27357. continue;
  27358. }
  27359. if (!subMesh._materialDefines) {
  27360. continue;
  27361. }
  27362. func(subMesh._materialDefines);
  27363. }
  27364. }
  27365. };
  27366. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27367. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27368. };
  27369. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27370. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27371. };
  27372. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27373. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27374. };
  27375. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27376. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27377. };
  27378. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27379. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27380. };
  27381. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27382. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27383. };
  27384. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27385. // Animations
  27386. this.getScene().stopAnimation(this);
  27387. // Remove from scene
  27388. var index = this._scene.materials.indexOf(this);
  27389. if (index >= 0) {
  27390. this._scene.materials.splice(index, 1);
  27391. }
  27392. // Remove from meshes
  27393. for (index = 0; index < this._scene.meshes.length; index++) {
  27394. var mesh = this._scene.meshes[index];
  27395. if (mesh.material === this) {
  27396. mesh.material = null;
  27397. if (mesh.geometry) {
  27398. var geometry = (mesh.geometry);
  27399. if (this.storeEffectOnSubMeshes) {
  27400. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27401. var subMesh = _a[_i];
  27402. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27403. if (forceDisposeEffect && subMesh._materialEffect) {
  27404. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27405. }
  27406. }
  27407. }
  27408. else {
  27409. geometry._releaseVertexArrayObject(this._effect);
  27410. }
  27411. }
  27412. }
  27413. }
  27414. this._uniformBuffer.dispose();
  27415. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27416. if (forceDisposeEffect && this._effect) {
  27417. if (!this.storeEffectOnSubMeshes) {
  27418. this._scene.getEngine()._releaseEffect(this._effect);
  27419. }
  27420. this._effect = null;
  27421. }
  27422. // Callback
  27423. this.onDisposeObservable.notifyObservers(this);
  27424. this.onDisposeObservable.clear();
  27425. this.onBindObservable.clear();
  27426. this.onUnBindObservable.clear();
  27427. };
  27428. Material.prototype.serialize = function () {
  27429. return BABYLON.SerializationHelper.Serialize(this);
  27430. };
  27431. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27432. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27433. multiMaterial.id = parsedMultiMaterial.id;
  27434. if (BABYLON.Tags) {
  27435. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27436. }
  27437. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27438. var subMatId = parsedMultiMaterial.materials[matIndex];
  27439. if (subMatId) {
  27440. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27441. }
  27442. else {
  27443. multiMaterial.subMaterials.push(null);
  27444. }
  27445. }
  27446. return multiMaterial;
  27447. };
  27448. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27449. if (!parsedMaterial.customType) {
  27450. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27451. }
  27452. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27453. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27454. if (!BABYLON.LegacyPBRMaterial) {
  27455. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27456. return;
  27457. }
  27458. }
  27459. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27460. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27461. ;
  27462. };
  27463. Material._TriangleFillMode = 0;
  27464. Material._WireFrameFillMode = 1;
  27465. Material._PointFillMode = 2;
  27466. Material._ClockWiseSideOrientation = 0;
  27467. Material._CounterClockWiseSideOrientation = 1;
  27468. Material._TextureDirtyFlag = 1;
  27469. Material._LightDirtyFlag = 2;
  27470. Material._FresnelDirtyFlag = 4;
  27471. Material._AttributesDirtyFlag = 8;
  27472. Material._MiscDirtyFlag = 16;
  27473. __decorate([
  27474. BABYLON.serialize()
  27475. ], Material.prototype, "id", void 0);
  27476. __decorate([
  27477. BABYLON.serialize()
  27478. ], Material.prototype, "name", void 0);
  27479. __decorate([
  27480. BABYLON.serialize()
  27481. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27482. __decorate([
  27483. BABYLON.serialize()
  27484. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27485. __decorate([
  27486. BABYLON.serialize()
  27487. ], Material.prototype, "state", void 0);
  27488. __decorate([
  27489. BABYLON.serialize()
  27490. ], Material.prototype, "alpha", void 0);
  27491. __decorate([
  27492. BABYLON.serialize("backFaceCulling")
  27493. ], Material.prototype, "_backFaceCulling", void 0);
  27494. __decorate([
  27495. BABYLON.serialize()
  27496. ], Material.prototype, "sideOrientation", void 0);
  27497. __decorate([
  27498. BABYLON.serialize("alphaMode")
  27499. ], Material.prototype, "_alphaMode", void 0);
  27500. __decorate([
  27501. BABYLON.serialize()
  27502. ], Material.prototype, "_needDepthPrePass", void 0);
  27503. __decorate([
  27504. BABYLON.serialize()
  27505. ], Material.prototype, "disableDepthWrite", void 0);
  27506. __decorate([
  27507. BABYLON.serialize()
  27508. ], Material.prototype, "forceDepthWrite", void 0);
  27509. __decorate([
  27510. BABYLON.serialize()
  27511. ], Material.prototype, "separateCullingPass", void 0);
  27512. __decorate([
  27513. BABYLON.serialize("fogEnabled")
  27514. ], Material.prototype, "_fogEnabled", void 0);
  27515. __decorate([
  27516. BABYLON.serialize()
  27517. ], Material.prototype, "pointSize", void 0);
  27518. __decorate([
  27519. BABYLON.serialize()
  27520. ], Material.prototype, "zOffset", void 0);
  27521. __decorate([
  27522. BABYLON.serialize()
  27523. ], Material.prototype, "wireframe", null);
  27524. __decorate([
  27525. BABYLON.serialize()
  27526. ], Material.prototype, "pointsCloud", null);
  27527. __decorate([
  27528. BABYLON.serialize()
  27529. ], Material.prototype, "fillMode", null);
  27530. return Material;
  27531. }());
  27532. BABYLON.Material = Material;
  27533. })(BABYLON || (BABYLON = {}));
  27534. //# sourceMappingURL=babylon.material.js.map
  27535. var BABYLON;
  27536. (function (BABYLON) {
  27537. var UniformBuffer = /** @class */ (function () {
  27538. /**
  27539. * Uniform buffer objects.
  27540. *
  27541. * Handles blocks of uniform on the GPU.
  27542. *
  27543. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  27544. *
  27545. * For more information, please refer to :
  27546. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  27547. */
  27548. function UniformBuffer(engine, data, dynamic) {
  27549. this._engine = engine;
  27550. this._noUBO = !engine.supportsUniformBuffers;
  27551. this._dynamic = dynamic;
  27552. this._data = data || [];
  27553. this._uniformLocations = {};
  27554. this._uniformSizes = {};
  27555. this._uniformLocationPointer = 0;
  27556. this._needSync = false;
  27557. if (this._noUBO) {
  27558. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  27559. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  27560. this.updateFloat = this._updateFloatForEffect;
  27561. this.updateFloat2 = this._updateFloat2ForEffect;
  27562. this.updateFloat3 = this._updateFloat3ForEffect;
  27563. this.updateFloat4 = this._updateFloat4ForEffect;
  27564. this.updateMatrix = this._updateMatrixForEffect;
  27565. this.updateVector3 = this._updateVector3ForEffect;
  27566. this.updateVector4 = this._updateVector4ForEffect;
  27567. this.updateColor3 = this._updateColor3ForEffect;
  27568. this.updateColor4 = this._updateColor4ForEffect;
  27569. }
  27570. else {
  27571. this._engine._uniformBuffers.push(this);
  27572. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  27573. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  27574. this.updateFloat = this._updateFloatForUniform;
  27575. this.updateFloat2 = this._updateFloat2ForUniform;
  27576. this.updateFloat3 = this._updateFloat3ForUniform;
  27577. this.updateFloat4 = this._updateFloat4ForUniform;
  27578. this.updateMatrix = this._updateMatrixForUniform;
  27579. this.updateVector3 = this._updateVector3ForUniform;
  27580. this.updateVector4 = this._updateVector4ForUniform;
  27581. this.updateColor3 = this._updateColor3ForUniform;
  27582. this.updateColor4 = this._updateColor4ForUniform;
  27583. }
  27584. }
  27585. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  27586. // Properties
  27587. /**
  27588. * Indicates if the buffer is using the WebGL2 UBO implementation,
  27589. * or just falling back on setUniformXXX calls.
  27590. */
  27591. get: function () {
  27592. return !this._noUBO;
  27593. },
  27594. enumerable: true,
  27595. configurable: true
  27596. });
  27597. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  27598. /**
  27599. * Indicates if the WebGL underlying uniform buffer is in sync
  27600. * with the javascript cache data.
  27601. */
  27602. get: function () {
  27603. return !this._needSync;
  27604. },
  27605. enumerable: true,
  27606. configurable: true
  27607. });
  27608. /**
  27609. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27610. * Also, a dynamic UniformBuffer will disable cache verification and always
  27611. * update the underlying WebGL uniform buffer to the GPU.
  27612. */
  27613. UniformBuffer.prototype.isDynamic = function () {
  27614. return this._dynamic !== undefined;
  27615. };
  27616. /**
  27617. * The data cache on JS side.
  27618. */
  27619. UniformBuffer.prototype.getData = function () {
  27620. return this._bufferData;
  27621. };
  27622. /**
  27623. * The underlying WebGL Uniform buffer.
  27624. */
  27625. UniformBuffer.prototype.getBuffer = function () {
  27626. return this._buffer;
  27627. };
  27628. /**
  27629. * std140 layout specifies how to align data within an UBO structure.
  27630. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27631. * for specs.
  27632. */
  27633. UniformBuffer.prototype._fillAlignment = function (size) {
  27634. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27635. // and 4x4 matrices
  27636. // TODO : change if other types are used
  27637. var alignment;
  27638. if (size <= 2) {
  27639. alignment = size;
  27640. }
  27641. else {
  27642. alignment = 4;
  27643. }
  27644. if ((this._uniformLocationPointer % alignment) !== 0) {
  27645. var oldPointer = this._uniformLocationPointer;
  27646. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27647. var diff = this._uniformLocationPointer - oldPointer;
  27648. for (var i = 0; i < diff; i++) {
  27649. this._data.push(0);
  27650. }
  27651. }
  27652. };
  27653. /**
  27654. * Adds an uniform in the buffer.
  27655. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27656. * for the layout to be correct !
  27657. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27658. * @param {number|number[]} size Data size, or data directly.
  27659. */
  27660. UniformBuffer.prototype.addUniform = function (name, size) {
  27661. if (this._noUBO) {
  27662. return;
  27663. }
  27664. if (this._uniformLocations[name] !== undefined) {
  27665. // Already existing uniform
  27666. return;
  27667. }
  27668. // This function must be called in the order of the shader layout !
  27669. // size can be the size of the uniform, or data directly
  27670. var data;
  27671. if (size instanceof Array) {
  27672. data = size;
  27673. size = data.length;
  27674. }
  27675. else {
  27676. size = size;
  27677. data = [];
  27678. // Fill with zeros
  27679. for (var i = 0; i < size; i++) {
  27680. data.push(0);
  27681. }
  27682. }
  27683. this._fillAlignment(size);
  27684. this._uniformSizes[name] = size;
  27685. this._uniformLocations[name] = this._uniformLocationPointer;
  27686. this._uniformLocationPointer += size;
  27687. for (var i = 0; i < size; i++) {
  27688. this._data.push(data[i]);
  27689. }
  27690. this._needSync = true;
  27691. };
  27692. /**
  27693. * Wrapper for addUniform.
  27694. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27695. * @param {Matrix} mat A 4x4 matrix.
  27696. */
  27697. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27698. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27699. };
  27700. /**
  27701. * Wrapper for addUniform.
  27702. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27703. * @param {number} x
  27704. * @param {number} y
  27705. */
  27706. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27707. var temp = [x, y];
  27708. this.addUniform(name, temp);
  27709. };
  27710. /**
  27711. * Wrapper for addUniform.
  27712. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27713. * @param {number} x
  27714. * @param {number} y
  27715. * @param {number} z
  27716. */
  27717. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27718. var temp = [x, y, z];
  27719. this.addUniform(name, temp);
  27720. };
  27721. /**
  27722. * Wrapper for addUniform.
  27723. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27724. * @param {Color3} color
  27725. */
  27726. UniformBuffer.prototype.addColor3 = function (name, color) {
  27727. var temp = new Array();
  27728. color.toArray(temp);
  27729. this.addUniform(name, temp);
  27730. };
  27731. /**
  27732. * Wrapper for addUniform.
  27733. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27734. * @param {Color3} color
  27735. * @param {number} alpha
  27736. */
  27737. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27738. var temp = new Array();
  27739. color.toArray(temp);
  27740. temp.push(alpha);
  27741. this.addUniform(name, temp);
  27742. };
  27743. /**
  27744. * Wrapper for addUniform.
  27745. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27746. * @param {Vector3} vector
  27747. */
  27748. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27749. var temp = new Array();
  27750. vector.toArray(temp);
  27751. this.addUniform(name, temp);
  27752. };
  27753. /**
  27754. * Wrapper for addUniform.
  27755. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27756. */
  27757. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27758. this.addUniform(name, 12);
  27759. };
  27760. /**
  27761. * Wrapper for addUniform.
  27762. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27763. */
  27764. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27765. this.addUniform(name, 8);
  27766. };
  27767. /**
  27768. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27769. */
  27770. UniformBuffer.prototype.create = function () {
  27771. if (this._noUBO) {
  27772. return;
  27773. }
  27774. if (this._buffer) {
  27775. return; // nothing to do
  27776. }
  27777. // See spec, alignment must be filled as a vec4
  27778. this._fillAlignment(4);
  27779. this._bufferData = new Float32Array(this._data);
  27780. this._rebuild();
  27781. this._needSync = true;
  27782. };
  27783. UniformBuffer.prototype._rebuild = function () {
  27784. if (this._noUBO) {
  27785. return;
  27786. }
  27787. if (this._dynamic) {
  27788. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27789. }
  27790. else {
  27791. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27792. }
  27793. };
  27794. /**
  27795. * Updates the WebGL Uniform Buffer on the GPU.
  27796. * If the `dynamic` flag is set to true, no cache comparison is done.
  27797. * Otherwise, the buffer will be updated only if the cache differs.
  27798. */
  27799. UniformBuffer.prototype.update = function () {
  27800. if (!this._buffer) {
  27801. this.create();
  27802. return;
  27803. }
  27804. if (!this._dynamic && !this._needSync) {
  27805. return;
  27806. }
  27807. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27808. this._needSync = false;
  27809. };
  27810. /**
  27811. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  27812. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27813. * @param {number[]|Float32Array} data Flattened data
  27814. * @param {number} size Size of the data.
  27815. */
  27816. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  27817. var location = this._uniformLocations[uniformName];
  27818. if (location === undefined) {
  27819. if (this._buffer) {
  27820. // Cannot add an uniform if the buffer is already created
  27821. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  27822. return;
  27823. }
  27824. this.addUniform(uniformName, size);
  27825. location = this._uniformLocations[uniformName];
  27826. }
  27827. if (!this._buffer) {
  27828. this.create();
  27829. }
  27830. if (!this._dynamic) {
  27831. // Cache for static uniform buffers
  27832. var changed = false;
  27833. for (var i = 0; i < size; i++) {
  27834. if (this._bufferData[location + i] !== data[i]) {
  27835. changed = true;
  27836. this._bufferData[location + i] = data[i];
  27837. }
  27838. }
  27839. this._needSync = this._needSync || changed;
  27840. }
  27841. else {
  27842. // No cache for dynamic
  27843. for (var i = 0; i < size; i++) {
  27844. this._bufferData[location + i] = data[i];
  27845. }
  27846. }
  27847. };
  27848. // Update methods
  27849. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  27850. // To match std140, matrix must be realigned
  27851. for (var i = 0; i < 3; i++) {
  27852. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  27853. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  27854. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  27855. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27856. }
  27857. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  27858. };
  27859. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  27860. this._currentEffect.setMatrix3x3(name, matrix);
  27861. };
  27862. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  27863. this._currentEffect.setMatrix2x2(name, matrix);
  27864. };
  27865. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  27866. // To match std140, matrix must be realigned
  27867. for (var i = 0; i < 2; i++) {
  27868. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  27869. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  27870. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  27871. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27872. }
  27873. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  27874. };
  27875. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  27876. this._currentEffect.setFloat(name, x);
  27877. };
  27878. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  27879. UniformBuffer._tempBuffer[0] = x;
  27880. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  27881. };
  27882. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  27883. if (suffix === void 0) { suffix = ""; }
  27884. this._currentEffect.setFloat2(name + suffix, x, y);
  27885. };
  27886. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  27887. if (suffix === void 0) { suffix = ""; }
  27888. UniformBuffer._tempBuffer[0] = x;
  27889. UniformBuffer._tempBuffer[1] = y;
  27890. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  27891. };
  27892. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  27893. if (suffix === void 0) { suffix = ""; }
  27894. this._currentEffect.setFloat3(name + suffix, x, y, z);
  27895. };
  27896. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  27897. if (suffix === void 0) { suffix = ""; }
  27898. UniformBuffer._tempBuffer[0] = x;
  27899. UniformBuffer._tempBuffer[1] = y;
  27900. UniformBuffer._tempBuffer[2] = z;
  27901. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27902. };
  27903. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  27904. if (suffix === void 0) { suffix = ""; }
  27905. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  27906. };
  27907. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  27908. if (suffix === void 0) { suffix = ""; }
  27909. UniformBuffer._tempBuffer[0] = x;
  27910. UniformBuffer._tempBuffer[1] = y;
  27911. UniformBuffer._tempBuffer[2] = z;
  27912. UniformBuffer._tempBuffer[3] = w;
  27913. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27914. };
  27915. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  27916. this._currentEffect.setMatrix(name, mat);
  27917. };
  27918. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  27919. this.updateUniform(name, mat.toArray(), 16);
  27920. };
  27921. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  27922. this._currentEffect.setVector3(name, vector);
  27923. };
  27924. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  27925. vector.toArray(UniformBuffer._tempBuffer);
  27926. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27927. };
  27928. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  27929. this._currentEffect.setVector4(name, vector);
  27930. };
  27931. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  27932. vector.toArray(UniformBuffer._tempBuffer);
  27933. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27934. };
  27935. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  27936. if (suffix === void 0) { suffix = ""; }
  27937. this._currentEffect.setColor3(name + suffix, color);
  27938. };
  27939. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  27940. if (suffix === void 0) { suffix = ""; }
  27941. color.toArray(UniformBuffer._tempBuffer);
  27942. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27943. };
  27944. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  27945. if (suffix === void 0) { suffix = ""; }
  27946. this._currentEffect.setColor4(name + suffix, color, alpha);
  27947. };
  27948. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  27949. if (suffix === void 0) { suffix = ""; }
  27950. color.toArray(UniformBuffer._tempBuffer);
  27951. UniformBuffer._tempBuffer[3] = alpha;
  27952. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27953. };
  27954. /**
  27955. * Sets a sampler uniform on the effect.
  27956. * @param {string} name Name of the sampler.
  27957. * @param {Texture} texture
  27958. */
  27959. UniformBuffer.prototype.setTexture = function (name, texture) {
  27960. this._currentEffect.setTexture(name, texture);
  27961. };
  27962. /**
  27963. * Directly updates the value of the uniform in the cache AND on the GPU.
  27964. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27965. * @param {number[]|Float32Array} data Flattened data
  27966. */
  27967. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  27968. this.updateUniform(uniformName, data, data.length);
  27969. this.update();
  27970. };
  27971. /**
  27972. * Binds this uniform buffer to an effect.
  27973. * @param {Effect} effect
  27974. * @param {string} name Name of the uniform block in the shader.
  27975. */
  27976. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  27977. this._currentEffect = effect;
  27978. if (this._noUBO || !this._buffer) {
  27979. return;
  27980. }
  27981. effect.bindUniformBuffer(this._buffer, name);
  27982. };
  27983. /**
  27984. * Disposes the uniform buffer.
  27985. */
  27986. UniformBuffer.prototype.dispose = function () {
  27987. if (this._noUBO) {
  27988. return;
  27989. }
  27990. var index = this._engine._uniformBuffers.indexOf(this);
  27991. if (index !== -1) {
  27992. this._engine._uniformBuffers.splice(index, 1);
  27993. }
  27994. if (!this._buffer) {
  27995. return;
  27996. }
  27997. if (this._engine._releaseBuffer(this._buffer)) {
  27998. this._buffer = null;
  27999. }
  28000. };
  28001. // Pool for avoiding memory leaks
  28002. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28003. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28004. return UniformBuffer;
  28005. }());
  28006. BABYLON.UniformBuffer = UniformBuffer;
  28007. })(BABYLON || (BABYLON = {}));
  28008. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28009. var BABYLON;
  28010. (function (BABYLON) {
  28011. var PushMaterial = /** @class */ (function (_super) {
  28012. __extends(PushMaterial, _super);
  28013. function PushMaterial(name, scene) {
  28014. var _this = _super.call(this, name, scene) || this;
  28015. _this.storeEffectOnSubMeshes = true;
  28016. return _this;
  28017. }
  28018. PushMaterial.prototype.getEffect = function () {
  28019. return this._activeEffect;
  28020. };
  28021. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28022. if (!mesh) {
  28023. return false;
  28024. }
  28025. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28026. return true;
  28027. }
  28028. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28029. };
  28030. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28031. this._activeEffect.setMatrix("world", world);
  28032. };
  28033. PushMaterial.prototype.bind = function (world, mesh) {
  28034. if (!mesh) {
  28035. return;
  28036. }
  28037. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28038. };
  28039. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28040. if (effect === void 0) { effect = null; }
  28041. _super.prototype._afterBind.call(this, mesh);
  28042. this.getScene()._cachedEffect = effect;
  28043. };
  28044. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28045. if (visibility === void 0) { visibility = 1; }
  28046. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28047. };
  28048. return PushMaterial;
  28049. }(BABYLON.Material));
  28050. BABYLON.PushMaterial = PushMaterial;
  28051. })(BABYLON || (BABYLON = {}));
  28052. //# sourceMappingURL=babylon.pushMaterial.js.map
  28053. var BABYLON;
  28054. (function (BABYLON) {
  28055. var VertexData = /** @class */ (function () {
  28056. function VertexData() {
  28057. }
  28058. VertexData.prototype.set = function (data, kind) {
  28059. switch (kind) {
  28060. case BABYLON.VertexBuffer.PositionKind:
  28061. this.positions = data;
  28062. break;
  28063. case BABYLON.VertexBuffer.NormalKind:
  28064. this.normals = data;
  28065. break;
  28066. case BABYLON.VertexBuffer.TangentKind:
  28067. this.tangents = data;
  28068. break;
  28069. case BABYLON.VertexBuffer.UVKind:
  28070. this.uvs = data;
  28071. break;
  28072. case BABYLON.VertexBuffer.UV2Kind:
  28073. this.uvs2 = data;
  28074. break;
  28075. case BABYLON.VertexBuffer.UV3Kind:
  28076. this.uvs3 = data;
  28077. break;
  28078. case BABYLON.VertexBuffer.UV4Kind:
  28079. this.uvs4 = data;
  28080. break;
  28081. case BABYLON.VertexBuffer.UV5Kind:
  28082. this.uvs5 = data;
  28083. break;
  28084. case BABYLON.VertexBuffer.UV6Kind:
  28085. this.uvs6 = data;
  28086. break;
  28087. case BABYLON.VertexBuffer.ColorKind:
  28088. this.colors = data;
  28089. break;
  28090. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28091. this.matricesIndices = data;
  28092. break;
  28093. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28094. this.matricesWeights = data;
  28095. break;
  28096. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28097. this.matricesIndicesExtra = data;
  28098. break;
  28099. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28100. this.matricesWeightsExtra = data;
  28101. break;
  28102. }
  28103. };
  28104. /**
  28105. * Associates the vertexData to the passed Mesh.
  28106. * Sets it as updatable or not (default `false`).
  28107. * Returns the VertexData.
  28108. */
  28109. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28110. this._applyTo(mesh, updatable);
  28111. return this;
  28112. };
  28113. /**
  28114. * Associates the vertexData to the passed Geometry.
  28115. * Sets it as updatable or not (default `false`).
  28116. * Returns the VertexData.
  28117. */
  28118. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28119. this._applyTo(geometry, updatable);
  28120. return this;
  28121. };
  28122. /**
  28123. * Updates the associated mesh.
  28124. * Returns the VertexData.
  28125. */
  28126. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28127. this._update(mesh);
  28128. return this;
  28129. };
  28130. /**
  28131. * Updates the associated geometry.
  28132. * Returns the VertexData.
  28133. */
  28134. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28135. this._update(geometry);
  28136. return this;
  28137. };
  28138. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28139. if (updatable === void 0) { updatable = false; }
  28140. if (this.positions) {
  28141. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28142. }
  28143. if (this.normals) {
  28144. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28145. }
  28146. if (this.tangents) {
  28147. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28148. }
  28149. if (this.uvs) {
  28150. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28151. }
  28152. if (this.uvs2) {
  28153. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28154. }
  28155. if (this.uvs3) {
  28156. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28157. }
  28158. if (this.uvs4) {
  28159. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28160. }
  28161. if (this.uvs5) {
  28162. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28163. }
  28164. if (this.uvs6) {
  28165. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28166. }
  28167. if (this.colors) {
  28168. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28169. }
  28170. if (this.matricesIndices) {
  28171. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28172. }
  28173. if (this.matricesWeights) {
  28174. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28175. }
  28176. if (this.matricesIndicesExtra) {
  28177. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28178. }
  28179. if (this.matricesWeightsExtra) {
  28180. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28181. }
  28182. if (this.indices) {
  28183. meshOrGeometry.setIndices(this.indices, null, updatable);
  28184. }
  28185. return this;
  28186. };
  28187. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28188. if (this.positions) {
  28189. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28190. }
  28191. if (this.normals) {
  28192. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28193. }
  28194. if (this.tangents) {
  28195. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28196. }
  28197. if (this.uvs) {
  28198. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28199. }
  28200. if (this.uvs2) {
  28201. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28202. }
  28203. if (this.uvs3) {
  28204. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28205. }
  28206. if (this.uvs4) {
  28207. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28208. }
  28209. if (this.uvs5) {
  28210. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28211. }
  28212. if (this.uvs6) {
  28213. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28214. }
  28215. if (this.colors) {
  28216. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28217. }
  28218. if (this.matricesIndices) {
  28219. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28220. }
  28221. if (this.matricesWeights) {
  28222. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28223. }
  28224. if (this.matricesIndicesExtra) {
  28225. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28226. }
  28227. if (this.matricesWeightsExtra) {
  28228. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28229. }
  28230. if (this.indices) {
  28231. meshOrGeometry.setIndices(this.indices, null);
  28232. }
  28233. return this;
  28234. };
  28235. /**
  28236. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28237. * Returns the VertexData.
  28238. */
  28239. VertexData.prototype.transform = function (matrix) {
  28240. var transformed = BABYLON.Vector3.Zero();
  28241. var index;
  28242. if (this.positions) {
  28243. var position = BABYLON.Vector3.Zero();
  28244. for (index = 0; index < this.positions.length; index += 3) {
  28245. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28246. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28247. this.positions[index] = transformed.x;
  28248. this.positions[index + 1] = transformed.y;
  28249. this.positions[index + 2] = transformed.z;
  28250. }
  28251. }
  28252. if (this.normals) {
  28253. var normal = BABYLON.Vector3.Zero();
  28254. for (index = 0; index < this.normals.length; index += 3) {
  28255. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28256. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28257. this.normals[index] = transformed.x;
  28258. this.normals[index + 1] = transformed.y;
  28259. this.normals[index + 2] = transformed.z;
  28260. }
  28261. }
  28262. if (this.tangents) {
  28263. var tangent = BABYLON.Vector4.Zero();
  28264. var tangentTransformed = BABYLON.Vector4.Zero();
  28265. for (index = 0; index < this.tangents.length; index += 4) {
  28266. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28267. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28268. this.tangents[index] = tangentTransformed.x;
  28269. this.tangents[index + 1] = tangentTransformed.y;
  28270. this.tangents[index + 2] = tangentTransformed.z;
  28271. this.tangents[index + 3] = tangentTransformed.w;
  28272. }
  28273. }
  28274. return this;
  28275. };
  28276. /**
  28277. * Merges the passed VertexData into the current one.
  28278. * Returns the modified VertexData.
  28279. */
  28280. VertexData.prototype.merge = function (other, options) {
  28281. options = options || {};
  28282. if (other.indices) {
  28283. if (!this.indices) {
  28284. this.indices = [];
  28285. }
  28286. var offset = this.positions ? this.positions.length / 3 : 0;
  28287. for (var index = 0; index < other.indices.length; index++) {
  28288. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28289. this.indices.push(other.indices[index] + offset);
  28290. }
  28291. }
  28292. this.positions = this._mergeElement(this.positions, other.positions);
  28293. if (!this.positions) {
  28294. return this;
  28295. }
  28296. var count = this.positions.length / 3;
  28297. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28298. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28299. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28300. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28301. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28302. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28303. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28304. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28305. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28306. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28307. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28308. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28309. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28310. return this;
  28311. };
  28312. VertexData.prototype._mergeElement = function (source, other, length) {
  28313. if (length === void 0) { length = 0; }
  28314. if (!other && !source) {
  28315. return null;
  28316. }
  28317. if (!other) {
  28318. return this._mergeElement(source, new Float32Array(source.length), length);
  28319. }
  28320. if (!source) {
  28321. if (length === 0 || length === other.length) {
  28322. return other;
  28323. }
  28324. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28325. }
  28326. var len = other.length + source.length;
  28327. var isSrcTypedArray = source instanceof Float32Array;
  28328. var isOthTypedArray = other instanceof Float32Array;
  28329. // use non-loop method when the source is Float32Array
  28330. if (isSrcTypedArray) {
  28331. var ret32 = new Float32Array(len);
  28332. ret32.set(source);
  28333. ret32.set(other, source.length);
  28334. return ret32;
  28335. // source is number[], when other is also use concat
  28336. }
  28337. else if (!isOthTypedArray) {
  28338. return source.concat(other);
  28339. // source is a number[], but other is a Float32Array, loop required
  28340. }
  28341. else {
  28342. var ret = source.slice(0); // copy source to a separate array
  28343. for (var i = 0, len = other.length; i < len; i++) {
  28344. ret.push(other[i]);
  28345. }
  28346. return ret;
  28347. }
  28348. };
  28349. /**
  28350. * Serializes the VertexData.
  28351. * Returns a serialized object.
  28352. */
  28353. VertexData.prototype.serialize = function () {
  28354. var serializationObject = this.serialize();
  28355. if (this.positions) {
  28356. serializationObject.positions = this.positions;
  28357. }
  28358. if (this.normals) {
  28359. serializationObject.normals = this.normals;
  28360. }
  28361. if (this.tangents) {
  28362. serializationObject.tangents = this.tangents;
  28363. }
  28364. if (this.uvs) {
  28365. serializationObject.uvs = this.uvs;
  28366. }
  28367. if (this.uvs2) {
  28368. serializationObject.uvs2 = this.uvs2;
  28369. }
  28370. if (this.uvs3) {
  28371. serializationObject.uvs3 = this.uvs3;
  28372. }
  28373. if (this.uvs4) {
  28374. serializationObject.uvs4 = this.uvs4;
  28375. }
  28376. if (this.uvs5) {
  28377. serializationObject.uvs5 = this.uvs5;
  28378. }
  28379. if (this.uvs6) {
  28380. serializationObject.uvs6 = this.uvs6;
  28381. }
  28382. if (this.colors) {
  28383. serializationObject.colors = this.colors;
  28384. }
  28385. if (this.matricesIndices) {
  28386. serializationObject.matricesIndices = this.matricesIndices;
  28387. serializationObject.matricesIndices._isExpanded = true;
  28388. }
  28389. if (this.matricesWeights) {
  28390. serializationObject.matricesWeights = this.matricesWeights;
  28391. }
  28392. if (this.matricesIndicesExtra) {
  28393. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28394. serializationObject.matricesIndicesExtra._isExpanded = true;
  28395. }
  28396. if (this.matricesWeightsExtra) {
  28397. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28398. }
  28399. serializationObject.indices = this.indices;
  28400. return serializationObject;
  28401. };
  28402. // Statics
  28403. /**
  28404. * Returns the object VertexData associated to the passed mesh.
  28405. */
  28406. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28407. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28408. };
  28409. /**
  28410. * Returns the object VertexData associated to the passed geometry.
  28411. */
  28412. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28413. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28414. };
  28415. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28416. var result = new VertexData();
  28417. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28418. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28419. }
  28420. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28421. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28422. }
  28423. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28424. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28425. }
  28426. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28427. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28428. }
  28429. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28430. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28431. }
  28432. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28433. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28434. }
  28435. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28436. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28437. }
  28438. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28439. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28440. }
  28441. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28442. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28443. }
  28444. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28445. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28446. }
  28447. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28448. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28449. }
  28450. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28451. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28452. }
  28453. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28454. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28455. }
  28456. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28457. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28458. }
  28459. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28460. return result;
  28461. };
  28462. /**
  28463. * Creates the vertexData of the Ribbon.
  28464. */
  28465. VertexData.CreateRibbon = function (options) {
  28466. var pathArray = options.pathArray;
  28467. var closeArray = options.closeArray || false;
  28468. var closePath = options.closePath || false;
  28469. var invertUV = options.invertUV || false;
  28470. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28471. var offset = options.offset || defaultOffset;
  28472. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28473. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28474. var customUV = options.uvs;
  28475. var customColors = options.colors;
  28476. var positions = [];
  28477. var indices = [];
  28478. var normals = [];
  28479. var uvs = [];
  28480. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28481. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28482. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28483. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28484. var minlg; // minimal length among all paths from pathArray
  28485. var lg = []; // array of path lengths : nb of vertex per path
  28486. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28487. var p; // path iterator
  28488. var i; // point iterator
  28489. var j; // point iterator
  28490. // if single path in pathArray
  28491. if (pathArray.length < 2) {
  28492. var ar1 = [];
  28493. var ar2 = [];
  28494. for (i = 0; i < pathArray[0].length - offset; i++) {
  28495. ar1.push(pathArray[0][i]);
  28496. ar2.push(pathArray[0][i + offset]);
  28497. }
  28498. pathArray = [ar1, ar2];
  28499. }
  28500. // positions and horizontal distances (u)
  28501. var idc = 0;
  28502. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  28503. var path;
  28504. var l;
  28505. minlg = pathArray[0].length;
  28506. var vectlg;
  28507. var dist;
  28508. for (p = 0; p < pathArray.length; p++) {
  28509. uTotalDistance[p] = 0;
  28510. us[p] = [0];
  28511. path = pathArray[p];
  28512. l = path.length;
  28513. minlg = (minlg < l) ? minlg : l;
  28514. j = 0;
  28515. while (j < l) {
  28516. positions.push(path[j].x, path[j].y, path[j].z);
  28517. if (j > 0) {
  28518. vectlg = path[j].subtract(path[j - 1]).length();
  28519. dist = vectlg + uTotalDistance[p];
  28520. us[p].push(dist);
  28521. uTotalDistance[p] = dist;
  28522. }
  28523. j++;
  28524. }
  28525. if (closePath) {
  28526. j--;
  28527. positions.push(path[0].x, path[0].y, path[0].z);
  28528. vectlg = path[j].subtract(path[0]).length();
  28529. dist = vectlg + uTotalDistance[p];
  28530. us[p].push(dist);
  28531. uTotalDistance[p] = dist;
  28532. }
  28533. lg[p] = l + closePathCorr;
  28534. idx[p] = idc;
  28535. idc += (l + closePathCorr);
  28536. }
  28537. // vertical distances (v)
  28538. var path1;
  28539. var path2;
  28540. var vertex1 = null;
  28541. var vertex2 = null;
  28542. for (i = 0; i < minlg + closePathCorr; i++) {
  28543. vTotalDistance[i] = 0;
  28544. vs[i] = [0];
  28545. for (p = 0; p < pathArray.length - 1; p++) {
  28546. path1 = pathArray[p];
  28547. path2 = pathArray[p + 1];
  28548. if (i === minlg) {
  28549. vertex1 = path1[0];
  28550. vertex2 = path2[0];
  28551. }
  28552. else {
  28553. vertex1 = path1[i];
  28554. vertex2 = path2[i];
  28555. }
  28556. vectlg = vertex2.subtract(vertex1).length();
  28557. dist = vectlg + vTotalDistance[i];
  28558. vs[i].push(dist);
  28559. vTotalDistance[i] = dist;
  28560. }
  28561. if (closeArray && vertex2 && vertex1) {
  28562. path1 = pathArray[p];
  28563. path2 = pathArray[0];
  28564. if (i === minlg) {
  28565. vertex2 = path2[0];
  28566. }
  28567. vectlg = vertex2.subtract(vertex1).length();
  28568. dist = vectlg + vTotalDistance[i];
  28569. vTotalDistance[i] = dist;
  28570. }
  28571. }
  28572. // uvs
  28573. var u;
  28574. var v;
  28575. if (customUV) {
  28576. for (p = 0; p < customUV.length; p++) {
  28577. uvs.push(customUV[p].x, customUV[p].y);
  28578. }
  28579. }
  28580. else {
  28581. for (p = 0; p < pathArray.length; p++) {
  28582. for (i = 0; i < minlg + closePathCorr; i++) {
  28583. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  28584. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  28585. if (invertUV) {
  28586. uvs.push(v, u);
  28587. }
  28588. else {
  28589. uvs.push(u, v);
  28590. }
  28591. }
  28592. }
  28593. }
  28594. // indices
  28595. p = 0; // path index
  28596. var pi = 0; // positions array index
  28597. var l1 = lg[p] - 1; // path1 length
  28598. var l2 = lg[p + 1] - 1; // path2 length
  28599. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28600. var shft = idx[1] - idx[0]; // shift
  28601. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28602. while (pi <= min && p < path1nb) {
  28603. // 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
  28604. indices.push(pi, pi + shft, pi + 1);
  28605. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28606. pi += 1;
  28607. if (pi === min) {
  28608. p++;
  28609. if (p === lg.length - 1) {
  28610. shft = idx[0] - idx[p];
  28611. l1 = lg[p] - 1;
  28612. l2 = lg[0] - 1;
  28613. }
  28614. else {
  28615. shft = idx[p + 1] - idx[p];
  28616. l1 = lg[p] - 1;
  28617. l2 = lg[p + 1] - 1;
  28618. }
  28619. pi = idx[p];
  28620. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28621. }
  28622. }
  28623. // normals
  28624. VertexData.ComputeNormals(positions, indices, normals);
  28625. if (closePath) {
  28626. var indexFirst = 0;
  28627. var indexLast = 0;
  28628. for (p = 0; p < pathArray.length; p++) {
  28629. indexFirst = idx[p] * 3;
  28630. if (p + 1 < pathArray.length) {
  28631. indexLast = (idx[p + 1] - 1) * 3;
  28632. }
  28633. else {
  28634. indexLast = normals.length - 3;
  28635. }
  28636. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28637. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28638. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28639. normals[indexLast] = normals[indexFirst];
  28640. normals[indexLast + 1] = normals[indexFirst + 1];
  28641. normals[indexLast + 2] = normals[indexFirst + 2];
  28642. }
  28643. }
  28644. // sides
  28645. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28646. // Colors
  28647. var colors = null;
  28648. if (customColors) {
  28649. colors = new Float32Array(customColors.length * 4);
  28650. for (var c = 0; c < customColors.length; c++) {
  28651. colors[c * 4] = customColors[c].r;
  28652. colors[c * 4 + 1] = customColors[c].g;
  28653. colors[c * 4 + 2] = customColors[c].b;
  28654. colors[c * 4 + 3] = customColors[c].a;
  28655. }
  28656. }
  28657. // Result
  28658. var vertexData = new VertexData();
  28659. var positions32 = new Float32Array(positions);
  28660. var normals32 = new Float32Array(normals);
  28661. var uvs32 = new Float32Array(uvs);
  28662. vertexData.indices = indices;
  28663. vertexData.positions = positions32;
  28664. vertexData.normals = normals32;
  28665. vertexData.uvs = uvs32;
  28666. if (colors) {
  28667. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28668. }
  28669. if (closePath) {
  28670. vertexData._idx = idx;
  28671. }
  28672. return vertexData;
  28673. };
  28674. /**
  28675. * Creates the VertexData of the Box.
  28676. */
  28677. VertexData.CreateBox = function (options) {
  28678. var normalsSource = [
  28679. new BABYLON.Vector3(0, 0, 1),
  28680. new BABYLON.Vector3(0, 0, -1),
  28681. new BABYLON.Vector3(1, 0, 0),
  28682. new BABYLON.Vector3(-1, 0, 0),
  28683. new BABYLON.Vector3(0, 1, 0),
  28684. new BABYLON.Vector3(0, -1, 0)
  28685. ];
  28686. var indices = [];
  28687. var positions = [];
  28688. var normals = [];
  28689. var uvs = [];
  28690. var width = options.width || options.size || 1;
  28691. var height = options.height || options.size || 1;
  28692. var depth = options.depth || options.size || 1;
  28693. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28694. var faceUV = options.faceUV || new Array(6);
  28695. var faceColors = options.faceColors;
  28696. var colors = [];
  28697. // default face colors and UV if undefined
  28698. for (var f = 0; f < 6; f++) {
  28699. if (faceUV[f] === undefined) {
  28700. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28701. }
  28702. if (faceColors && faceColors[f] === undefined) {
  28703. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28704. }
  28705. }
  28706. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28707. // Create each face in turn.
  28708. for (var index = 0; index < normalsSource.length; index++) {
  28709. var normal = normalsSource[index];
  28710. // Get two vectors perpendicular to the face normal and to each other.
  28711. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28712. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28713. // Six indices (two triangles) per face.
  28714. var verticesLength = positions.length / 3;
  28715. indices.push(verticesLength);
  28716. indices.push(verticesLength + 1);
  28717. indices.push(verticesLength + 2);
  28718. indices.push(verticesLength);
  28719. indices.push(verticesLength + 2);
  28720. indices.push(verticesLength + 3);
  28721. // Four vertices per face.
  28722. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28723. positions.push(vertex.x, vertex.y, vertex.z);
  28724. normals.push(normal.x, normal.y, normal.z);
  28725. uvs.push(faceUV[index].z, faceUV[index].w);
  28726. if (faceColors) {
  28727. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28728. }
  28729. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28730. positions.push(vertex.x, vertex.y, vertex.z);
  28731. normals.push(normal.x, normal.y, normal.z);
  28732. uvs.push(faceUV[index].x, faceUV[index].w);
  28733. if (faceColors) {
  28734. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28735. }
  28736. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28737. positions.push(vertex.x, vertex.y, vertex.z);
  28738. normals.push(normal.x, normal.y, normal.z);
  28739. uvs.push(faceUV[index].x, faceUV[index].y);
  28740. if (faceColors) {
  28741. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28742. }
  28743. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28744. positions.push(vertex.x, vertex.y, vertex.z);
  28745. normals.push(normal.x, normal.y, normal.z);
  28746. uvs.push(faceUV[index].z, faceUV[index].y);
  28747. if (faceColors) {
  28748. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28749. }
  28750. }
  28751. // sides
  28752. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28753. // Result
  28754. var vertexData = new VertexData();
  28755. vertexData.indices = indices;
  28756. vertexData.positions = positions;
  28757. vertexData.normals = normals;
  28758. vertexData.uvs = uvs;
  28759. if (faceColors) {
  28760. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28761. vertexData.colors = totalColors;
  28762. }
  28763. return vertexData;
  28764. };
  28765. /**
  28766. * Creates the VertexData of the Sphere.
  28767. */
  28768. VertexData.CreateSphere = function (options) {
  28769. var segments = options.segments || 32;
  28770. var diameterX = options.diameterX || options.diameter || 1;
  28771. var diameterY = options.diameterY || options.diameter || 1;
  28772. var diameterZ = options.diameterZ || options.diameter || 1;
  28773. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28774. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28775. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28776. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28777. var totalZRotationSteps = 2 + segments;
  28778. var totalYRotationSteps = 2 * totalZRotationSteps;
  28779. var indices = [];
  28780. var positions = [];
  28781. var normals = [];
  28782. var uvs = [];
  28783. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28784. var normalizedZ = zRotationStep / totalZRotationSteps;
  28785. var angleZ = normalizedZ * Math.PI * slice;
  28786. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28787. var normalizedY = yRotationStep / totalYRotationSteps;
  28788. var angleY = normalizedY * Math.PI * 2 * arc;
  28789. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28790. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28791. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28792. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28793. var vertex = complete.multiply(radius);
  28794. var normal = complete.divide(radius).normalize();
  28795. positions.push(vertex.x, vertex.y, vertex.z);
  28796. normals.push(normal.x, normal.y, normal.z);
  28797. uvs.push(normalizedY, normalizedZ);
  28798. }
  28799. if (zRotationStep > 0) {
  28800. var verticesCount = positions.length / 3;
  28801. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28802. indices.push((firstIndex));
  28803. indices.push((firstIndex + 1));
  28804. indices.push(firstIndex + totalYRotationSteps + 1);
  28805. indices.push((firstIndex + totalYRotationSteps + 1));
  28806. indices.push((firstIndex + 1));
  28807. indices.push((firstIndex + totalYRotationSteps + 2));
  28808. }
  28809. }
  28810. }
  28811. // Sides
  28812. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28813. // Result
  28814. var vertexData = new VertexData();
  28815. vertexData.indices = indices;
  28816. vertexData.positions = positions;
  28817. vertexData.normals = normals;
  28818. vertexData.uvs = uvs;
  28819. return vertexData;
  28820. };
  28821. /**
  28822. * Creates the VertexData of the Cylinder or Cone.
  28823. */
  28824. VertexData.CreateCylinder = function (options) {
  28825. var height = options.height || 2;
  28826. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28827. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  28828. var tessellation = options.tessellation || 24;
  28829. var subdivisions = options.subdivisions || 1;
  28830. var hasRings = options.hasRings ? true : false;
  28831. var enclose = options.enclose ? true : false;
  28832. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28833. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28834. var faceUV = options.faceUV || new Array(3);
  28835. var faceColors = options.faceColors;
  28836. // default face colors and UV if undefined
  28837. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28838. var ringNb = (hasRings) ? subdivisions : 1;
  28839. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28840. var f;
  28841. for (f = 0; f < surfaceNb; f++) {
  28842. if (faceColors && faceColors[f] === undefined) {
  28843. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28844. }
  28845. }
  28846. for (f = 0; f < surfaceNb; f++) {
  28847. if (faceUV && faceUV[f] === undefined) {
  28848. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28849. }
  28850. }
  28851. var indices = new Array();
  28852. var positions = new Array();
  28853. var normals = new Array();
  28854. var uvs = new Array();
  28855. var colors = new Array();
  28856. var angle_step = Math.PI * 2 * arc / tessellation;
  28857. var angle;
  28858. var h;
  28859. var radius;
  28860. var tan = (diameterBottom - diameterTop) / 2 / height;
  28861. var ringVertex = BABYLON.Vector3.Zero();
  28862. var ringNormal = BABYLON.Vector3.Zero();
  28863. var ringFirstVertex = BABYLON.Vector3.Zero();
  28864. var ringFirstNormal = BABYLON.Vector3.Zero();
  28865. var quadNormal = BABYLON.Vector3.Zero();
  28866. var Y = BABYLON.Axis.Y;
  28867. // positions, normals, uvs
  28868. var i;
  28869. var j;
  28870. var r;
  28871. var ringIdx = 1;
  28872. var s = 1; // surface index
  28873. var cs = 0;
  28874. var v = 0;
  28875. for (i = 0; i <= subdivisions; i++) {
  28876. h = i / subdivisions;
  28877. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28878. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28879. for (r = 0; r < ringIdx; r++) {
  28880. if (hasRings) {
  28881. s += r;
  28882. }
  28883. if (enclose) {
  28884. s += 2 * r;
  28885. }
  28886. for (j = 0; j <= tessellation; j++) {
  28887. angle = j * angle_step;
  28888. // position
  28889. ringVertex.x = Math.cos(-angle) * radius;
  28890. ringVertex.y = -height / 2 + h * height;
  28891. ringVertex.z = Math.sin(-angle) * radius;
  28892. // normal
  28893. if (diameterTop === 0 && i === subdivisions) {
  28894. // if no top cap, reuse former normals
  28895. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28896. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28897. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28898. }
  28899. else {
  28900. ringNormal.x = ringVertex.x;
  28901. ringNormal.z = ringVertex.z;
  28902. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28903. ringNormal.normalize();
  28904. }
  28905. // keep first ring vertex values for enclose
  28906. if (j === 0) {
  28907. ringFirstVertex.copyFrom(ringVertex);
  28908. ringFirstNormal.copyFrom(ringNormal);
  28909. }
  28910. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28911. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28912. if (hasRings) {
  28913. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28914. }
  28915. else {
  28916. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28917. }
  28918. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28919. if (faceColors) {
  28920. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28921. }
  28922. }
  28923. // if enclose, add four vertices and their dedicated normals
  28924. if (arc !== 1 && enclose) {
  28925. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28926. positions.push(0, ringVertex.y, 0);
  28927. positions.push(0, ringVertex.y, 0);
  28928. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28929. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28930. quadNormal.normalize();
  28931. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28932. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28933. quadNormal.normalize();
  28934. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28935. if (hasRings) {
  28936. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28937. }
  28938. else {
  28939. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28940. }
  28941. uvs.push(faceUV[s + 1].x, v);
  28942. uvs.push(faceUV[s + 1].z, v);
  28943. if (hasRings) {
  28944. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28945. }
  28946. else {
  28947. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28948. }
  28949. uvs.push(faceUV[s + 2].x, v);
  28950. uvs.push(faceUV[s + 2].z, v);
  28951. if (faceColors) {
  28952. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28953. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28954. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28955. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28956. }
  28957. }
  28958. if (cs !== s) {
  28959. cs = s;
  28960. }
  28961. }
  28962. }
  28963. // indices
  28964. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28965. var s;
  28966. i = 0;
  28967. for (s = 0; s < subdivisions; s++) {
  28968. var i0 = 0;
  28969. var i1 = 0;
  28970. var i2 = 0;
  28971. var i3 = 0;
  28972. for (j = 0; j < tessellation; j++) {
  28973. i0 = i * (e + 1) + j;
  28974. i1 = (i + 1) * (e + 1) + j;
  28975. i2 = i * (e + 1) + (j + 1);
  28976. i3 = (i + 1) * (e + 1) + (j + 1);
  28977. indices.push(i0, i1, i2);
  28978. indices.push(i3, i2, i1);
  28979. }
  28980. if (arc !== 1 && enclose) {
  28981. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28982. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28983. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28984. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28985. }
  28986. i = (hasRings) ? (i + 2) : (i + 1);
  28987. }
  28988. // Caps
  28989. var createCylinderCap = function (isTop) {
  28990. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28991. if (radius === 0) {
  28992. return;
  28993. }
  28994. // Cap positions, normals & uvs
  28995. var angle;
  28996. var circleVector;
  28997. var i;
  28998. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28999. var c = null;
  29000. if (faceColors) {
  29001. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29002. }
  29003. // cap center
  29004. var vbase = positions.length / 3;
  29005. var offset = isTop ? height / 2 : -height / 2;
  29006. var center = new BABYLON.Vector3(0, offset, 0);
  29007. positions.push(center.x, center.y, center.z);
  29008. normals.push(0, isTop ? 1 : -1, 0);
  29009. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29010. if (c) {
  29011. colors.push(c.r, c.g, c.b, c.a);
  29012. }
  29013. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29014. for (i = 0; i <= tessellation; i++) {
  29015. angle = Math.PI * 2 * i * arc / tessellation;
  29016. var cos = Math.cos(-angle);
  29017. var sin = Math.sin(-angle);
  29018. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29019. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29020. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29021. normals.push(0, isTop ? 1 : -1, 0);
  29022. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29023. if (c) {
  29024. colors.push(c.r, c.g, c.b, c.a);
  29025. }
  29026. }
  29027. // Cap indices
  29028. for (i = 0; i < tessellation; i++) {
  29029. if (!isTop) {
  29030. indices.push(vbase);
  29031. indices.push(vbase + (i + 1));
  29032. indices.push(vbase + (i + 2));
  29033. }
  29034. else {
  29035. indices.push(vbase);
  29036. indices.push(vbase + (i + 2));
  29037. indices.push(vbase + (i + 1));
  29038. }
  29039. }
  29040. };
  29041. // add caps to geometry
  29042. createCylinderCap(false);
  29043. createCylinderCap(true);
  29044. // Sides
  29045. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29046. var vertexData = new VertexData();
  29047. vertexData.indices = indices;
  29048. vertexData.positions = positions;
  29049. vertexData.normals = normals;
  29050. vertexData.uvs = uvs;
  29051. if (faceColors) {
  29052. vertexData.colors = colors;
  29053. }
  29054. return vertexData;
  29055. };
  29056. /**
  29057. * Creates the VertexData of the Torus.
  29058. */
  29059. VertexData.CreateTorus = function (options) {
  29060. var indices = [];
  29061. var positions = [];
  29062. var normals = [];
  29063. var uvs = [];
  29064. var diameter = options.diameter || 1;
  29065. var thickness = options.thickness || 0.5;
  29066. var tessellation = options.tessellation || 16;
  29067. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29068. var stride = tessellation + 1;
  29069. for (var i = 0; i <= tessellation; i++) {
  29070. var u = i / tessellation;
  29071. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29072. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29073. for (var j = 0; j <= tessellation; j++) {
  29074. var v = 1 - j / tessellation;
  29075. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29076. var dx = Math.cos(innerAngle);
  29077. var dy = Math.sin(innerAngle);
  29078. // Create a vertex.
  29079. var normal = new BABYLON.Vector3(dx, dy, 0);
  29080. var position = normal.scale(thickness / 2);
  29081. var textureCoordinate = new BABYLON.Vector2(u, v);
  29082. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29083. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29084. positions.push(position.x, position.y, position.z);
  29085. normals.push(normal.x, normal.y, normal.z);
  29086. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29087. // And create indices for two triangles.
  29088. var nextI = (i + 1) % stride;
  29089. var nextJ = (j + 1) % stride;
  29090. indices.push(i * stride + j);
  29091. indices.push(i * stride + nextJ);
  29092. indices.push(nextI * stride + j);
  29093. indices.push(i * stride + nextJ);
  29094. indices.push(nextI * stride + nextJ);
  29095. indices.push(nextI * stride + j);
  29096. }
  29097. }
  29098. // Sides
  29099. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29100. // Result
  29101. var vertexData = new VertexData();
  29102. vertexData.indices = indices;
  29103. vertexData.positions = positions;
  29104. vertexData.normals = normals;
  29105. vertexData.uvs = uvs;
  29106. return vertexData;
  29107. };
  29108. /**
  29109. * Creates the VertexData of the LineSystem.
  29110. */
  29111. VertexData.CreateLineSystem = function (options) {
  29112. var indices = [];
  29113. var positions = [];
  29114. var lines = options.lines;
  29115. var idx = 0;
  29116. for (var l = 0; l < lines.length; l++) {
  29117. var points = lines[l];
  29118. for (var index = 0; index < points.length; index++) {
  29119. positions.push(points[index].x, points[index].y, points[index].z);
  29120. if (index > 0) {
  29121. indices.push(idx - 1);
  29122. indices.push(idx);
  29123. }
  29124. idx++;
  29125. }
  29126. }
  29127. var vertexData = new VertexData();
  29128. vertexData.indices = indices;
  29129. vertexData.positions = positions;
  29130. return vertexData;
  29131. };
  29132. /**
  29133. * Create the VertexData of the DashedLines.
  29134. */
  29135. VertexData.CreateDashedLines = function (options) {
  29136. var dashSize = options.dashSize || 3;
  29137. var gapSize = options.gapSize || 1;
  29138. var dashNb = options.dashNb || 200;
  29139. var points = options.points;
  29140. var positions = new Array();
  29141. var indices = new Array();
  29142. var curvect = BABYLON.Vector3.Zero();
  29143. var lg = 0;
  29144. var nb = 0;
  29145. var shft = 0;
  29146. var dashshft = 0;
  29147. var curshft = 0;
  29148. var idx = 0;
  29149. var i = 0;
  29150. for (i = 0; i < points.length - 1; i++) {
  29151. points[i + 1].subtractToRef(points[i], curvect);
  29152. lg += curvect.length();
  29153. }
  29154. shft = lg / dashNb;
  29155. dashshft = dashSize * shft / (dashSize + gapSize);
  29156. for (i = 0; i < points.length - 1; i++) {
  29157. points[i + 1].subtractToRef(points[i], curvect);
  29158. nb = Math.floor(curvect.length() / shft);
  29159. curvect.normalize();
  29160. for (var j = 0; j < nb; j++) {
  29161. curshft = shft * j;
  29162. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29163. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29164. indices.push(idx, idx + 1);
  29165. idx += 2;
  29166. }
  29167. }
  29168. // Result
  29169. var vertexData = new VertexData();
  29170. vertexData.positions = positions;
  29171. vertexData.indices = indices;
  29172. return vertexData;
  29173. };
  29174. /**
  29175. * Creates the VertexData of the Ground.
  29176. */
  29177. VertexData.CreateGround = function (options) {
  29178. var indices = [];
  29179. var positions = [];
  29180. var normals = [];
  29181. var uvs = [];
  29182. var row, col;
  29183. var width = options.width || 1;
  29184. var height = options.height || 1;
  29185. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29186. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29187. for (row = 0; row <= subdivisionsY; row++) {
  29188. for (col = 0; col <= subdivisionsX; col++) {
  29189. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29190. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29191. positions.push(position.x, position.y, position.z);
  29192. normals.push(normal.x, normal.y, normal.z);
  29193. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29194. }
  29195. }
  29196. for (row = 0; row < subdivisionsY; row++) {
  29197. for (col = 0; col < subdivisionsX; col++) {
  29198. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29199. indices.push(col + 1 + row * (subdivisionsX + 1));
  29200. indices.push(col + row * (subdivisionsX + 1));
  29201. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29202. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29203. indices.push(col + row * (subdivisionsX + 1));
  29204. }
  29205. }
  29206. // Result
  29207. var vertexData = new VertexData();
  29208. vertexData.indices = indices;
  29209. vertexData.positions = positions;
  29210. vertexData.normals = normals;
  29211. vertexData.uvs = uvs;
  29212. return vertexData;
  29213. };
  29214. /**
  29215. * Creates the VertexData of the TiledGround.
  29216. */
  29217. VertexData.CreateTiledGround = function (options) {
  29218. var xmin = options.xmin || -1.0;
  29219. var zmin = options.zmin || -1.0;
  29220. var xmax = options.xmax || 1.0;
  29221. var zmax = options.zmax || 1.0;
  29222. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29223. var precision = options.precision || { w: 1, h: 1 };
  29224. var indices = new Array();
  29225. var positions = new Array();
  29226. var normals = new Array();
  29227. var uvs = new Array();
  29228. var row, col, tileRow, tileCol;
  29229. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29230. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29231. precision.w = (precision.w < 1) ? 1 : precision.w;
  29232. precision.h = (precision.h < 1) ? 1 : precision.h;
  29233. var tileSize = {
  29234. 'w': (xmax - xmin) / subdivisions.w,
  29235. 'h': (zmax - zmin) / subdivisions.h
  29236. };
  29237. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29238. // Indices
  29239. var base = positions.length / 3;
  29240. var rowLength = precision.w + 1;
  29241. for (row = 0; row < precision.h; row++) {
  29242. for (col = 0; col < precision.w; col++) {
  29243. var square = [
  29244. base + col + row * rowLength,
  29245. base + (col + 1) + row * rowLength,
  29246. base + (col + 1) + (row + 1) * rowLength,
  29247. base + col + (row + 1) * rowLength
  29248. ];
  29249. indices.push(square[1]);
  29250. indices.push(square[2]);
  29251. indices.push(square[3]);
  29252. indices.push(square[0]);
  29253. indices.push(square[1]);
  29254. indices.push(square[3]);
  29255. }
  29256. }
  29257. // Position, normals and uvs
  29258. var position = BABYLON.Vector3.Zero();
  29259. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29260. for (row = 0; row <= precision.h; row++) {
  29261. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29262. for (col = 0; col <= precision.w; col++) {
  29263. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29264. position.y = 0;
  29265. positions.push(position.x, position.y, position.z);
  29266. normals.push(normal.x, normal.y, normal.z);
  29267. uvs.push(col / precision.w, row / precision.h);
  29268. }
  29269. }
  29270. }
  29271. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29272. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29273. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29274. }
  29275. }
  29276. // Result
  29277. var vertexData = new VertexData();
  29278. vertexData.indices = indices;
  29279. vertexData.positions = positions;
  29280. vertexData.normals = normals;
  29281. vertexData.uvs = uvs;
  29282. return vertexData;
  29283. };
  29284. /**
  29285. * Creates the VertexData of the Ground designed from a heightmap.
  29286. */
  29287. VertexData.CreateGroundFromHeightMap = function (options) {
  29288. var indices = [];
  29289. var positions = [];
  29290. var normals = [];
  29291. var uvs = [];
  29292. var row, col;
  29293. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29294. // Vertices
  29295. for (row = 0; row <= options.subdivisions; row++) {
  29296. for (col = 0; col <= options.subdivisions; col++) {
  29297. 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));
  29298. // Compute height
  29299. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29300. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29301. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29302. var r = options.buffer[pos] / 255.0;
  29303. var g = options.buffer[pos + 1] / 255.0;
  29304. var b = options.buffer[pos + 2] / 255.0;
  29305. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29306. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29307. // Add vertex
  29308. positions.push(position.x, position.y, position.z);
  29309. normals.push(0, 0, 0);
  29310. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29311. }
  29312. }
  29313. // Indices
  29314. for (row = 0; row < options.subdivisions; row++) {
  29315. for (col = 0; col < options.subdivisions; col++) {
  29316. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29317. indices.push(col + 1 + row * (options.subdivisions + 1));
  29318. indices.push(col + row * (options.subdivisions + 1));
  29319. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29320. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29321. indices.push(col + row * (options.subdivisions + 1));
  29322. }
  29323. }
  29324. // Normals
  29325. VertexData.ComputeNormals(positions, indices, normals);
  29326. // Result
  29327. var vertexData = new VertexData();
  29328. vertexData.indices = indices;
  29329. vertexData.positions = positions;
  29330. vertexData.normals = normals;
  29331. vertexData.uvs = uvs;
  29332. return vertexData;
  29333. };
  29334. /**
  29335. * Creates the VertexData of the Plane.
  29336. */
  29337. VertexData.CreatePlane = function (options) {
  29338. var indices = [];
  29339. var positions = [];
  29340. var normals = [];
  29341. var uvs = [];
  29342. var width = options.width || options.size || 1;
  29343. var height = options.height || options.size || 1;
  29344. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29345. // Vertices
  29346. var halfWidth = width / 2.0;
  29347. var halfHeight = height / 2.0;
  29348. positions.push(-halfWidth, -halfHeight, 0);
  29349. normals.push(0, 0, -1.0);
  29350. uvs.push(0.0, 0.0);
  29351. positions.push(halfWidth, -halfHeight, 0);
  29352. normals.push(0, 0, -1.0);
  29353. uvs.push(1.0, 0.0);
  29354. positions.push(halfWidth, halfHeight, 0);
  29355. normals.push(0, 0, -1.0);
  29356. uvs.push(1.0, 1.0);
  29357. positions.push(-halfWidth, halfHeight, 0);
  29358. normals.push(0, 0, -1.0);
  29359. uvs.push(0.0, 1.0);
  29360. // Indices
  29361. indices.push(0);
  29362. indices.push(1);
  29363. indices.push(2);
  29364. indices.push(0);
  29365. indices.push(2);
  29366. indices.push(3);
  29367. // Sides
  29368. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29369. // Result
  29370. var vertexData = new VertexData();
  29371. vertexData.indices = indices;
  29372. vertexData.positions = positions;
  29373. vertexData.normals = normals;
  29374. vertexData.uvs = uvs;
  29375. return vertexData;
  29376. };
  29377. /**
  29378. * Creates the VertexData of the Disc or regular Polygon.
  29379. */
  29380. VertexData.CreateDisc = function (options) {
  29381. var positions = new Array();
  29382. var indices = new Array();
  29383. var normals = new Array();
  29384. var uvs = new Array();
  29385. var radius = options.radius || 0.5;
  29386. var tessellation = options.tessellation || 64;
  29387. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29388. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29389. // positions and uvs
  29390. positions.push(0, 0, 0); // disc center first
  29391. uvs.push(0.5, 0.5);
  29392. var theta = Math.PI * 2 * arc;
  29393. var step = theta / tessellation;
  29394. for (var a = 0; a < theta; a += step) {
  29395. var x = Math.cos(a);
  29396. var y = Math.sin(a);
  29397. var u = (x + 1) / 2;
  29398. var v = (1 - y) / 2;
  29399. positions.push(radius * x, radius * y, 0);
  29400. uvs.push(u, v);
  29401. }
  29402. if (arc === 1) {
  29403. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29404. uvs.push(uvs[2], uvs[3]);
  29405. }
  29406. //indices
  29407. var vertexNb = positions.length / 3;
  29408. for (var i = 1; i < vertexNb - 1; i++) {
  29409. indices.push(i + 1, 0, i);
  29410. }
  29411. // result
  29412. VertexData.ComputeNormals(positions, indices, normals);
  29413. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  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. * Re-creates the VertexData of the Polygon for sideOrientation.
  29423. */
  29424. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29425. var faceUV = fUV || new Array(3);
  29426. var faceColors = fColors;
  29427. var colors = [];
  29428. // default face colors and UV if undefined
  29429. for (var f = 0; f < 3; f++) {
  29430. if (faceUV[f] === undefined) {
  29431. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29432. }
  29433. if (faceColors && faceColors[f] === undefined) {
  29434. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29435. }
  29436. }
  29437. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29438. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29439. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29440. var indices = polygon.getIndices();
  29441. // set face colours and textures
  29442. var idx = 0;
  29443. var face = 0;
  29444. for (var index = 0; index < normals.length; index += 3) {
  29445. //Edge Face no. 1
  29446. if (Math.abs(normals[index + 1]) < 0.001) {
  29447. face = 1;
  29448. }
  29449. //Top Face no. 0
  29450. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29451. face = 0;
  29452. }
  29453. //Bottom Face no. 2
  29454. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29455. face = 2;
  29456. }
  29457. idx = index / 3;
  29458. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29459. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29460. if (faceColors) {
  29461. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29462. }
  29463. }
  29464. // sides
  29465. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29466. // Result
  29467. var vertexData = new VertexData();
  29468. vertexData.indices = indices;
  29469. vertexData.positions = positions;
  29470. vertexData.normals = normals;
  29471. vertexData.uvs = uvs;
  29472. if (faceColors) {
  29473. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29474. vertexData.colors = totalColors;
  29475. }
  29476. return vertexData;
  29477. };
  29478. /**
  29479. * Creates the VertexData of the IcoSphere.
  29480. */
  29481. VertexData.CreateIcoSphere = function (options) {
  29482. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29483. var radius = options.radius || 1;
  29484. var flat = (options.flat === undefined) ? true : options.flat;
  29485. var subdivisions = options.subdivisions || 4;
  29486. var radiusX = options.radiusX || radius;
  29487. var radiusY = options.radiusY || radius;
  29488. var radiusZ = options.radiusZ || radius;
  29489. var t = (1 + Math.sqrt(5)) / 2;
  29490. // 12 vertex x,y,z
  29491. var ico_vertices = [
  29492. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29493. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29494. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29495. ];
  29496. // index of 3 vertex makes a face of icopshere
  29497. var ico_indices = [
  29498. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29499. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29500. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29501. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29502. ];
  29503. // vertex for uv have aliased position, not for UV
  29504. var vertices_unalias_id = [
  29505. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29506. // vertex alias
  29507. 0,
  29508. 2,
  29509. 3,
  29510. 3,
  29511. 3,
  29512. 4,
  29513. 7,
  29514. 8,
  29515. 9,
  29516. 9,
  29517. 10,
  29518. 11 // 23: B + 12
  29519. ];
  29520. // uv as integer step (not pixels !)
  29521. var ico_vertexuv = [
  29522. 5, 1, 3, 1, 6, 4, 0, 0,
  29523. 5, 3, 4, 2, 2, 2, 4, 0,
  29524. 2, 0, 1, 1, 6, 0, 6, 2,
  29525. // vertex alias (for same vertex on different faces)
  29526. 0, 4,
  29527. 3, 3,
  29528. 4, 4,
  29529. 3, 1,
  29530. 4, 2,
  29531. 4, 4,
  29532. 0, 2,
  29533. 1, 1,
  29534. 2, 2,
  29535. 3, 3,
  29536. 1, 3,
  29537. 2, 4 // 23: B + 12
  29538. ];
  29539. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29540. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29541. // First island of uv mapping
  29542. // v = 4h 3+ 2
  29543. // v = 3h 9+ 4
  29544. // v = 2h 9+ 5 B
  29545. // v = 1h 9 1 0
  29546. // v = 0h 3 8 7 A
  29547. // u = 0 1 2 3 4 5 6 *a
  29548. // Second island of uv mapping
  29549. // v = 4h 0+ B+ 4+
  29550. // v = 3h A+ 2+
  29551. // v = 2h 7+ 6 3+
  29552. // v = 1h 8+ 3+
  29553. // v = 0h
  29554. // u = 0 1 2 3 4 5 6 *a
  29555. // Face layout on texture UV mapping
  29556. // ============
  29557. // \ 4 /\ 16 / ======
  29558. // \ / \ / /\ 11 /
  29559. // \/ 7 \/ / \ /
  29560. // ======= / 10 \/
  29561. // /\ 17 /\ =======
  29562. // / \ / \ \ 15 /\
  29563. // / 8 \/ 12 \ \ / \
  29564. // ============ \/ 6 \
  29565. // \ 18 /\ ============
  29566. // \ / \ \ 5 /\ 0 /
  29567. // \/ 13 \ \ / \ /
  29568. // ======= \/ 1 \/
  29569. // =============
  29570. // /\ 19 /\ 2 /\
  29571. // / \ / \ / \
  29572. // / 14 \/ 9 \/ 3 \
  29573. // ===================
  29574. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29575. var ustep = 138 / 1024;
  29576. var vstep = 239 / 1024;
  29577. var uoffset = 60 / 1024;
  29578. var voffset = 26 / 1024;
  29579. // Second island should have margin, not to touch the first island
  29580. // avoid any borderline artefact in pixel rounding
  29581. var island_u_offset = -40 / 1024;
  29582. var island_v_offset = +20 / 1024;
  29583. // face is either island 0 or 1 :
  29584. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29585. var island = [
  29586. 0, 0, 0, 0, 1,
  29587. 0, 0, 1, 1, 0,
  29588. 0, 0, 1, 1, 0,
  29589. 0, 1, 1, 1, 0 // 15 - 19
  29590. ];
  29591. var indices = new Array();
  29592. var positions = new Array();
  29593. var normals = new Array();
  29594. var uvs = new Array();
  29595. var current_indice = 0;
  29596. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29597. var face_vertex_pos = new Array(3);
  29598. var face_vertex_uv = new Array(3);
  29599. var v012;
  29600. for (v012 = 0; v012 < 3; v012++) {
  29601. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29602. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29603. }
  29604. // create all with normals
  29605. for (var face = 0; face < 20; face++) {
  29606. // 3 vertex per face
  29607. for (v012 = 0; v012 < 3; v012++) {
  29608. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29609. var v_id = ico_indices[3 * face + v012];
  29610. // vertex have 3D position (x,y,z)
  29611. 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]);
  29612. // Normalize to get normal, then scale to radius
  29613. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29614. // uv Coordinates from vertex ID
  29615. 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);
  29616. }
  29617. // Subdivide the face (interpolate pos, norm, uv)
  29618. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29619. // - norm is linear interpolation of vertex corner normal
  29620. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29621. // - uv is linear interpolation
  29622. //
  29623. // Topology is as below for sub-divide by 2
  29624. // vertex shown as v0,v1,v2
  29625. // interp index is i1 to progress in range [v0,v1[
  29626. // interp index is i2 to progress in range [v0,v2[
  29627. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29628. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29629. //
  29630. //
  29631. // i2 v2
  29632. // ^ ^
  29633. // / / \
  29634. // / / \
  29635. // / / \
  29636. // / / (0,1) \
  29637. // / #---------\
  29638. // / / \ (0,0)'/ \
  29639. // / / \ / \
  29640. // / / \ / \
  29641. // / / (0,0) \ / (1,0) \
  29642. // / #---------#---------\
  29643. // v0 v1
  29644. //
  29645. // --------------------> i1
  29646. //
  29647. // interp of (i1,i2):
  29648. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29649. // along i1 : lerp(x0,x1, i1/(S-i2))
  29650. //
  29651. // centroid of triangle is needed to get help normal computation
  29652. // (c1,c2) are used for centroid location
  29653. var interp_vertex = function (i1, i2, c1, c2) {
  29654. // vertex is interpolated from
  29655. // - face_vertex_pos[0..2]
  29656. // - face_vertex_uv[0..2]
  29657. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29658. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29659. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29660. pos_interp.normalize();
  29661. var vertex_normal;
  29662. if (flat) {
  29663. // in flat mode, recalculate normal as face centroid normal
  29664. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29665. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29666. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29667. }
  29668. else {
  29669. // in smooth mode, recalculate normal from each single vertex position
  29670. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29671. }
  29672. // Vertex normal need correction due to X,Y,Z radius scaling
  29673. vertex_normal.x /= radiusX;
  29674. vertex_normal.y /= radiusY;
  29675. vertex_normal.z /= radiusZ;
  29676. vertex_normal.normalize();
  29677. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29678. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29679. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29680. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29681. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29682. uvs.push(uv_interp.x, uv_interp.y);
  29683. // push each vertex has member of a face
  29684. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29685. indices.push(current_indice);
  29686. current_indice++;
  29687. };
  29688. for (var i2 = 0; i2 < subdivisions; i2++) {
  29689. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29690. // face : (i1,i2) for /\ :
  29691. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29692. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29693. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29694. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29695. if (i1 + i2 + 1 < subdivisions) {
  29696. // face : (i1,i2)' for \/ :
  29697. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29698. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29699. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29700. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29701. }
  29702. }
  29703. }
  29704. }
  29705. // Sides
  29706. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29707. // Result
  29708. var vertexData = new VertexData();
  29709. vertexData.indices = indices;
  29710. vertexData.positions = positions;
  29711. vertexData.normals = normals;
  29712. vertexData.uvs = uvs;
  29713. return vertexData;
  29714. };
  29715. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29716. /**
  29717. * Creates the VertexData of the Polyhedron.
  29718. */
  29719. VertexData.CreatePolyhedron = function (options) {
  29720. // provided polyhedron types :
  29721. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29722. // 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)
  29723. var polyhedra = [];
  29724. 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]] };
  29725. 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]] };
  29726. polyhedra[2] = {
  29727. 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]],
  29728. 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]]
  29729. };
  29730. polyhedra[3] = {
  29731. 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]],
  29732. 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]]
  29733. };
  29734. polyhedra[4] = {
  29735. 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]],
  29736. 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]]
  29737. };
  29738. 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]] };
  29739. 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]] };
  29740. 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]] };
  29741. 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]] };
  29742. 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]] };
  29743. 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]] };
  29744. 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]] };
  29745. 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]] };
  29746. 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]] };
  29747. polyhedra[14] = {
  29748. 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]],
  29749. 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]]
  29750. };
  29751. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29752. var size = options.size;
  29753. var sizeX = options.sizeX || size || 1;
  29754. var sizeY = options.sizeY || size || 1;
  29755. var sizeZ = options.sizeZ || size || 1;
  29756. var data = options.custom || polyhedra[type];
  29757. var nbfaces = data.face.length;
  29758. var faceUV = options.faceUV || new Array(nbfaces);
  29759. var faceColors = options.faceColors;
  29760. var flat = (options.flat === undefined) ? true : options.flat;
  29761. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29762. var positions = new Array();
  29763. var indices = new Array();
  29764. var normals = new Array();
  29765. var uvs = new Array();
  29766. var colors = new Array();
  29767. var index = 0;
  29768. var faceIdx = 0; // face cursor in the array "indexes"
  29769. var indexes = new Array();
  29770. var i = 0;
  29771. var f = 0;
  29772. var u, v, ang, x, y, tmp;
  29773. // default face colors and UV if undefined
  29774. if (flat) {
  29775. for (f = 0; f < nbfaces; f++) {
  29776. if (faceColors && faceColors[f] === undefined) {
  29777. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29778. }
  29779. if (faceUV && faceUV[f] === undefined) {
  29780. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29781. }
  29782. }
  29783. }
  29784. if (!flat) {
  29785. for (i = 0; i < data.vertex.length; i++) {
  29786. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29787. uvs.push(0, 0);
  29788. }
  29789. for (f = 0; f < nbfaces; f++) {
  29790. for (i = 0; i < data.face[f].length - 2; i++) {
  29791. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29792. }
  29793. }
  29794. }
  29795. else {
  29796. for (f = 0; f < nbfaces; f++) {
  29797. var fl = data.face[f].length; // number of vertices of the current face
  29798. ang = 2 * Math.PI / fl;
  29799. x = 0.5 * Math.tan(ang / 2);
  29800. y = 0.5;
  29801. // positions, uvs, colors
  29802. for (i = 0; i < fl; i++) {
  29803. // positions
  29804. 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);
  29805. indexes.push(index);
  29806. index++;
  29807. // uvs
  29808. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29809. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29810. uvs.push(u, v);
  29811. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29812. y = x * Math.sin(ang) + y * Math.cos(ang);
  29813. x = tmp;
  29814. // colors
  29815. if (faceColors) {
  29816. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29817. }
  29818. }
  29819. // indices from indexes
  29820. for (i = 0; i < fl - 2; i++) {
  29821. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29822. }
  29823. faceIdx += fl;
  29824. }
  29825. }
  29826. VertexData.ComputeNormals(positions, indices, normals);
  29827. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29828. var vertexData = new VertexData();
  29829. vertexData.positions = positions;
  29830. vertexData.indices = indices;
  29831. vertexData.normals = normals;
  29832. vertexData.uvs = uvs;
  29833. if (faceColors && flat) {
  29834. vertexData.colors = colors;
  29835. }
  29836. return vertexData;
  29837. };
  29838. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29839. /**
  29840. * Creates the VertexData of the Torus Knot.
  29841. */
  29842. VertexData.CreateTorusKnot = function (options) {
  29843. var indices = new Array();
  29844. var positions = new Array();
  29845. var normals = new Array();
  29846. var uvs = new Array();
  29847. var radius = options.radius || 2;
  29848. var tube = options.tube || 0.5;
  29849. var radialSegments = options.radialSegments || 32;
  29850. var tubularSegments = options.tubularSegments || 32;
  29851. var p = options.p || 2;
  29852. var q = options.q || 3;
  29853. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29854. // Helper
  29855. var getPos = function (angle) {
  29856. var cu = Math.cos(angle);
  29857. var su = Math.sin(angle);
  29858. var quOverP = q / p * angle;
  29859. var cs = Math.cos(quOverP);
  29860. var tx = radius * (2 + cs) * 0.5 * cu;
  29861. var ty = radius * (2 + cs) * su * 0.5;
  29862. var tz = radius * Math.sin(quOverP) * 0.5;
  29863. return new BABYLON.Vector3(tx, ty, tz);
  29864. };
  29865. // Vertices
  29866. var i;
  29867. var j;
  29868. for (i = 0; i <= radialSegments; i++) {
  29869. var modI = i % radialSegments;
  29870. var u = modI / radialSegments * 2 * p * Math.PI;
  29871. var p1 = getPos(u);
  29872. var p2 = getPos(u + 0.01);
  29873. var tang = p2.subtract(p1);
  29874. var n = p2.add(p1);
  29875. var bitan = BABYLON.Vector3.Cross(tang, n);
  29876. n = BABYLON.Vector3.Cross(bitan, tang);
  29877. bitan.normalize();
  29878. n.normalize();
  29879. for (j = 0; j < tubularSegments; j++) {
  29880. var modJ = j % tubularSegments;
  29881. var v = modJ / tubularSegments * 2 * Math.PI;
  29882. var cx = -tube * Math.cos(v);
  29883. var cy = tube * Math.sin(v);
  29884. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29885. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29886. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29887. uvs.push(i / radialSegments);
  29888. uvs.push(j / tubularSegments);
  29889. }
  29890. }
  29891. for (i = 0; i < radialSegments; i++) {
  29892. for (j = 0; j < tubularSegments; j++) {
  29893. var jNext = (j + 1) % tubularSegments;
  29894. var a = i * tubularSegments + j;
  29895. var b = (i + 1) * tubularSegments + j;
  29896. var c = (i + 1) * tubularSegments + jNext;
  29897. var d = i * tubularSegments + jNext;
  29898. indices.push(d);
  29899. indices.push(b);
  29900. indices.push(a);
  29901. indices.push(d);
  29902. indices.push(c);
  29903. indices.push(b);
  29904. }
  29905. }
  29906. // Normals
  29907. VertexData.ComputeNormals(positions, indices, normals);
  29908. // Sides
  29909. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29910. // Result
  29911. var vertexData = new VertexData();
  29912. vertexData.indices = indices;
  29913. vertexData.positions = positions;
  29914. vertexData.normals = normals;
  29915. vertexData.uvs = uvs;
  29916. return vertexData;
  29917. };
  29918. // Tools
  29919. /**
  29920. * @param {any} - positions (number[] or Float32Array)
  29921. * @param {any} - indices (number[] or Uint16Array)
  29922. * @param {any} - normals (number[] or Float32Array)
  29923. * options (optional) :
  29924. * facetPositions : optional array of facet positions (vector3)
  29925. * facetNormals : optional array of facet normals (vector3)
  29926. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  29927. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  29928. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  29929. * bbSize : optional bounding box size data, required for facetPartitioning computation
  29930. * bInfo : optional bounding info, required for facetPartitioning computation
  29931. */
  29932. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  29933. // temporary scalar variables
  29934. var index = 0; // facet index
  29935. var p1p2x = 0.0; // p1p2 vector x coordinate
  29936. var p1p2y = 0.0; // p1p2 vector y coordinate
  29937. var p1p2z = 0.0; // p1p2 vector z coordinate
  29938. var p3p2x = 0.0; // p3p2 vector x coordinate
  29939. var p3p2y = 0.0; // p3p2 vector y coordinate
  29940. var p3p2z = 0.0; // p3p2 vector z coordinate
  29941. var faceNormalx = 0.0; // facet normal x coordinate
  29942. var faceNormaly = 0.0; // facet normal y coordinate
  29943. var faceNormalz = 0.0; // facet normal z coordinate
  29944. var length = 0.0; // facet normal length before normalization
  29945. var v1x = 0; // vector1 x index in the positions array
  29946. var v1y = 0; // vector1 y index in the positions array
  29947. var v1z = 0; // vector1 z index in the positions array
  29948. var v2x = 0; // vector2 x index in the positions array
  29949. var v2y = 0; // vector2 y index in the positions array
  29950. var v2z = 0; // vector2 z index in the positions array
  29951. var v3x = 0; // vector3 x index in the positions array
  29952. var v3y = 0; // vector3 y index in the positions array
  29953. var v3z = 0; // vector3 z index in the positions array
  29954. var computeFacetNormals = false;
  29955. var computeFacetPositions = false;
  29956. var computeFacetPartitioning = false;
  29957. var faceNormalSign = 1;
  29958. var ratio = 0;
  29959. if (options) {
  29960. computeFacetNormals = (options.facetNormals) ? true : false;
  29961. computeFacetPositions = (options.facetPositions) ? true : false;
  29962. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  29963. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  29964. ratio = options.ratio || 0;
  29965. }
  29966. // facetPartitioning reinit if needed
  29967. var xSubRatio = 0;
  29968. var ySubRatio = 0;
  29969. var zSubRatio = 0;
  29970. var subSq = 0;
  29971. if (computeFacetPartitioning && options && options.bbSize) {
  29972. var ox = 0; // X partitioning index for facet position
  29973. var oy = 0; // Y partinioning index for facet position
  29974. var oz = 0; // Z partinioning index for facet position
  29975. var b1x = 0; // X partitioning index for facet v1 vertex
  29976. var b1y = 0; // Y partitioning index for facet v1 vertex
  29977. var b1z = 0; // z partitioning index for facet v1 vertex
  29978. var b2x = 0; // X partitioning index for facet v2 vertex
  29979. var b2y = 0; // Y partitioning index for facet v2 vertex
  29980. var b2z = 0; // Z partitioning index for facet v2 vertex
  29981. var b3x = 0; // X partitioning index for facet v3 vertex
  29982. var b3y = 0; // Y partitioning index for facet v3 vertex
  29983. var b3z = 0; // Z partitioning index for facet v3 vertex
  29984. var block_idx_o = 0; // facet barycenter block index
  29985. var block_idx_v1 = 0; // v1 vertex block index
  29986. var block_idx_v2 = 0; // v2 vertex block index
  29987. var block_idx_v3 = 0; // v3 vertex block index
  29988. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  29989. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  29990. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  29991. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  29992. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  29993. subSq = options.subDiv.max * options.subDiv.max;
  29994. options.facetPartitioning.length = 0;
  29995. }
  29996. // reset the normals
  29997. for (index = 0; index < positions.length; index++) {
  29998. normals[index] = 0.0;
  29999. }
  30000. // Loop : 1 indice triplet = 1 facet
  30001. var nbFaces = indices.length / 3;
  30002. for (index = 0; index < nbFaces; index++) {
  30003. // get the indexes of the coordinates of each vertex of the facet
  30004. v1x = indices[index * 3] * 3;
  30005. v1y = v1x + 1;
  30006. v1z = v1x + 2;
  30007. v2x = indices[index * 3 + 1] * 3;
  30008. v2y = v2x + 1;
  30009. v2z = v2x + 2;
  30010. v3x = indices[index * 3 + 2] * 3;
  30011. v3y = v3x + 1;
  30012. v3z = v3x + 2;
  30013. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30014. p1p2y = positions[v1y] - positions[v2y];
  30015. p1p2z = positions[v1z] - positions[v2z];
  30016. p3p2x = positions[v3x] - positions[v2x];
  30017. p3p2y = positions[v3y] - positions[v2y];
  30018. p3p2z = positions[v3z] - positions[v2z];
  30019. // compute the face normal with the cross product
  30020. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30021. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30022. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30023. // normalize this normal and store it in the array facetData
  30024. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30025. length = (length === 0) ? 1.0 : length;
  30026. faceNormalx /= length;
  30027. faceNormaly /= length;
  30028. faceNormalz /= length;
  30029. if (computeFacetNormals && options) {
  30030. options.facetNormals[index].x = faceNormalx;
  30031. options.facetNormals[index].y = faceNormaly;
  30032. options.facetNormals[index].z = faceNormalz;
  30033. }
  30034. if (computeFacetPositions && options) {
  30035. // compute and the facet barycenter coordinates in the array facetPositions
  30036. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30037. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30038. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30039. }
  30040. if (computeFacetPartitioning && options) {
  30041. // store the facet indexes in arrays in the main facetPartitioning array :
  30042. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30043. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30044. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30045. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30046. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30047. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30048. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30049. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30050. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30051. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30052. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30053. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30054. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30055. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30056. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30057. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30058. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30059. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30060. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30061. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30062. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30063. // push each facet index in each block containing the vertex
  30064. options.facetPartitioning[block_idx_v1].push(index);
  30065. if (block_idx_v2 != block_idx_v1) {
  30066. options.facetPartitioning[block_idx_v2].push(index);
  30067. }
  30068. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30069. options.facetPartitioning[block_idx_v3].push(index);
  30070. }
  30071. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30072. options.facetPartitioning[block_idx_o].push(index);
  30073. }
  30074. }
  30075. // compute the normals anyway
  30076. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30077. normals[v1y] += faceNormaly;
  30078. normals[v1z] += faceNormalz;
  30079. normals[v2x] += faceNormalx;
  30080. normals[v2y] += faceNormaly;
  30081. normals[v2z] += faceNormalz;
  30082. normals[v3x] += faceNormalx;
  30083. normals[v3y] += faceNormaly;
  30084. normals[v3z] += faceNormalz;
  30085. }
  30086. // last normalization of each normal
  30087. for (index = 0; index < normals.length / 3; index++) {
  30088. faceNormalx = normals[index * 3];
  30089. faceNormaly = normals[index * 3 + 1];
  30090. faceNormalz = normals[index * 3 + 2];
  30091. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30092. length = (length === 0) ? 1.0 : length;
  30093. faceNormalx /= length;
  30094. faceNormaly /= length;
  30095. faceNormalz /= length;
  30096. normals[index * 3] = faceNormalx;
  30097. normals[index * 3 + 1] = faceNormaly;
  30098. normals[index * 3 + 2] = faceNormalz;
  30099. }
  30100. };
  30101. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30102. var li = indices.length;
  30103. var ln = normals.length;
  30104. var i;
  30105. var n;
  30106. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30107. switch (sideOrientation) {
  30108. case BABYLON.Mesh.FRONTSIDE:
  30109. // nothing changed
  30110. break;
  30111. case BABYLON.Mesh.BACKSIDE:
  30112. var tmp;
  30113. // indices
  30114. for (i = 0; i < li; i += 3) {
  30115. tmp = indices[i];
  30116. indices[i] = indices[i + 2];
  30117. indices[i + 2] = tmp;
  30118. }
  30119. // normals
  30120. for (n = 0; n < ln; n++) {
  30121. normals[n] = -normals[n];
  30122. }
  30123. break;
  30124. case BABYLON.Mesh.DOUBLESIDE:
  30125. // positions
  30126. var lp = positions.length;
  30127. var l = lp / 3;
  30128. for (var p = 0; p < lp; p++) {
  30129. positions[lp + p] = positions[p];
  30130. }
  30131. // indices
  30132. for (i = 0; i < li; i += 3) {
  30133. indices[i + li] = indices[i + 2] + l;
  30134. indices[i + 1 + li] = indices[i + 1] + l;
  30135. indices[i + 2 + li] = indices[i] + l;
  30136. }
  30137. // normals
  30138. for (n = 0; n < ln; n++) {
  30139. normals[ln + n] = -normals[n];
  30140. }
  30141. // uvs
  30142. var lu = uvs.length;
  30143. var u = 0;
  30144. for (u = 0; u < lu; u++) {
  30145. uvs[u + lu] = uvs[u];
  30146. }
  30147. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30148. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30149. u = 0;
  30150. for (i = 0; i < lu / 2; i++) {
  30151. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30152. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30153. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30154. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30155. u += 2;
  30156. }
  30157. break;
  30158. }
  30159. };
  30160. /**
  30161. * Creates a new VertexData from the imported parameters.
  30162. */
  30163. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30164. var vertexData = new VertexData();
  30165. // positions
  30166. var positions = parsedVertexData.positions;
  30167. if (positions) {
  30168. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30169. }
  30170. // normals
  30171. var normals = parsedVertexData.normals;
  30172. if (normals) {
  30173. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30174. }
  30175. // tangents
  30176. var tangents = parsedVertexData.tangents;
  30177. if (tangents) {
  30178. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30179. }
  30180. // uvs
  30181. var uvs = parsedVertexData.uvs;
  30182. if (uvs) {
  30183. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30184. }
  30185. // uv2s
  30186. var uv2s = parsedVertexData.uv2s;
  30187. if (uv2s) {
  30188. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30189. }
  30190. // uv3s
  30191. var uv3s = parsedVertexData.uv3s;
  30192. if (uv3s) {
  30193. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30194. }
  30195. // uv4s
  30196. var uv4s = parsedVertexData.uv4s;
  30197. if (uv4s) {
  30198. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30199. }
  30200. // uv5s
  30201. var uv5s = parsedVertexData.uv5s;
  30202. if (uv5s) {
  30203. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30204. }
  30205. // uv6s
  30206. var uv6s = parsedVertexData.uv6s;
  30207. if (uv6s) {
  30208. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30209. }
  30210. // colors
  30211. var colors = parsedVertexData.colors;
  30212. if (colors) {
  30213. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30214. }
  30215. // matricesIndices
  30216. var matricesIndices = parsedVertexData.matricesIndices;
  30217. if (matricesIndices) {
  30218. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30219. }
  30220. // matricesWeights
  30221. var matricesWeights = parsedVertexData.matricesWeights;
  30222. if (matricesWeights) {
  30223. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30224. }
  30225. // indices
  30226. var indices = parsedVertexData.indices;
  30227. if (indices) {
  30228. vertexData.indices = indices;
  30229. }
  30230. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30231. };
  30232. return VertexData;
  30233. }());
  30234. BABYLON.VertexData = VertexData;
  30235. })(BABYLON || (BABYLON = {}));
  30236. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30237. var BABYLON;
  30238. (function (BABYLON) {
  30239. var Geometry = /** @class */ (function () {
  30240. function Geometry(id, scene, vertexData, updatable, mesh) {
  30241. if (updatable === void 0) { updatable = false; }
  30242. if (mesh === void 0) { mesh = null; }
  30243. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30244. this._totalVertices = 0;
  30245. this._isDisposed = false;
  30246. this._indexBufferIsUpdatable = false;
  30247. this.id = id;
  30248. this._engine = scene.getEngine();
  30249. this._meshes = [];
  30250. this._scene = scene;
  30251. //Init vertex buffer cache
  30252. this._vertexBuffers = {};
  30253. this._indices = [];
  30254. this._updatable = updatable;
  30255. // vertexData
  30256. if (vertexData) {
  30257. this.setAllVerticesData(vertexData, updatable);
  30258. }
  30259. else {
  30260. this._totalVertices = 0;
  30261. this._indices = [];
  30262. }
  30263. if (this._engine.getCaps().vertexArrayObject) {
  30264. this._vertexArrayObjects = {};
  30265. }
  30266. // applyToMesh
  30267. if (mesh) {
  30268. if (mesh.getClassName() === "LinesMesh") {
  30269. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30270. this.updateExtend();
  30271. }
  30272. this.applyToMesh(mesh);
  30273. mesh.computeWorldMatrix(true);
  30274. }
  30275. }
  30276. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30277. /**
  30278. * 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
  30279. * @returns The Bias Vector
  30280. */
  30281. get: function () {
  30282. return this._boundingBias;
  30283. },
  30284. set: function (value) {
  30285. if (this._boundingBias && this._boundingBias.equals(value)) {
  30286. return;
  30287. }
  30288. this._boundingBias = value.clone();
  30289. this.updateBoundingInfo(true, null);
  30290. },
  30291. enumerable: true,
  30292. configurable: true
  30293. });
  30294. Geometry.CreateGeometryForMesh = function (mesh) {
  30295. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30296. geometry.applyToMesh(mesh);
  30297. return geometry;
  30298. };
  30299. Object.defineProperty(Geometry.prototype, "extend", {
  30300. get: function () {
  30301. return this._extend;
  30302. },
  30303. enumerable: true,
  30304. configurable: true
  30305. });
  30306. Geometry.prototype.getScene = function () {
  30307. return this._scene;
  30308. };
  30309. Geometry.prototype.getEngine = function () {
  30310. return this._engine;
  30311. };
  30312. Geometry.prototype.isReady = function () {
  30313. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30314. };
  30315. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30316. get: function () {
  30317. for (var index = 0; index < this._meshes.length; index++) {
  30318. if (!this._meshes[index].doNotSerialize) {
  30319. return false;
  30320. }
  30321. }
  30322. return true;
  30323. },
  30324. enumerable: true,
  30325. configurable: true
  30326. });
  30327. Geometry.prototype._rebuild = function () {
  30328. if (this._vertexArrayObjects) {
  30329. this._vertexArrayObjects = {};
  30330. }
  30331. // Index buffer
  30332. if (this._meshes.length !== 0 && this._indices) {
  30333. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30334. }
  30335. // Vertex buffers
  30336. for (var key in this._vertexBuffers) {
  30337. var vertexBuffer = this._vertexBuffers[key];
  30338. vertexBuffer._rebuild();
  30339. }
  30340. };
  30341. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30342. vertexData.applyToGeometry(this, updatable);
  30343. this.notifyUpdate();
  30344. };
  30345. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30346. if (updatable === void 0) { updatable = false; }
  30347. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30348. this.setVerticesBuffer(buffer);
  30349. };
  30350. Geometry.prototype.removeVerticesData = function (kind) {
  30351. if (this._vertexBuffers[kind]) {
  30352. this._vertexBuffers[kind].dispose();
  30353. delete this._vertexBuffers[kind];
  30354. }
  30355. };
  30356. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30357. var kind = buffer.getKind();
  30358. if (this._vertexBuffers[kind]) {
  30359. this._vertexBuffers[kind].dispose();
  30360. }
  30361. this._vertexBuffers[kind] = buffer;
  30362. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30363. var data = buffer.getData();
  30364. var stride = buffer.getStrideSize();
  30365. this._totalVertices = data.length / stride;
  30366. this.updateExtend(data, stride);
  30367. this._resetPointsArrayCache();
  30368. var meshes = this._meshes;
  30369. var numOfMeshes = meshes.length;
  30370. for (var index = 0; index < numOfMeshes; index++) {
  30371. var mesh = meshes[index];
  30372. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30373. mesh._createGlobalSubMesh(false);
  30374. mesh.computeWorldMatrix(true);
  30375. }
  30376. }
  30377. this.notifyUpdate(kind);
  30378. if (this._vertexArrayObjects) {
  30379. this._disposeVertexArrayObjects();
  30380. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30381. }
  30382. };
  30383. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30384. var vertexBuffer = this.getVertexBuffer(kind);
  30385. if (!vertexBuffer) {
  30386. return;
  30387. }
  30388. vertexBuffer.updateDirectly(data, offset);
  30389. this.notifyUpdate(kind);
  30390. };
  30391. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30392. if (updateExtends === void 0) { updateExtends = false; }
  30393. var vertexBuffer = this.getVertexBuffer(kind);
  30394. if (!vertexBuffer) {
  30395. return;
  30396. }
  30397. vertexBuffer.update(data);
  30398. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30399. var stride = vertexBuffer.getStrideSize();
  30400. this._totalVertices = data.length / stride;
  30401. this.updateBoundingInfo(updateExtends, data);
  30402. }
  30403. this.notifyUpdate(kind);
  30404. };
  30405. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30406. if (updateExtends) {
  30407. this.updateExtend(data);
  30408. }
  30409. var meshes = this._meshes;
  30410. var numOfMeshes = meshes.length;
  30411. this._resetPointsArrayCache();
  30412. for (var index = 0; index < numOfMeshes; index++) {
  30413. var mesh = meshes[index];
  30414. if (updateExtends) {
  30415. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30416. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30417. var subMesh = mesh.subMeshes[subIndex];
  30418. subMesh.refreshBoundingInfo();
  30419. }
  30420. }
  30421. }
  30422. };
  30423. Geometry.prototype._bind = function (effect, indexToBind) {
  30424. if (!effect) {
  30425. return;
  30426. }
  30427. if (indexToBind === undefined) {
  30428. indexToBind = this._indexBuffer;
  30429. }
  30430. var vbs = this.getVertexBuffers();
  30431. if (!vbs) {
  30432. return;
  30433. }
  30434. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30435. this._engine.bindBuffers(vbs, indexToBind, effect);
  30436. return;
  30437. }
  30438. // Using VAO
  30439. if (!this._vertexArrayObjects[effect.key]) {
  30440. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30441. }
  30442. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30443. };
  30444. Geometry.prototype.getTotalVertices = function () {
  30445. if (!this.isReady()) {
  30446. return 0;
  30447. }
  30448. return this._totalVertices;
  30449. };
  30450. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30451. var vertexBuffer = this.getVertexBuffer(kind);
  30452. if (!vertexBuffer) {
  30453. return null;
  30454. }
  30455. var orig = vertexBuffer.getData();
  30456. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30457. return orig;
  30458. }
  30459. else {
  30460. var len = orig.length;
  30461. var copy = [];
  30462. for (var i = 0; i < len; i++) {
  30463. copy.push(orig[i]);
  30464. }
  30465. return copy;
  30466. }
  30467. };
  30468. /**
  30469. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30470. * Possible `kind` values :
  30471. * - BABYLON.VertexBuffer.PositionKind
  30472. * - BABYLON.VertexBuffer.UVKind
  30473. * - BABYLON.VertexBuffer.UV2Kind
  30474. * - BABYLON.VertexBuffer.UV3Kind
  30475. * - BABYLON.VertexBuffer.UV4Kind
  30476. * - BABYLON.VertexBuffer.UV5Kind
  30477. * - BABYLON.VertexBuffer.UV6Kind
  30478. * - BABYLON.VertexBuffer.ColorKind
  30479. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30480. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30481. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30482. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30483. */
  30484. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  30485. var vb = this._vertexBuffers[kind];
  30486. if (!vb) {
  30487. return false;
  30488. }
  30489. return vb.isUpdatable();
  30490. };
  30491. Geometry.prototype.getVertexBuffer = function (kind) {
  30492. if (!this.isReady()) {
  30493. return null;
  30494. }
  30495. return this._vertexBuffers[kind];
  30496. };
  30497. Geometry.prototype.getVertexBuffers = function () {
  30498. if (!this.isReady()) {
  30499. return null;
  30500. }
  30501. return this._vertexBuffers;
  30502. };
  30503. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30504. if (!this._vertexBuffers) {
  30505. if (this._delayInfo) {
  30506. return this._delayInfo.indexOf(kind) !== -1;
  30507. }
  30508. return false;
  30509. }
  30510. return this._vertexBuffers[kind] !== undefined;
  30511. };
  30512. Geometry.prototype.getVerticesDataKinds = function () {
  30513. var result = [];
  30514. var kind;
  30515. if (!this._vertexBuffers && this._delayInfo) {
  30516. for (kind in this._delayInfo) {
  30517. result.push(kind);
  30518. }
  30519. }
  30520. else {
  30521. for (kind in this._vertexBuffers) {
  30522. result.push(kind);
  30523. }
  30524. }
  30525. return result;
  30526. };
  30527. Geometry.prototype.updateIndices = function (indices, offset) {
  30528. if (!this._indexBuffer) {
  30529. return;
  30530. }
  30531. if (!this._indexBufferIsUpdatable) {
  30532. this.setIndices(indices, null, true);
  30533. }
  30534. else {
  30535. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  30536. }
  30537. };
  30538. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  30539. if (totalVertices === void 0) { totalVertices = null; }
  30540. if (updatable === void 0) { updatable = false; }
  30541. if (this._indexBuffer) {
  30542. this._engine._releaseBuffer(this._indexBuffer);
  30543. }
  30544. this._disposeVertexArrayObjects();
  30545. this._indices = indices;
  30546. this._indexBufferIsUpdatable = updatable;
  30547. if (this._meshes.length !== 0 && this._indices) {
  30548. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  30549. }
  30550. if (totalVertices != undefined) {
  30551. this._totalVertices = totalVertices;
  30552. }
  30553. var meshes = this._meshes;
  30554. var numOfMeshes = meshes.length;
  30555. for (var index = 0; index < numOfMeshes; index++) {
  30556. meshes[index]._createGlobalSubMesh(true);
  30557. }
  30558. this.notifyUpdate();
  30559. };
  30560. Geometry.prototype.getTotalIndices = function () {
  30561. if (!this.isReady()) {
  30562. return 0;
  30563. }
  30564. return this._indices.length;
  30565. };
  30566. Geometry.prototype.getIndices = function (copyWhenShared) {
  30567. if (!this.isReady()) {
  30568. return null;
  30569. }
  30570. var orig = this._indices;
  30571. if (!copyWhenShared || this._meshes.length === 1) {
  30572. return orig;
  30573. }
  30574. else {
  30575. var len = orig.length;
  30576. var copy = [];
  30577. for (var i = 0; i < len; i++) {
  30578. copy.push(orig[i]);
  30579. }
  30580. return copy;
  30581. }
  30582. };
  30583. Geometry.prototype.getIndexBuffer = function () {
  30584. if (!this.isReady()) {
  30585. return null;
  30586. }
  30587. return this._indexBuffer;
  30588. };
  30589. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  30590. if (effect === void 0) { effect = null; }
  30591. if (!effect || !this._vertexArrayObjects) {
  30592. return;
  30593. }
  30594. if (this._vertexArrayObjects[effect.key]) {
  30595. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  30596. delete this._vertexArrayObjects[effect.key];
  30597. }
  30598. };
  30599. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30600. var meshes = this._meshes;
  30601. var index = meshes.indexOf(mesh);
  30602. if (index === -1) {
  30603. return;
  30604. }
  30605. meshes.splice(index, 1);
  30606. mesh._geometry = null;
  30607. if (meshes.length === 0 && shouldDispose) {
  30608. this.dispose();
  30609. }
  30610. };
  30611. Geometry.prototype.applyToMesh = function (mesh) {
  30612. if (mesh._geometry === this) {
  30613. return;
  30614. }
  30615. var previousGeometry = mesh._geometry;
  30616. if (previousGeometry) {
  30617. previousGeometry.releaseForMesh(mesh);
  30618. }
  30619. var meshes = this._meshes;
  30620. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30621. mesh._geometry = this;
  30622. this._scene.pushGeometry(this);
  30623. meshes.push(mesh);
  30624. if (this.isReady()) {
  30625. this._applyToMesh(mesh);
  30626. }
  30627. else {
  30628. mesh._boundingInfo = this._boundingInfo;
  30629. }
  30630. };
  30631. Geometry.prototype.updateExtend = function (data, stride) {
  30632. if (data === void 0) { data = null; }
  30633. if (!data) {
  30634. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30635. }
  30636. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  30637. };
  30638. Geometry.prototype._applyToMesh = function (mesh) {
  30639. var numOfMeshes = this._meshes.length;
  30640. // vertexBuffers
  30641. for (var kind in this._vertexBuffers) {
  30642. if (numOfMeshes === 1) {
  30643. this._vertexBuffers[kind].create();
  30644. }
  30645. var buffer = this._vertexBuffers[kind].getBuffer();
  30646. if (buffer)
  30647. buffer.references = numOfMeshes;
  30648. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30649. if (!this._extend) {
  30650. this.updateExtend(this._vertexBuffers[kind].getData());
  30651. }
  30652. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30653. mesh._createGlobalSubMesh(false);
  30654. //bounding info was just created again, world matrix should be applied again.
  30655. mesh._updateBoundingInfo();
  30656. }
  30657. }
  30658. // indexBuffer
  30659. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30660. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30661. }
  30662. if (this._indexBuffer) {
  30663. this._indexBuffer.references = numOfMeshes;
  30664. }
  30665. };
  30666. Geometry.prototype.notifyUpdate = function (kind) {
  30667. if (this.onGeometryUpdated) {
  30668. this.onGeometryUpdated(this, kind);
  30669. }
  30670. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30671. var mesh = _a[_i];
  30672. mesh._markSubMeshesAsAttributesDirty();
  30673. }
  30674. };
  30675. Geometry.prototype.load = function (scene, onLoaded) {
  30676. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30677. return;
  30678. }
  30679. if (this.isReady()) {
  30680. if (onLoaded) {
  30681. onLoaded();
  30682. }
  30683. return;
  30684. }
  30685. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30686. this._queueLoad(scene, onLoaded);
  30687. };
  30688. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30689. var _this = this;
  30690. if (!this.delayLoadingFile) {
  30691. return;
  30692. }
  30693. scene._addPendingData(this);
  30694. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30695. if (!_this._delayLoadingFunction) {
  30696. return;
  30697. }
  30698. _this._delayLoadingFunction(JSON.parse(data), _this);
  30699. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30700. _this._delayInfo = [];
  30701. scene._removePendingData(_this);
  30702. var meshes = _this._meshes;
  30703. var numOfMeshes = meshes.length;
  30704. for (var index = 0; index < numOfMeshes; index++) {
  30705. _this._applyToMesh(meshes[index]);
  30706. }
  30707. if (onLoaded) {
  30708. onLoaded();
  30709. }
  30710. }, function () { }, scene.database);
  30711. };
  30712. /**
  30713. * Invert the geometry to move from a right handed system to a left handed one.
  30714. */
  30715. Geometry.prototype.toLeftHanded = function () {
  30716. // Flip faces
  30717. var tIndices = this.getIndices(false);
  30718. if (tIndices != null && tIndices.length > 0) {
  30719. for (var i = 0; i < tIndices.length; i += 3) {
  30720. var tTemp = tIndices[i + 0];
  30721. tIndices[i + 0] = tIndices[i + 2];
  30722. tIndices[i + 2] = tTemp;
  30723. }
  30724. this.setIndices(tIndices);
  30725. }
  30726. // Negate position.z
  30727. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30728. if (tPositions != null && tPositions.length > 0) {
  30729. for (var i = 0; i < tPositions.length; i += 3) {
  30730. tPositions[i + 2] = -tPositions[i + 2];
  30731. }
  30732. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30733. }
  30734. // Negate normal.z
  30735. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30736. if (tNormals != null && tNormals.length > 0) {
  30737. for (var i = 0; i < tNormals.length; i += 3) {
  30738. tNormals[i + 2] = -tNormals[i + 2];
  30739. }
  30740. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30741. }
  30742. };
  30743. // Cache
  30744. Geometry.prototype._resetPointsArrayCache = function () {
  30745. this._positions = null;
  30746. };
  30747. Geometry.prototype._generatePointsArray = function () {
  30748. if (this._positions)
  30749. return true;
  30750. this._positions = [];
  30751. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30752. if (!data) {
  30753. return false;
  30754. }
  30755. for (var index = 0; index < data.length; index += 3) {
  30756. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30757. }
  30758. return true;
  30759. };
  30760. Geometry.prototype.isDisposed = function () {
  30761. return this._isDisposed;
  30762. };
  30763. Geometry.prototype._disposeVertexArrayObjects = function () {
  30764. if (this._vertexArrayObjects) {
  30765. for (var kind in this._vertexArrayObjects) {
  30766. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30767. }
  30768. this._vertexArrayObjects = {};
  30769. }
  30770. };
  30771. Geometry.prototype.dispose = function () {
  30772. var meshes = this._meshes;
  30773. var numOfMeshes = meshes.length;
  30774. var index;
  30775. for (index = 0; index < numOfMeshes; index++) {
  30776. this.releaseForMesh(meshes[index]);
  30777. }
  30778. this._meshes = [];
  30779. this._disposeVertexArrayObjects();
  30780. for (var kind in this._vertexBuffers) {
  30781. this._vertexBuffers[kind].dispose();
  30782. }
  30783. this._vertexBuffers = {};
  30784. this._totalVertices = 0;
  30785. if (this._indexBuffer) {
  30786. this._engine._releaseBuffer(this._indexBuffer);
  30787. }
  30788. this._indexBuffer = null;
  30789. this._indices = [];
  30790. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30791. this.delayLoadingFile = null;
  30792. this._delayLoadingFunction = null;
  30793. this._delayInfo = [];
  30794. this._boundingInfo = null;
  30795. this._scene.removeGeometry(this);
  30796. this._isDisposed = true;
  30797. };
  30798. Geometry.prototype.copy = function (id) {
  30799. var vertexData = new BABYLON.VertexData();
  30800. vertexData.indices = [];
  30801. var indices = this.getIndices();
  30802. if (indices) {
  30803. for (var index = 0; index < indices.length; index++) {
  30804. vertexData.indices.push(indices[index]);
  30805. }
  30806. }
  30807. var updatable = false;
  30808. var stopChecking = false;
  30809. var kind;
  30810. for (kind in this._vertexBuffers) {
  30811. // using slice() to make a copy of the array and not just reference it
  30812. var data = this.getVerticesData(kind);
  30813. if (data instanceof Float32Array) {
  30814. vertexData.set(new Float32Array(data), kind);
  30815. }
  30816. else {
  30817. vertexData.set(data.slice(0), kind);
  30818. }
  30819. if (!stopChecking) {
  30820. var vb = this.getVertexBuffer(kind);
  30821. if (vb) {
  30822. updatable = vb.isUpdatable();
  30823. stopChecking = !updatable;
  30824. }
  30825. }
  30826. }
  30827. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  30828. geometry.delayLoadState = this.delayLoadState;
  30829. geometry.delayLoadingFile = this.delayLoadingFile;
  30830. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30831. for (kind in this._delayInfo) {
  30832. geometry._delayInfo = geometry._delayInfo || [];
  30833. geometry._delayInfo.push(kind);
  30834. }
  30835. // Bounding info
  30836. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30837. return geometry;
  30838. };
  30839. Geometry.prototype.serialize = function () {
  30840. var serializationObject = {};
  30841. serializationObject.id = this.id;
  30842. serializationObject.updatable = this._updatable;
  30843. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30844. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30845. }
  30846. return serializationObject;
  30847. };
  30848. Geometry.prototype.toNumberArray = function (origin) {
  30849. if (Array.isArray(origin)) {
  30850. return origin;
  30851. }
  30852. else {
  30853. return Array.prototype.slice.call(origin);
  30854. }
  30855. };
  30856. Geometry.prototype.serializeVerticeData = function () {
  30857. var serializationObject = this.serialize();
  30858. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30859. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  30860. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30861. serializationObject.positions._updatable = true;
  30862. }
  30863. }
  30864. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30865. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  30866. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30867. serializationObject.normals._updatable = true;
  30868. }
  30869. }
  30870. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30871. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  30872. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  30873. serializationObject.uvs._updatable = true;
  30874. }
  30875. }
  30876. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30877. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  30878. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  30879. serializationObject.uv2s._updatable = true;
  30880. }
  30881. }
  30882. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30883. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  30884. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  30885. serializationObject.uv3s._updatable = true;
  30886. }
  30887. }
  30888. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30889. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  30890. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  30891. serializationObject.uv4s._updatable = true;
  30892. }
  30893. }
  30894. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30895. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  30896. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  30897. serializationObject.uv5s._updatable = true;
  30898. }
  30899. }
  30900. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30901. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  30902. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  30903. serializationObject.uv6s._updatable = true;
  30904. }
  30905. }
  30906. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30907. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  30908. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  30909. serializationObject.colors._updatable = true;
  30910. }
  30911. }
  30912. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30913. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  30914. serializationObject.matricesIndices._isExpanded = true;
  30915. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30916. serializationObject.matricesIndices._updatable = true;
  30917. }
  30918. }
  30919. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30920. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  30921. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30922. serializationObject.matricesWeights._updatable = true;
  30923. }
  30924. }
  30925. serializationObject.indices = this.toNumberArray(this.getIndices());
  30926. return serializationObject;
  30927. };
  30928. // Statics
  30929. Geometry.ExtractFromMesh = function (mesh, id) {
  30930. var geometry = mesh._geometry;
  30931. if (!geometry) {
  30932. return null;
  30933. }
  30934. return geometry.copy(id);
  30935. };
  30936. /**
  30937. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  30938. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  30939. * Be aware Math.random() could cause collisions, but:
  30940. * "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"
  30941. */
  30942. Geometry.RandomId = function () {
  30943. return BABYLON.Tools.RandomId();
  30944. };
  30945. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  30946. var scene = mesh.getScene();
  30947. // Geometry
  30948. var geometryId = parsedGeometry.geometryId;
  30949. if (geometryId) {
  30950. var geometry = scene.getGeometryByID(geometryId);
  30951. if (geometry) {
  30952. geometry.applyToMesh(mesh);
  30953. }
  30954. }
  30955. else if (parsedGeometry instanceof ArrayBuffer) {
  30956. var binaryInfo = mesh._binaryInfo;
  30957. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  30958. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  30959. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  30960. }
  30961. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  30962. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  30963. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  30964. }
  30965. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  30966. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  30967. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  30968. }
  30969. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  30970. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  30971. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  30972. }
  30973. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  30974. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  30975. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  30976. }
  30977. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  30978. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  30979. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  30980. }
  30981. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  30982. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  30983. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  30984. }
  30985. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  30986. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  30987. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  30988. }
  30989. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  30990. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  30991. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  30992. }
  30993. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  30994. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  30995. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  30996. }
  30997. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  30998. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  30999. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31000. }
  31001. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31002. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31003. mesh.setIndices(indicesData, null);
  31004. }
  31005. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31006. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31007. mesh.subMeshes = [];
  31008. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31009. var materialIndex = subMeshesData[(i * 5) + 0];
  31010. var verticesStart = subMeshesData[(i * 5) + 1];
  31011. var verticesCount = subMeshesData[(i * 5) + 2];
  31012. var indexStart = subMeshesData[(i * 5) + 3];
  31013. var indexCount = subMeshesData[(i * 5) + 4];
  31014. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31015. }
  31016. }
  31017. }
  31018. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31019. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31020. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31021. if (parsedGeometry.uvs) {
  31022. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31023. }
  31024. if (parsedGeometry.uvs2) {
  31025. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31026. }
  31027. if (parsedGeometry.uvs3) {
  31028. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31029. }
  31030. if (parsedGeometry.uvs4) {
  31031. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31032. }
  31033. if (parsedGeometry.uvs5) {
  31034. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31035. }
  31036. if (parsedGeometry.uvs6) {
  31037. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31038. }
  31039. if (parsedGeometry.colors) {
  31040. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31041. }
  31042. if (parsedGeometry.matricesIndices) {
  31043. if (!parsedGeometry.matricesIndices._isExpanded) {
  31044. var floatIndices = [];
  31045. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31046. var matricesIndex = parsedGeometry.matricesIndices[i];
  31047. floatIndices.push(matricesIndex & 0x000000FF);
  31048. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31049. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31050. floatIndices.push(matricesIndex >> 24);
  31051. }
  31052. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31053. }
  31054. else {
  31055. delete parsedGeometry.matricesIndices._isExpanded;
  31056. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31057. }
  31058. }
  31059. if (parsedGeometry.matricesIndicesExtra) {
  31060. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31061. var floatIndices = [];
  31062. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31063. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31064. floatIndices.push(matricesIndex & 0x000000FF);
  31065. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31066. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31067. floatIndices.push(matricesIndex >> 24);
  31068. }
  31069. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31070. }
  31071. else {
  31072. delete parsedGeometry.matricesIndices._isExpanded;
  31073. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31074. }
  31075. }
  31076. if (parsedGeometry.matricesWeights) {
  31077. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31078. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31079. }
  31080. if (parsedGeometry.matricesWeightsExtra) {
  31081. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31082. }
  31083. mesh.setIndices(parsedGeometry.indices, null);
  31084. }
  31085. // SubMeshes
  31086. if (parsedGeometry.subMeshes) {
  31087. mesh.subMeshes = [];
  31088. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31089. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31090. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31091. }
  31092. }
  31093. // Flat shading
  31094. if (mesh._shouldGenerateFlatShading) {
  31095. mesh.convertToFlatShadedMesh();
  31096. delete mesh._shouldGenerateFlatShading;
  31097. }
  31098. // Update
  31099. mesh.computeWorldMatrix(true);
  31100. // Octree
  31101. if (scene['_selectionOctree']) {
  31102. scene['_selectionOctree'].addMesh(mesh);
  31103. }
  31104. };
  31105. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31106. var epsilon = 1e-3;
  31107. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31108. return;
  31109. }
  31110. var noInfluenceBoneIndex = 0.0;
  31111. if (parsedGeometry.skeletonId > -1) {
  31112. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31113. if (!skeleton) {
  31114. return;
  31115. }
  31116. noInfluenceBoneIndex = skeleton.bones.length;
  31117. }
  31118. else {
  31119. return;
  31120. }
  31121. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31122. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31123. var matricesWeights = parsedGeometry.matricesWeights;
  31124. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31125. var influencers = parsedGeometry.numBoneInfluencer;
  31126. var size = matricesWeights.length;
  31127. for (var i = 0; i < size; i += 4) {
  31128. var weight = 0.0;
  31129. var firstZeroWeight = -1;
  31130. for (var j = 0; j < 4; j++) {
  31131. var w = matricesWeights[i + j];
  31132. weight += w;
  31133. if (w < epsilon && firstZeroWeight < 0) {
  31134. firstZeroWeight = j;
  31135. }
  31136. }
  31137. if (matricesWeightsExtra) {
  31138. for (var j = 0; j < 4; j++) {
  31139. var w = matricesWeightsExtra[i + j];
  31140. weight += w;
  31141. if (w < epsilon && firstZeroWeight < 0) {
  31142. firstZeroWeight = j + 4;
  31143. }
  31144. }
  31145. }
  31146. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31147. firstZeroWeight = influencers - 1;
  31148. }
  31149. if (weight > epsilon) {
  31150. var mweight = 1.0 / weight;
  31151. for (var j = 0; j < 4; j++) {
  31152. matricesWeights[i + j] *= mweight;
  31153. }
  31154. if (matricesWeightsExtra) {
  31155. for (var j = 0; j < 4; j++) {
  31156. matricesWeightsExtra[i + j] *= mweight;
  31157. }
  31158. }
  31159. }
  31160. else {
  31161. if (firstZeroWeight >= 4) {
  31162. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31163. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31164. }
  31165. else {
  31166. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31167. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31168. }
  31169. }
  31170. }
  31171. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31172. if (parsedGeometry.matricesWeightsExtra) {
  31173. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31174. }
  31175. };
  31176. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31177. if (scene.getGeometryByID(parsedVertexData.id)) {
  31178. return null; // null since geometry could be something else than a box...
  31179. }
  31180. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31181. if (BABYLON.Tags) {
  31182. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31183. }
  31184. if (parsedVertexData.delayLoadingFile) {
  31185. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31186. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31187. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31188. geometry._delayInfo = [];
  31189. if (parsedVertexData.hasUVs) {
  31190. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31191. }
  31192. if (parsedVertexData.hasUVs2) {
  31193. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31194. }
  31195. if (parsedVertexData.hasUVs3) {
  31196. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31197. }
  31198. if (parsedVertexData.hasUVs4) {
  31199. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31200. }
  31201. if (parsedVertexData.hasUVs5) {
  31202. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31203. }
  31204. if (parsedVertexData.hasUVs6) {
  31205. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31206. }
  31207. if (parsedVertexData.hasColors) {
  31208. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31209. }
  31210. if (parsedVertexData.hasMatricesIndices) {
  31211. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31212. }
  31213. if (parsedVertexData.hasMatricesWeights) {
  31214. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31215. }
  31216. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31217. }
  31218. else {
  31219. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31220. }
  31221. scene.pushGeometry(geometry, true);
  31222. return geometry;
  31223. };
  31224. return Geometry;
  31225. }());
  31226. BABYLON.Geometry = Geometry;
  31227. /////// Primitives //////////////////////////////////////////////
  31228. (function (Geometry) {
  31229. var Primitives;
  31230. (function (Primitives) {
  31231. /// Abstract class
  31232. var _Primitive = /** @class */ (function (_super) {
  31233. __extends(_Primitive, _super);
  31234. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31235. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31236. if (mesh === void 0) { mesh = null; }
  31237. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31238. _this._canBeRegenerated = _canBeRegenerated;
  31239. _this._beingRegenerated = true;
  31240. _this.regenerate();
  31241. _this._beingRegenerated = false;
  31242. return _this;
  31243. }
  31244. _Primitive.prototype.canBeRegenerated = function () {
  31245. return this._canBeRegenerated;
  31246. };
  31247. _Primitive.prototype.regenerate = function () {
  31248. if (!this._canBeRegenerated) {
  31249. return;
  31250. }
  31251. this._beingRegenerated = true;
  31252. this.setAllVerticesData(this._regenerateVertexData(), false);
  31253. this._beingRegenerated = false;
  31254. };
  31255. _Primitive.prototype.asNewGeometry = function (id) {
  31256. return _super.prototype.copy.call(this, id);
  31257. };
  31258. // overrides
  31259. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31260. if (!this._beingRegenerated) {
  31261. return;
  31262. }
  31263. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31264. };
  31265. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31266. if (!this._beingRegenerated) {
  31267. return;
  31268. }
  31269. _super.prototype.setVerticesData.call(this, kind, data, false);
  31270. };
  31271. // to override
  31272. // protected
  31273. _Primitive.prototype._regenerateVertexData = function () {
  31274. throw new Error("Abstract method");
  31275. };
  31276. _Primitive.prototype.copy = function (id) {
  31277. throw new Error("Must be overriden in sub-classes.");
  31278. };
  31279. _Primitive.prototype.serialize = function () {
  31280. var serializationObject = _super.prototype.serialize.call(this);
  31281. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31282. return serializationObject;
  31283. };
  31284. return _Primitive;
  31285. }(Geometry));
  31286. Primitives._Primitive = _Primitive;
  31287. var Ribbon = /** @class */ (function (_super) {
  31288. __extends(Ribbon, _super);
  31289. // Members
  31290. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31291. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31292. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31293. _this.pathArray = pathArray;
  31294. _this.closeArray = closeArray;
  31295. _this.closePath = closePath;
  31296. _this.offset = offset;
  31297. _this.side = side;
  31298. return _this;
  31299. }
  31300. Ribbon.prototype._regenerateVertexData = function () {
  31301. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31302. };
  31303. Ribbon.prototype.copy = function (id) {
  31304. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31305. };
  31306. return Ribbon;
  31307. }(_Primitive));
  31308. Primitives.Ribbon = Ribbon;
  31309. var Box = /** @class */ (function (_super) {
  31310. __extends(Box, _super);
  31311. // Members
  31312. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31313. if (mesh === void 0) { mesh = null; }
  31314. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31315. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31316. _this.size = size;
  31317. _this.side = side;
  31318. return _this;
  31319. }
  31320. Box.prototype._regenerateVertexData = function () {
  31321. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31322. };
  31323. Box.prototype.copy = function (id) {
  31324. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31325. };
  31326. Box.prototype.serialize = function () {
  31327. var serializationObject = _super.prototype.serialize.call(this);
  31328. serializationObject.size = this.size;
  31329. return serializationObject;
  31330. };
  31331. Box.Parse = function (parsedBox, scene) {
  31332. if (scene.getGeometryByID(parsedBox.id)) {
  31333. return null; // null since geometry could be something else than a box...
  31334. }
  31335. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31336. if (BABYLON.Tags) {
  31337. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31338. }
  31339. scene.pushGeometry(box, true);
  31340. return box;
  31341. };
  31342. return Box;
  31343. }(_Primitive));
  31344. Primitives.Box = Box;
  31345. var Sphere = /** @class */ (function (_super) {
  31346. __extends(Sphere, _super);
  31347. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31348. if (mesh === void 0) { mesh = null; }
  31349. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31350. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31351. _this.segments = segments;
  31352. _this.diameter = diameter;
  31353. _this.side = side;
  31354. return _this;
  31355. }
  31356. Sphere.prototype._regenerateVertexData = function () {
  31357. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31358. };
  31359. Sphere.prototype.copy = function (id) {
  31360. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31361. };
  31362. Sphere.prototype.serialize = function () {
  31363. var serializationObject = _super.prototype.serialize.call(this);
  31364. serializationObject.segments = this.segments;
  31365. serializationObject.diameter = this.diameter;
  31366. return serializationObject;
  31367. };
  31368. Sphere.Parse = function (parsedSphere, scene) {
  31369. if (scene.getGeometryByID(parsedSphere.id)) {
  31370. return null; // null since geometry could be something else than a sphere...
  31371. }
  31372. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31373. if (BABYLON.Tags) {
  31374. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31375. }
  31376. scene.pushGeometry(sphere, true);
  31377. return sphere;
  31378. };
  31379. return Sphere;
  31380. }(_Primitive));
  31381. Primitives.Sphere = Sphere;
  31382. var Disc = /** @class */ (function (_super) {
  31383. __extends(Disc, _super);
  31384. // Members
  31385. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31386. if (mesh === void 0) { mesh = null; }
  31387. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31388. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31389. _this.radius = radius;
  31390. _this.tessellation = tessellation;
  31391. _this.side = side;
  31392. return _this;
  31393. }
  31394. Disc.prototype._regenerateVertexData = function () {
  31395. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31396. };
  31397. Disc.prototype.copy = function (id) {
  31398. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31399. };
  31400. return Disc;
  31401. }(_Primitive));
  31402. Primitives.Disc = Disc;
  31403. var Cylinder = /** @class */ (function (_super) {
  31404. __extends(Cylinder, _super);
  31405. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31406. if (subdivisions === void 0) { subdivisions = 1; }
  31407. if (mesh === void 0) { mesh = null; }
  31408. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31409. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31410. _this.height = height;
  31411. _this.diameterTop = diameterTop;
  31412. _this.diameterBottom = diameterBottom;
  31413. _this.tessellation = tessellation;
  31414. _this.subdivisions = subdivisions;
  31415. _this.side = side;
  31416. return _this;
  31417. }
  31418. Cylinder.prototype._regenerateVertexData = function () {
  31419. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31420. };
  31421. Cylinder.prototype.copy = function (id) {
  31422. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31423. };
  31424. Cylinder.prototype.serialize = function () {
  31425. var serializationObject = _super.prototype.serialize.call(this);
  31426. serializationObject.height = this.height;
  31427. serializationObject.diameterTop = this.diameterTop;
  31428. serializationObject.diameterBottom = this.diameterBottom;
  31429. serializationObject.tessellation = this.tessellation;
  31430. return serializationObject;
  31431. };
  31432. Cylinder.Parse = function (parsedCylinder, scene) {
  31433. if (scene.getGeometryByID(parsedCylinder.id)) {
  31434. return null; // null since geometry could be something else than a cylinder...
  31435. }
  31436. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31437. if (BABYLON.Tags) {
  31438. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31439. }
  31440. scene.pushGeometry(cylinder, true);
  31441. return cylinder;
  31442. };
  31443. return Cylinder;
  31444. }(_Primitive));
  31445. Primitives.Cylinder = Cylinder;
  31446. var Torus = /** @class */ (function (_super) {
  31447. __extends(Torus, _super);
  31448. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31449. if (mesh === void 0) { mesh = null; }
  31450. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31451. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31452. _this.diameter = diameter;
  31453. _this.thickness = thickness;
  31454. _this.tessellation = tessellation;
  31455. _this.side = side;
  31456. return _this;
  31457. }
  31458. Torus.prototype._regenerateVertexData = function () {
  31459. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31460. };
  31461. Torus.prototype.copy = function (id) {
  31462. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31463. };
  31464. Torus.prototype.serialize = function () {
  31465. var serializationObject = _super.prototype.serialize.call(this);
  31466. serializationObject.diameter = this.diameter;
  31467. serializationObject.thickness = this.thickness;
  31468. serializationObject.tessellation = this.tessellation;
  31469. return serializationObject;
  31470. };
  31471. Torus.Parse = function (parsedTorus, scene) {
  31472. if (scene.getGeometryByID(parsedTorus.id)) {
  31473. return null; // null since geometry could be something else than a torus...
  31474. }
  31475. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31476. if (BABYLON.Tags) {
  31477. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31478. }
  31479. scene.pushGeometry(torus, true);
  31480. return torus;
  31481. };
  31482. return Torus;
  31483. }(_Primitive));
  31484. Primitives.Torus = Torus;
  31485. var Ground = /** @class */ (function (_super) {
  31486. __extends(Ground, _super);
  31487. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31488. if (mesh === void 0) { mesh = null; }
  31489. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31490. _this.width = width;
  31491. _this.height = height;
  31492. _this.subdivisions = subdivisions;
  31493. return _this;
  31494. }
  31495. Ground.prototype._regenerateVertexData = function () {
  31496. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31497. };
  31498. Ground.prototype.copy = function (id) {
  31499. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31500. };
  31501. Ground.prototype.serialize = function () {
  31502. var serializationObject = _super.prototype.serialize.call(this);
  31503. serializationObject.width = this.width;
  31504. serializationObject.height = this.height;
  31505. serializationObject.subdivisions = this.subdivisions;
  31506. return serializationObject;
  31507. };
  31508. Ground.Parse = function (parsedGround, scene) {
  31509. if (scene.getGeometryByID(parsedGround.id)) {
  31510. return null; // null since geometry could be something else than a ground...
  31511. }
  31512. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31513. if (BABYLON.Tags) {
  31514. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31515. }
  31516. scene.pushGeometry(ground, true);
  31517. return ground;
  31518. };
  31519. return Ground;
  31520. }(_Primitive));
  31521. Primitives.Ground = Ground;
  31522. var TiledGround = /** @class */ (function (_super) {
  31523. __extends(TiledGround, _super);
  31524. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31525. if (mesh === void 0) { mesh = null; }
  31526. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31527. _this.xmin = xmin;
  31528. _this.zmin = zmin;
  31529. _this.xmax = xmax;
  31530. _this.zmax = zmax;
  31531. _this.subdivisions = subdivisions;
  31532. _this.precision = precision;
  31533. return _this;
  31534. }
  31535. TiledGround.prototype._regenerateVertexData = function () {
  31536. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31537. };
  31538. TiledGround.prototype.copy = function (id) {
  31539. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31540. };
  31541. return TiledGround;
  31542. }(_Primitive));
  31543. Primitives.TiledGround = TiledGround;
  31544. var Plane = /** @class */ (function (_super) {
  31545. __extends(Plane, _super);
  31546. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31547. if (mesh === void 0) { mesh = null; }
  31548. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31549. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31550. _this.size = size;
  31551. _this.side = side;
  31552. return _this;
  31553. }
  31554. Plane.prototype._regenerateVertexData = function () {
  31555. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31556. };
  31557. Plane.prototype.copy = function (id) {
  31558. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31559. };
  31560. Plane.prototype.serialize = function () {
  31561. var serializationObject = _super.prototype.serialize.call(this);
  31562. serializationObject.size = this.size;
  31563. return serializationObject;
  31564. };
  31565. Plane.Parse = function (parsedPlane, scene) {
  31566. if (scene.getGeometryByID(parsedPlane.id)) {
  31567. return null; // null since geometry could be something else than a ground...
  31568. }
  31569. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31570. if (BABYLON.Tags) {
  31571. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31572. }
  31573. scene.pushGeometry(plane, true);
  31574. return plane;
  31575. };
  31576. return Plane;
  31577. }(_Primitive));
  31578. Primitives.Plane = Plane;
  31579. var TorusKnot = /** @class */ (function (_super) {
  31580. __extends(TorusKnot, _super);
  31581. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31582. if (mesh === void 0) { mesh = null; }
  31583. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31584. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31585. _this.radius = radius;
  31586. _this.tube = tube;
  31587. _this.radialSegments = radialSegments;
  31588. _this.tubularSegments = tubularSegments;
  31589. _this.p = p;
  31590. _this.q = q;
  31591. _this.side = side;
  31592. return _this;
  31593. }
  31594. TorusKnot.prototype._regenerateVertexData = function () {
  31595. 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 });
  31596. };
  31597. TorusKnot.prototype.copy = function (id) {
  31598. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31599. };
  31600. TorusKnot.prototype.serialize = function () {
  31601. var serializationObject = _super.prototype.serialize.call(this);
  31602. serializationObject.radius = this.radius;
  31603. serializationObject.tube = this.tube;
  31604. serializationObject.radialSegments = this.radialSegments;
  31605. serializationObject.tubularSegments = this.tubularSegments;
  31606. serializationObject.p = this.p;
  31607. serializationObject.q = this.q;
  31608. return serializationObject;
  31609. };
  31610. ;
  31611. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31612. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31613. return null; // null since geometry could be something else than a ground...
  31614. }
  31615. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31616. if (BABYLON.Tags) {
  31617. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31618. }
  31619. scene.pushGeometry(torusKnot, true);
  31620. return torusKnot;
  31621. };
  31622. return TorusKnot;
  31623. }(_Primitive));
  31624. Primitives.TorusKnot = TorusKnot;
  31625. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31626. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31627. })(BABYLON || (BABYLON = {}));
  31628. //# sourceMappingURL=babylon.geometry.js.map
  31629. var BABYLON;
  31630. (function (BABYLON) {
  31631. var PostProcessManager = /** @class */ (function () {
  31632. function PostProcessManager(scene) {
  31633. this._vertexBuffers = {};
  31634. this._scene = scene;
  31635. }
  31636. PostProcessManager.prototype._prepareBuffers = function () {
  31637. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31638. return;
  31639. }
  31640. // VBO
  31641. var vertices = [];
  31642. vertices.push(1, 1);
  31643. vertices.push(-1, 1);
  31644. vertices.push(-1, -1);
  31645. vertices.push(1, -1);
  31646. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31647. this._buildIndexBuffer();
  31648. };
  31649. PostProcessManager.prototype._buildIndexBuffer = function () {
  31650. // Indices
  31651. var indices = [];
  31652. indices.push(0);
  31653. indices.push(1);
  31654. indices.push(2);
  31655. indices.push(0);
  31656. indices.push(2);
  31657. indices.push(3);
  31658. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31659. };
  31660. PostProcessManager.prototype._rebuild = function () {
  31661. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31662. if (!vb) {
  31663. return;
  31664. }
  31665. vb._rebuild();
  31666. this._buildIndexBuffer();
  31667. };
  31668. // Methods
  31669. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31670. if (sourceTexture === void 0) { sourceTexture = null; }
  31671. if (postProcesses === void 0) { postProcesses = null; }
  31672. var camera = this._scene.activeCamera;
  31673. if (!camera) {
  31674. return false;
  31675. }
  31676. var postProcesses = postProcesses || camera._postProcesses;
  31677. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31678. return false;
  31679. }
  31680. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31681. return true;
  31682. };
  31683. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31684. if (targetTexture === void 0) { targetTexture = null; }
  31685. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31686. if (!this._scene.activeCamera) {
  31687. return;
  31688. }
  31689. var engine = this._scene.getEngine();
  31690. for (var index = 0; index < postProcesses.length; index++) {
  31691. if (index < postProcesses.length - 1) {
  31692. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31693. }
  31694. else {
  31695. if (targetTexture) {
  31696. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31697. }
  31698. else {
  31699. engine.restoreDefaultFramebuffer();
  31700. }
  31701. }
  31702. var pp = postProcesses[index];
  31703. var effect = pp.apply();
  31704. if (effect) {
  31705. pp.onBeforeRenderObservable.notifyObservers(effect);
  31706. // VBOs
  31707. this._prepareBuffers();
  31708. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31709. // Draw order
  31710. engine.draw(true, 0, 6);
  31711. pp.onAfterRenderObservable.notifyObservers(effect);
  31712. }
  31713. }
  31714. // Restore depth buffer
  31715. engine.setDepthBuffer(true);
  31716. engine.setDepthWrite(true);
  31717. };
  31718. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31719. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31720. var camera = this._scene.activeCamera;
  31721. if (!camera) {
  31722. return;
  31723. }
  31724. postProcesses = postProcesses || camera._postProcesses;
  31725. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31726. return;
  31727. }
  31728. var engine = this._scene.getEngine();
  31729. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31730. if (index < len - 1) {
  31731. postProcesses[index + 1].activate(camera, targetTexture);
  31732. }
  31733. else {
  31734. if (targetTexture) {
  31735. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31736. }
  31737. else {
  31738. engine.restoreDefaultFramebuffer();
  31739. }
  31740. }
  31741. if (doNotPresent) {
  31742. break;
  31743. }
  31744. var pp = postProcesses[index];
  31745. var effect = pp.apply();
  31746. if (effect) {
  31747. pp.onBeforeRenderObservable.notifyObservers(effect);
  31748. // VBOs
  31749. this._prepareBuffers();
  31750. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31751. // Draw order
  31752. engine.draw(true, 0, 6);
  31753. pp.onAfterRenderObservable.notifyObservers(effect);
  31754. }
  31755. }
  31756. // Restore states
  31757. engine.setDepthBuffer(true);
  31758. engine.setDepthWrite(true);
  31759. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31760. };
  31761. PostProcessManager.prototype.dispose = function () {
  31762. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31763. if (buffer) {
  31764. buffer.dispose();
  31765. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31766. }
  31767. if (this._indexBuffer) {
  31768. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31769. this._indexBuffer = null;
  31770. }
  31771. };
  31772. return PostProcessManager;
  31773. }());
  31774. BABYLON.PostProcessManager = PostProcessManager;
  31775. })(BABYLON || (BABYLON = {}));
  31776. //# sourceMappingURL=babylon.postProcessManager.js.map
  31777. var BABYLON;
  31778. (function (BABYLON) {
  31779. /**
  31780. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31781. */
  31782. var PerformanceMonitor = /** @class */ (function () {
  31783. /**
  31784. * constructor
  31785. * @param frameSampleSize The number of samples required to saturate the sliding window
  31786. */
  31787. function PerformanceMonitor(frameSampleSize) {
  31788. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31789. this._enabled = true;
  31790. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31791. }
  31792. /**
  31793. * Samples current frame
  31794. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31795. */
  31796. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31797. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31798. if (!this._enabled)
  31799. return;
  31800. if (this._lastFrameTimeMs != null) {
  31801. var dt = timeMs - this._lastFrameTimeMs;
  31802. this._rollingFrameTime.add(dt);
  31803. }
  31804. this._lastFrameTimeMs = timeMs;
  31805. };
  31806. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31807. /**
  31808. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31809. * @return Average frame time in milliseconds
  31810. */
  31811. get: function () {
  31812. return this._rollingFrameTime.average;
  31813. },
  31814. enumerable: true,
  31815. configurable: true
  31816. });
  31817. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  31818. /**
  31819. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31820. * @return Frame time variance in milliseconds squared
  31821. */
  31822. get: function () {
  31823. return this._rollingFrameTime.variance;
  31824. },
  31825. enumerable: true,
  31826. configurable: true
  31827. });
  31828. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  31829. /**
  31830. * Returns the frame time of the most recent frame
  31831. * @return Frame time in milliseconds
  31832. */
  31833. get: function () {
  31834. return this._rollingFrameTime.history(0);
  31835. },
  31836. enumerable: true,
  31837. configurable: true
  31838. });
  31839. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  31840. /**
  31841. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  31842. * @return Framerate in frames per second
  31843. */
  31844. get: function () {
  31845. return 1000.0 / this._rollingFrameTime.average;
  31846. },
  31847. enumerable: true,
  31848. configurable: true
  31849. });
  31850. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  31851. /**
  31852. * Returns the average framerate in frames per second using the most recent frame time
  31853. * @return Framerate in frames per second
  31854. */
  31855. get: function () {
  31856. var history = this._rollingFrameTime.history(0);
  31857. if (history === 0) {
  31858. return 0;
  31859. }
  31860. return 1000.0 / history;
  31861. },
  31862. enumerable: true,
  31863. configurable: true
  31864. });
  31865. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  31866. /**
  31867. * Returns true if enough samples have been taken to completely fill the sliding window
  31868. * @return true if saturated
  31869. */
  31870. get: function () {
  31871. return this._rollingFrameTime.isSaturated();
  31872. },
  31873. enumerable: true,
  31874. configurable: true
  31875. });
  31876. /**
  31877. * Enables contributions to the sliding window sample set
  31878. */
  31879. PerformanceMonitor.prototype.enable = function () {
  31880. this._enabled = true;
  31881. };
  31882. /**
  31883. * Disables contributions to the sliding window sample set
  31884. * Samples will not be interpolated over the disabled period
  31885. */
  31886. PerformanceMonitor.prototype.disable = function () {
  31887. this._enabled = false;
  31888. //clear last sample to avoid interpolating over the disabled period when next enabled
  31889. this._lastFrameTimeMs = null;
  31890. this._lastChangeTimeMs = null;
  31891. };
  31892. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  31893. /**
  31894. * Returns true if sampling is enabled
  31895. * @return true if enabled
  31896. */
  31897. get: function () {
  31898. return this._enabled;
  31899. },
  31900. enumerable: true,
  31901. configurable: true
  31902. });
  31903. /**
  31904. * Resets performance monitor
  31905. */
  31906. PerformanceMonitor.prototype.reset = function () {
  31907. //clear last sample to avoid interpolating over the disabled period when next enabled
  31908. this._lastFrameTimeMs = null;
  31909. this._lastChangeTimeMs = null;
  31910. //wipe record
  31911. this._rollingFrameTime.reset();
  31912. };
  31913. return PerformanceMonitor;
  31914. }());
  31915. BABYLON.PerformanceMonitor = PerformanceMonitor;
  31916. /**
  31917. * RollingAverage
  31918. *
  31919. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  31920. */
  31921. var RollingAverage = /** @class */ (function () {
  31922. /**
  31923. * constructor
  31924. * @param length The number of samples required to saturate the sliding window
  31925. */
  31926. function RollingAverage(length) {
  31927. this._samples = new Array(length);
  31928. this.reset();
  31929. }
  31930. /**
  31931. * Adds a sample to the sample set
  31932. * @param v The sample value
  31933. */
  31934. RollingAverage.prototype.add = function (v) {
  31935. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  31936. var delta;
  31937. //we need to check if we've already wrapped round
  31938. if (this.isSaturated()) {
  31939. //remove bottom of stack from mean
  31940. var bottomValue = this._samples[this._pos];
  31941. delta = bottomValue - this.average;
  31942. this.average -= delta / (this._sampleCount - 1);
  31943. this._m2 -= delta * (bottomValue - this.average);
  31944. }
  31945. else {
  31946. this._sampleCount++;
  31947. }
  31948. //add new value to mean
  31949. delta = v - this.average;
  31950. this.average += delta / (this._sampleCount);
  31951. this._m2 += delta * (v - this.average);
  31952. //set the new variance
  31953. this.variance = this._m2 / (this._sampleCount - 1);
  31954. this._samples[this._pos] = v;
  31955. this._pos++;
  31956. this._pos %= this._samples.length; //positive wrap around
  31957. };
  31958. /**
  31959. * Returns previously added values or null if outside of history or outside the sliding window domain
  31960. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  31961. * @return Value previously recorded with add() or null if outside of range
  31962. */
  31963. RollingAverage.prototype.history = function (i) {
  31964. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  31965. return 0;
  31966. }
  31967. var i0 = this._wrapPosition(this._pos - 1.0);
  31968. return this._samples[this._wrapPosition(i0 - i)];
  31969. };
  31970. /**
  31971. * Returns true if enough samples have been taken to completely fill the sliding window
  31972. * @return true if sample-set saturated
  31973. */
  31974. RollingAverage.prototype.isSaturated = function () {
  31975. return this._sampleCount >= this._samples.length;
  31976. };
  31977. /**
  31978. * Resets the rolling average (equivalent to 0 samples taken so far)
  31979. */
  31980. RollingAverage.prototype.reset = function () {
  31981. this.average = 0;
  31982. this.variance = 0;
  31983. this._sampleCount = 0;
  31984. this._pos = 0;
  31985. this._m2 = 0;
  31986. };
  31987. /**
  31988. * Wraps a value around the sample range boundaries
  31989. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  31990. * @return Wrapped position in sample range
  31991. */
  31992. RollingAverage.prototype._wrapPosition = function (i) {
  31993. var max = this._samples.length;
  31994. return ((i % max) + max) % max;
  31995. };
  31996. return RollingAverage;
  31997. }());
  31998. BABYLON.RollingAverage = RollingAverage;
  31999. })(BABYLON || (BABYLON = {}));
  32000. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32001. var BABYLON;
  32002. (function (BABYLON) {
  32003. /**
  32004. * This groups together the common properties used for image processing either in direct forward pass
  32005. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32006. * or not.
  32007. */
  32008. var ImageProcessingConfiguration = /** @class */ (function () {
  32009. function ImageProcessingConfiguration() {
  32010. /**
  32011. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32012. */
  32013. this.colorCurves = new BABYLON.ColorCurves();
  32014. this._colorCurvesEnabled = false;
  32015. this._colorGradingEnabled = false;
  32016. this._colorGradingWithGreenDepth = true;
  32017. this._colorGradingBGR = true;
  32018. this._exposure = 1.0;
  32019. this._toneMappingEnabled = false;
  32020. this._contrast = 1.0;
  32021. /**
  32022. * Vignette stretch size.
  32023. */
  32024. this.vignetteStretch = 0;
  32025. /**
  32026. * Vignette centre X Offset.
  32027. */
  32028. this.vignetteCentreX = 0;
  32029. /**
  32030. * Vignette centre Y Offset.
  32031. */
  32032. this.vignetteCentreY = 0;
  32033. /**
  32034. * Vignette weight or intensity of the vignette effect.
  32035. */
  32036. this.vignetteWeight = 1.5;
  32037. /**
  32038. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32039. * if vignetteEnabled is set to true.
  32040. */
  32041. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32042. /**
  32043. * Camera field of view used by the Vignette effect.
  32044. */
  32045. this.vignetteCameraFov = 0.5;
  32046. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32047. this._vignetteEnabled = false;
  32048. this._applyByPostProcess = false;
  32049. /**
  32050. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32051. * @type {BABYLON.Observable}
  32052. */
  32053. this.onUpdateParameters = new BABYLON.Observable();
  32054. }
  32055. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32056. /**
  32057. * Gets wether the color curves effect is enabled.
  32058. */
  32059. get: function () {
  32060. return this._colorCurvesEnabled;
  32061. },
  32062. /**
  32063. * Sets wether the color curves effect is enabled.
  32064. */
  32065. set: function (value) {
  32066. if (this._colorCurvesEnabled === value) {
  32067. return;
  32068. }
  32069. this._colorCurvesEnabled = value;
  32070. this._updateParameters();
  32071. },
  32072. enumerable: true,
  32073. configurable: true
  32074. });
  32075. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32076. /**
  32077. * Gets wether the color grading effect is enabled.
  32078. */
  32079. get: function () {
  32080. return this._colorGradingEnabled;
  32081. },
  32082. /**
  32083. * Sets wether the color grading effect is enabled.
  32084. */
  32085. set: function (value) {
  32086. if (this._colorGradingEnabled === value) {
  32087. return;
  32088. }
  32089. this._colorGradingEnabled = value;
  32090. this._updateParameters();
  32091. },
  32092. enumerable: true,
  32093. configurable: true
  32094. });
  32095. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32096. /**
  32097. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32098. */
  32099. get: function () {
  32100. return this._colorGradingWithGreenDepth;
  32101. },
  32102. /**
  32103. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32104. */
  32105. set: function (value) {
  32106. if (this._colorGradingWithGreenDepth === value) {
  32107. return;
  32108. }
  32109. this._colorGradingWithGreenDepth = value;
  32110. this._updateParameters();
  32111. },
  32112. enumerable: true,
  32113. configurable: true
  32114. });
  32115. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32116. /**
  32117. * Gets wether the color grading texture contains BGR values.
  32118. */
  32119. get: function () {
  32120. return this._colorGradingBGR;
  32121. },
  32122. /**
  32123. * Sets wether the color grading texture contains BGR values.
  32124. */
  32125. set: function (value) {
  32126. if (this._colorGradingBGR === value) {
  32127. return;
  32128. }
  32129. this._colorGradingBGR = value;
  32130. this._updateParameters();
  32131. },
  32132. enumerable: true,
  32133. configurable: true
  32134. });
  32135. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32136. /**
  32137. * Gets the Exposure used in the effect.
  32138. */
  32139. get: function () {
  32140. return this._exposure;
  32141. },
  32142. /**
  32143. * Sets the Exposure used in the effect.
  32144. */
  32145. set: function (value) {
  32146. if (this._exposure === value) {
  32147. return;
  32148. }
  32149. this._exposure = value;
  32150. this._updateParameters();
  32151. },
  32152. enumerable: true,
  32153. configurable: true
  32154. });
  32155. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32156. /**
  32157. * Gets wether the tone mapping effect is enabled.
  32158. */
  32159. get: function () {
  32160. return this._toneMappingEnabled;
  32161. },
  32162. /**
  32163. * Sets wether the tone mapping effect is enabled.
  32164. */
  32165. set: function (value) {
  32166. if (this._toneMappingEnabled === value) {
  32167. return;
  32168. }
  32169. this._toneMappingEnabled = value;
  32170. this._updateParameters();
  32171. },
  32172. enumerable: true,
  32173. configurable: true
  32174. });
  32175. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32176. /**
  32177. * Gets the contrast used in the effect.
  32178. */
  32179. get: function () {
  32180. return this._contrast;
  32181. },
  32182. /**
  32183. * Sets the contrast used in the effect.
  32184. */
  32185. set: function (value) {
  32186. if (this._contrast === value) {
  32187. return;
  32188. }
  32189. this._contrast = value;
  32190. this._updateParameters();
  32191. },
  32192. enumerable: true,
  32193. configurable: true
  32194. });
  32195. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32196. /**
  32197. * Gets the vignette blend mode allowing different kind of effect.
  32198. */
  32199. get: function () {
  32200. return this._vignetteBlendMode;
  32201. },
  32202. /**
  32203. * Sets the vignette blend mode allowing different kind of effect.
  32204. */
  32205. set: function (value) {
  32206. if (this._vignetteBlendMode === value) {
  32207. return;
  32208. }
  32209. this._vignetteBlendMode = value;
  32210. this._updateParameters();
  32211. },
  32212. enumerable: true,
  32213. configurable: true
  32214. });
  32215. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32216. /**
  32217. * Gets wether the vignette effect is enabled.
  32218. */
  32219. get: function () {
  32220. return this._vignetteEnabled;
  32221. },
  32222. /**
  32223. * Sets wether the vignette effect is enabled.
  32224. */
  32225. set: function (value) {
  32226. if (this._vignetteEnabled === value) {
  32227. return;
  32228. }
  32229. this._vignetteEnabled = value;
  32230. this._updateParameters();
  32231. },
  32232. enumerable: true,
  32233. configurable: true
  32234. });
  32235. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32236. /**
  32237. * Gets wether the image processing is applied through a post process or not.
  32238. */
  32239. get: function () {
  32240. return this._applyByPostProcess;
  32241. },
  32242. /**
  32243. * Sets wether the image processing is applied through a post process or not.
  32244. */
  32245. set: function (value) {
  32246. if (this._applyByPostProcess === value) {
  32247. return;
  32248. }
  32249. this._applyByPostProcess = value;
  32250. this._updateParameters();
  32251. },
  32252. enumerable: true,
  32253. configurable: true
  32254. });
  32255. /**
  32256. * Method called each time the image processing information changes requires to recompile the effect.
  32257. */
  32258. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32259. this.onUpdateParameters.notifyObservers(this);
  32260. };
  32261. ImageProcessingConfiguration.prototype.getClassName = function () {
  32262. return "ImageProcessingConfiguration";
  32263. };
  32264. /**
  32265. * Prepare the list of uniforms associated with the Image Processing effects.
  32266. * @param uniformsList The list of uniforms used in the effect
  32267. * @param defines the list of defines currently in use
  32268. */
  32269. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32270. if (defines.EXPOSURE) {
  32271. uniforms.push("exposureLinear");
  32272. }
  32273. if (defines.CONTRAST) {
  32274. uniforms.push("contrast");
  32275. }
  32276. if (defines.COLORGRADING) {
  32277. uniforms.push("colorTransformSettings");
  32278. }
  32279. if (defines.VIGNETTE) {
  32280. uniforms.push("vInverseScreenSize");
  32281. uniforms.push("vignetteSettings1");
  32282. uniforms.push("vignetteSettings2");
  32283. }
  32284. if (defines.COLORCURVES) {
  32285. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32286. }
  32287. };
  32288. /**
  32289. * Prepare the list of samplers associated with the Image Processing effects.
  32290. * @param uniformsList The list of uniforms used in the effect
  32291. * @param defines the list of defines currently in use
  32292. */
  32293. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32294. if (defines.COLORGRADING) {
  32295. samplersList.push("txColorTransform");
  32296. }
  32297. };
  32298. /**
  32299. * Prepare the list of defines associated to the shader.
  32300. * @param defines the list of defines to complete
  32301. */
  32302. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32303. if (forPostProcess === void 0) { forPostProcess = false; }
  32304. if (forPostProcess !== this.applyByPostProcess) {
  32305. defines.VIGNETTE = false;
  32306. defines.TONEMAPPING = false;
  32307. defines.CONTRAST = false;
  32308. defines.EXPOSURE = false;
  32309. defines.COLORCURVES = false;
  32310. defines.COLORGRADING = false;
  32311. defines.COLORGRADING3D = false;
  32312. defines.IMAGEPROCESSING = false;
  32313. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32314. return;
  32315. }
  32316. defines.VIGNETTE = this.vignetteEnabled;
  32317. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32318. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32319. defines.TONEMAPPING = this.toneMappingEnabled;
  32320. defines.CONTRAST = (this.contrast !== 1.0);
  32321. defines.EXPOSURE = (this.exposure !== 1.0);
  32322. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32323. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32324. if (defines.COLORGRADING) {
  32325. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32326. }
  32327. else {
  32328. defines.COLORGRADING3D = false;
  32329. }
  32330. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32331. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32332. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32333. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32334. };
  32335. /**
  32336. * Returns true if all the image processing information are ready.
  32337. */
  32338. ImageProcessingConfiguration.prototype.isReady = function () {
  32339. // Color Grading texure can not be none blocking.
  32340. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32341. };
  32342. /**
  32343. * Binds the image processing to the shader.
  32344. * @param effect The effect to bind to
  32345. */
  32346. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32347. if (aspectRatio === void 0) { aspectRatio = 1; }
  32348. // Color Curves
  32349. if (this._colorCurvesEnabled && this.colorCurves) {
  32350. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32351. }
  32352. // Vignette
  32353. if (this._vignetteEnabled) {
  32354. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32355. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32356. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32357. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32358. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32359. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32360. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32361. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32362. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32363. var vignettePower = -2.0 * this.vignetteWeight;
  32364. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32365. }
  32366. // Exposure
  32367. effect.setFloat("exposureLinear", this.exposure);
  32368. // Contrast
  32369. effect.setFloat("contrast", this.contrast);
  32370. // Color transform settings
  32371. if (this.colorGradingTexture) {
  32372. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32373. var textureSize = this.colorGradingTexture.getSize().height;
  32374. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32375. 0.5 / textureSize, // textureOffset
  32376. textureSize, // textureSize
  32377. this.colorGradingTexture.level // weight
  32378. );
  32379. }
  32380. };
  32381. /**
  32382. * Clones the current image processing instance.
  32383. * @return The cloned image processing
  32384. */
  32385. ImageProcessingConfiguration.prototype.clone = function () {
  32386. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32387. };
  32388. /**
  32389. * Serializes the current image processing instance to a json representation.
  32390. * @return a JSON representation
  32391. */
  32392. ImageProcessingConfiguration.prototype.serialize = function () {
  32393. return BABYLON.SerializationHelper.Serialize(this);
  32394. };
  32395. /**
  32396. * Parses the image processing from a json representation.
  32397. * @param source the JSON source to parse
  32398. * @return The parsed image processing
  32399. */
  32400. ImageProcessingConfiguration.Parse = function (source) {
  32401. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32402. };
  32403. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32404. /**
  32405. * Used to apply the vignette as a mix with the pixel color.
  32406. */
  32407. get: function () {
  32408. return this._VIGNETTEMODE_MULTIPLY;
  32409. },
  32410. enumerable: true,
  32411. configurable: true
  32412. });
  32413. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32414. /**
  32415. * Used to apply the vignette as a replacement of the pixel color.
  32416. */
  32417. get: function () {
  32418. return this._VIGNETTEMODE_OPAQUE;
  32419. },
  32420. enumerable: true,
  32421. configurable: true
  32422. });
  32423. // Static constants associated to the image processing.
  32424. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32425. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32426. __decorate([
  32427. BABYLON.serializeAsColorCurves()
  32428. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32429. __decorate([
  32430. BABYLON.serialize()
  32431. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32432. __decorate([
  32433. BABYLON.serializeAsTexture()
  32434. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32435. __decorate([
  32436. BABYLON.serialize()
  32437. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32438. __decorate([
  32439. BABYLON.serialize()
  32440. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32441. __decorate([
  32442. BABYLON.serialize()
  32443. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32444. __decorate([
  32445. BABYLON.serialize()
  32446. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32447. __decorate([
  32448. BABYLON.serialize()
  32449. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32450. __decorate([
  32451. BABYLON.serialize()
  32452. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32453. __decorate([
  32454. BABYLON.serialize()
  32455. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32456. __decorate([
  32457. BABYLON.serialize()
  32458. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32459. __decorate([
  32460. BABYLON.serialize()
  32461. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32462. __decorate([
  32463. BABYLON.serialize()
  32464. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32465. __decorate([
  32466. BABYLON.serializeAsColor4()
  32467. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32468. __decorate([
  32469. BABYLON.serialize()
  32470. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32471. __decorate([
  32472. BABYLON.serialize()
  32473. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32474. __decorate([
  32475. BABYLON.serialize()
  32476. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32477. __decorate([
  32478. BABYLON.serialize()
  32479. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32480. return ImageProcessingConfiguration;
  32481. }());
  32482. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  32483. })(BABYLON || (BABYLON = {}));
  32484. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  32485. var BABYLON;
  32486. (function (BABYLON) {
  32487. /**
  32488. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  32489. * It can help converting any input color in a desired output one. This can then be used to create effects
  32490. * from sepia, black and white to sixties or futuristic rendering...
  32491. *
  32492. * The only supported format is currently 3dl.
  32493. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  32494. */
  32495. var ColorGradingTexture = /** @class */ (function (_super) {
  32496. __extends(ColorGradingTexture, _super);
  32497. /**
  32498. * Instantiates a ColorGradingTexture from the following parameters.
  32499. *
  32500. * @param url The location of the color gradind data (currently only supporting 3dl)
  32501. * @param scene The scene the texture will be used in
  32502. */
  32503. function ColorGradingTexture(url, scene) {
  32504. var _this = _super.call(this, scene) || this;
  32505. if (!url) {
  32506. return _this;
  32507. }
  32508. _this._engine = scene.getEngine();
  32509. _this._textureMatrix = BABYLON.Matrix.Identity();
  32510. _this.name = url;
  32511. _this.url = url;
  32512. _this.hasAlpha = false;
  32513. _this.isCube = false;
  32514. _this.is3D = _this._engine.webGLVersion > 1;
  32515. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32516. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32517. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32518. _this.anisotropicFilteringLevel = 1;
  32519. _this._texture = _this._getFromCache(url, true);
  32520. if (!_this._texture) {
  32521. if (!scene.useDelayedTextureLoading) {
  32522. _this.loadTexture();
  32523. }
  32524. else {
  32525. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32526. }
  32527. }
  32528. return _this;
  32529. }
  32530. /**
  32531. * Returns the texture matrix used in most of the material.
  32532. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  32533. */
  32534. ColorGradingTexture.prototype.getTextureMatrix = function () {
  32535. return this._textureMatrix;
  32536. };
  32537. /**
  32538. * Occurs when the file being loaded is a .3dl LUT file.
  32539. */
  32540. ColorGradingTexture.prototype.load3dlTexture = function () {
  32541. var engine = this._engine;
  32542. var texture;
  32543. if (engine.webGLVersion === 1) {
  32544. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32545. }
  32546. else {
  32547. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32548. }
  32549. this._texture = texture;
  32550. var callback = function (text) {
  32551. var data = null;
  32552. var tempData = null;
  32553. var line;
  32554. var lines = text.split('\n');
  32555. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  32556. var maxColor = 0;
  32557. for (var i = 0; i < lines.length; i++) {
  32558. line = lines[i];
  32559. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  32560. continue;
  32561. if (line.indexOf('#') === 0)
  32562. continue;
  32563. var words = line.split(" ");
  32564. if (size === 0) {
  32565. // Number of space + one
  32566. size = words.length;
  32567. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  32568. tempData = new Float32Array(size * size * size * 4);
  32569. continue;
  32570. }
  32571. if (size != 0) {
  32572. var r = Math.max(parseInt(words[0]), 0);
  32573. var g = Math.max(parseInt(words[1]), 0);
  32574. var b = Math.max(parseInt(words[2]), 0);
  32575. maxColor = Math.max(r, maxColor);
  32576. maxColor = Math.max(g, maxColor);
  32577. maxColor = Math.max(b, maxColor);
  32578. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  32579. if (tempData) {
  32580. tempData[pixelStorageIndex + 0] = r;
  32581. tempData[pixelStorageIndex + 1] = g;
  32582. tempData[pixelStorageIndex + 2] = b;
  32583. }
  32584. pixelIndexSlice++;
  32585. if (pixelIndexSlice % size == 0) {
  32586. pixelIndexH++;
  32587. pixelIndexSlice = 0;
  32588. if (pixelIndexH % size == 0) {
  32589. pixelIndexW++;
  32590. pixelIndexH = 0;
  32591. }
  32592. }
  32593. }
  32594. }
  32595. if (tempData && data) {
  32596. for (var i = 0; i < tempData.length; i++) {
  32597. if (i > 0 && (i + 1) % 4 === 0) {
  32598. data[i] = 255;
  32599. }
  32600. else {
  32601. var value = tempData[i];
  32602. data[i] = (value / maxColor * 255);
  32603. }
  32604. }
  32605. }
  32606. if (texture.is3D) {
  32607. texture.updateSize(size, size, size);
  32608. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32609. }
  32610. else {
  32611. texture.updateSize(size * size, size);
  32612. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32613. }
  32614. };
  32615. BABYLON.Tools.LoadFile(this.url, callback);
  32616. return this._texture;
  32617. };
  32618. /**
  32619. * Starts the loading process of the texture.
  32620. */
  32621. ColorGradingTexture.prototype.loadTexture = function () {
  32622. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  32623. this.load3dlTexture();
  32624. }
  32625. };
  32626. /**
  32627. * Clones the color gradind texture.
  32628. */
  32629. ColorGradingTexture.prototype.clone = function () {
  32630. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  32631. // Base texture
  32632. newTexture.level = this.level;
  32633. return newTexture;
  32634. };
  32635. /**
  32636. * Called during delayed load for textures.
  32637. */
  32638. ColorGradingTexture.prototype.delayLoad = function () {
  32639. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32640. return;
  32641. }
  32642. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32643. this._texture = this._getFromCache(this.url, true);
  32644. if (!this._texture) {
  32645. this.loadTexture();
  32646. }
  32647. };
  32648. /**
  32649. * Parses a color grading texture serialized by Babylon.
  32650. * @param parsedTexture The texture information being parsedTexture
  32651. * @param scene The scene to load the texture in
  32652. * @param rootUrl The root url of the data assets to load
  32653. * @return A color gradind texture
  32654. */
  32655. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32656. var texture = null;
  32657. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  32658. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  32659. texture.name = parsedTexture.name;
  32660. texture.level = parsedTexture.level;
  32661. }
  32662. return texture;
  32663. };
  32664. /**
  32665. * Serializes the LUT texture to json format.
  32666. */
  32667. ColorGradingTexture.prototype.serialize = function () {
  32668. if (!this.name) {
  32669. return null;
  32670. }
  32671. var serializationObject = {};
  32672. serializationObject.name = this.name;
  32673. serializationObject.level = this.level;
  32674. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32675. return serializationObject;
  32676. };
  32677. /**
  32678. * Empty line regex stored for GC.
  32679. */
  32680. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32681. return ColorGradingTexture;
  32682. }(BABYLON.BaseTexture));
  32683. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32684. })(BABYLON || (BABYLON = {}));
  32685. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32686. var BABYLON;
  32687. (function (BABYLON) {
  32688. /**
  32689. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32690. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32691. * 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;
  32692. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32693. */
  32694. var ColorCurves = /** @class */ (function () {
  32695. function ColorCurves() {
  32696. this._dirty = true;
  32697. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32698. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32699. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32700. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32701. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32702. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32703. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32704. this._globalHue = 30;
  32705. this._globalDensity = 0;
  32706. this._globalSaturation = 0;
  32707. this._globalExposure = 0;
  32708. this._highlightsHue = 30;
  32709. this._highlightsDensity = 0;
  32710. this._highlightsSaturation = 0;
  32711. this._highlightsExposure = 0;
  32712. this._midtonesHue = 30;
  32713. this._midtonesDensity = 0;
  32714. this._midtonesSaturation = 0;
  32715. this._midtonesExposure = 0;
  32716. this._shadowsHue = 30;
  32717. this._shadowsDensity = 0;
  32718. this._shadowsSaturation = 0;
  32719. this._shadowsExposure = 0;
  32720. }
  32721. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32722. /**
  32723. * Gets the global Hue value.
  32724. * 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).
  32725. */
  32726. get: function () {
  32727. return this._globalHue;
  32728. },
  32729. /**
  32730. * Sets the global Hue value.
  32731. * 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).
  32732. */
  32733. set: function (value) {
  32734. this._globalHue = value;
  32735. this._dirty = true;
  32736. },
  32737. enumerable: true,
  32738. configurable: true
  32739. });
  32740. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32741. /**
  32742. * Gets the global Density value.
  32743. * 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.
  32744. * Values less than zero provide a filter of opposite hue.
  32745. */
  32746. get: function () {
  32747. return this._globalDensity;
  32748. },
  32749. /**
  32750. * Sets the global Density value.
  32751. * 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.
  32752. * Values less than zero provide a filter of opposite hue.
  32753. */
  32754. set: function (value) {
  32755. this._globalDensity = value;
  32756. this._dirty = true;
  32757. },
  32758. enumerable: true,
  32759. configurable: true
  32760. });
  32761. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32762. /**
  32763. * Gets the global Saturation value.
  32764. * 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.
  32765. */
  32766. get: function () {
  32767. return this._globalSaturation;
  32768. },
  32769. /**
  32770. * Sets the global Saturation value.
  32771. * 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.
  32772. */
  32773. set: function (value) {
  32774. this._globalSaturation = value;
  32775. this._dirty = true;
  32776. },
  32777. enumerable: true,
  32778. configurable: true
  32779. });
  32780. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32781. /**
  32782. * Gets the highlights Hue value.
  32783. * 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).
  32784. */
  32785. get: function () {
  32786. return this._highlightsHue;
  32787. },
  32788. /**
  32789. * Sets the highlights Hue value.
  32790. * 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).
  32791. */
  32792. set: function (value) {
  32793. this._highlightsHue = value;
  32794. this._dirty = true;
  32795. },
  32796. enumerable: true,
  32797. configurable: true
  32798. });
  32799. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32800. /**
  32801. * Gets the highlights Density value.
  32802. * 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.
  32803. * Values less than zero provide a filter of opposite hue.
  32804. */
  32805. get: function () {
  32806. return this._highlightsDensity;
  32807. },
  32808. /**
  32809. * Sets the highlights Density value.
  32810. * 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.
  32811. * Values less than zero provide a filter of opposite hue.
  32812. */
  32813. set: function (value) {
  32814. this._highlightsDensity = value;
  32815. this._dirty = true;
  32816. },
  32817. enumerable: true,
  32818. configurable: true
  32819. });
  32820. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  32821. /**
  32822. * Gets the highlights Saturation value.
  32823. * 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.
  32824. */
  32825. get: function () {
  32826. return this._highlightsSaturation;
  32827. },
  32828. /**
  32829. * Sets the highlights Saturation value.
  32830. * 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.
  32831. */
  32832. set: function (value) {
  32833. this._highlightsSaturation = value;
  32834. this._dirty = true;
  32835. },
  32836. enumerable: true,
  32837. configurable: true
  32838. });
  32839. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  32840. /**
  32841. * Gets the highlights Exposure value.
  32842. * 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.
  32843. */
  32844. get: function () {
  32845. return this._highlightsExposure;
  32846. },
  32847. /**
  32848. * Sets the highlights Exposure value.
  32849. * 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.
  32850. */
  32851. set: function (value) {
  32852. this._highlightsExposure = value;
  32853. this._dirty = true;
  32854. },
  32855. enumerable: true,
  32856. configurable: true
  32857. });
  32858. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  32859. /**
  32860. * Gets the midtones Hue value.
  32861. * 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).
  32862. */
  32863. get: function () {
  32864. return this._midtonesHue;
  32865. },
  32866. /**
  32867. * Sets the midtones Hue value.
  32868. * 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).
  32869. */
  32870. set: function (value) {
  32871. this._midtonesHue = value;
  32872. this._dirty = true;
  32873. },
  32874. enumerable: true,
  32875. configurable: true
  32876. });
  32877. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  32878. /**
  32879. * Gets the midtones Density value.
  32880. * 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.
  32881. * Values less than zero provide a filter of opposite hue.
  32882. */
  32883. get: function () {
  32884. return this._midtonesDensity;
  32885. },
  32886. /**
  32887. * Sets the midtones Density value.
  32888. * 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.
  32889. * Values less than zero provide a filter of opposite hue.
  32890. */
  32891. set: function (value) {
  32892. this._midtonesDensity = value;
  32893. this._dirty = true;
  32894. },
  32895. enumerable: true,
  32896. configurable: true
  32897. });
  32898. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  32899. /**
  32900. * Gets the midtones Saturation value.
  32901. * 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.
  32902. */
  32903. get: function () {
  32904. return this._midtonesSaturation;
  32905. },
  32906. /**
  32907. * Sets the midtones Saturation value.
  32908. * 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.
  32909. */
  32910. set: function (value) {
  32911. this._midtonesSaturation = value;
  32912. this._dirty = true;
  32913. },
  32914. enumerable: true,
  32915. configurable: true
  32916. });
  32917. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  32918. /**
  32919. * Gets the midtones Exposure value.
  32920. * 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.
  32921. */
  32922. get: function () {
  32923. return this._midtonesExposure;
  32924. },
  32925. /**
  32926. * Sets the midtones Exposure value.
  32927. * 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.
  32928. */
  32929. set: function (value) {
  32930. this._midtonesExposure = value;
  32931. this._dirty = true;
  32932. },
  32933. enumerable: true,
  32934. configurable: true
  32935. });
  32936. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  32937. /**
  32938. * Gets the shadows Hue value.
  32939. * 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).
  32940. */
  32941. get: function () {
  32942. return this._shadowsHue;
  32943. },
  32944. /**
  32945. * Sets the shadows Hue value.
  32946. * 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).
  32947. */
  32948. set: function (value) {
  32949. this._shadowsHue = value;
  32950. this._dirty = true;
  32951. },
  32952. enumerable: true,
  32953. configurable: true
  32954. });
  32955. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  32956. /**
  32957. * Gets the shadows Density value.
  32958. * 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.
  32959. * Values less than zero provide a filter of opposite hue.
  32960. */
  32961. get: function () {
  32962. return this._shadowsDensity;
  32963. },
  32964. /**
  32965. * Sets the shadows Density value.
  32966. * 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.
  32967. * Values less than zero provide a filter of opposite hue.
  32968. */
  32969. set: function (value) {
  32970. this._shadowsDensity = value;
  32971. this._dirty = true;
  32972. },
  32973. enumerable: true,
  32974. configurable: true
  32975. });
  32976. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  32977. /**
  32978. * Gets the shadows Saturation value.
  32979. * 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.
  32980. */
  32981. get: function () {
  32982. return this._shadowsSaturation;
  32983. },
  32984. /**
  32985. * Sets the shadows Saturation value.
  32986. * 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.
  32987. */
  32988. set: function (value) {
  32989. this._shadowsSaturation = value;
  32990. this._dirty = true;
  32991. },
  32992. enumerable: true,
  32993. configurable: true
  32994. });
  32995. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  32996. /**
  32997. * Gets the shadows Exposure value.
  32998. * 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.
  32999. */
  33000. get: function () {
  33001. return this._shadowsExposure;
  33002. },
  33003. /**
  33004. * Sets the shadows Exposure value.
  33005. * 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.
  33006. */
  33007. set: function (value) {
  33008. this._shadowsExposure = value;
  33009. this._dirty = true;
  33010. },
  33011. enumerable: true,
  33012. configurable: true
  33013. });
  33014. ColorCurves.prototype.getClassName = function () {
  33015. return "ColorCurves";
  33016. };
  33017. /**
  33018. * Binds the color curves to the shader.
  33019. * @param colorCurves The color curve to bind
  33020. * @param effect The effect to bind to
  33021. */
  33022. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33023. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33024. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33025. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33026. if (colorCurves._dirty) {
  33027. colorCurves._dirty = false;
  33028. // Fill in global info.
  33029. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33030. // Compute highlights info.
  33031. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33032. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33033. // Compute midtones info.
  33034. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33035. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33036. // Compute shadows info.
  33037. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33038. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33039. // Compute deltas (neutral is midtones).
  33040. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33041. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33042. }
  33043. if (effect) {
  33044. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33045. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33046. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33047. }
  33048. };
  33049. /**
  33050. * Prepare the list of uniforms associated with the ColorCurves effects.
  33051. * @param uniformsList The list of uniforms used in the effect
  33052. */
  33053. ColorCurves.PrepareUniforms = function (uniformsList) {
  33054. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33055. };
  33056. /**
  33057. * Returns color grading data based on a hue, density, saturation and exposure value.
  33058. * @param filterHue The hue of the color filter.
  33059. * @param filterDensity The density of the color filter.
  33060. * @param saturation The saturation.
  33061. * @param exposure The exposure.
  33062. * @param result The result data container.
  33063. */
  33064. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33065. if (hue == null) {
  33066. return;
  33067. }
  33068. hue = ColorCurves.clamp(hue, 0, 360);
  33069. density = ColorCurves.clamp(density, -100, 100);
  33070. saturation = ColorCurves.clamp(saturation, -100, 100);
  33071. exposure = ColorCurves.clamp(exposure, -100, 100);
  33072. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33073. // so that the maximum filter density is only 50% control. This provides fine control
  33074. // for small values and reasonable range.
  33075. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33076. density *= 0.5;
  33077. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33078. if (density < 0) {
  33079. density *= -1;
  33080. hue = (hue + 180) % 360;
  33081. }
  33082. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33083. result.scaleToRef(2, result);
  33084. result.a = 1 + 0.01 * saturation;
  33085. };
  33086. /**
  33087. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33088. * @param value The input slider value in range [-100,100].
  33089. * @returns Adjusted value.
  33090. */
  33091. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33092. value /= 100;
  33093. var x = Math.abs(value);
  33094. x = Math.pow(x, 2);
  33095. if (value < 0) {
  33096. x *= -1;
  33097. }
  33098. x *= 100;
  33099. return x;
  33100. };
  33101. /**
  33102. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33103. * @param hue The hue (H) input.
  33104. * @param saturation The saturation (S) input.
  33105. * @param brightness The brightness (B) input.
  33106. * @result An RGBA color represented as Vector4.
  33107. */
  33108. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33109. var h = ColorCurves.clamp(hue, 0, 360);
  33110. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33111. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33112. if (s === 0) {
  33113. result.r = v;
  33114. result.g = v;
  33115. result.b = v;
  33116. }
  33117. else {
  33118. // sector 0 to 5
  33119. h /= 60;
  33120. var i = Math.floor(h);
  33121. // fractional part of h
  33122. var f = h - i;
  33123. var p = v * (1 - s);
  33124. var q = v * (1 - s * f);
  33125. var t = v * (1 - s * (1 - f));
  33126. switch (i) {
  33127. case 0:
  33128. result.r = v;
  33129. result.g = t;
  33130. result.b = p;
  33131. break;
  33132. case 1:
  33133. result.r = q;
  33134. result.g = v;
  33135. result.b = p;
  33136. break;
  33137. case 2:
  33138. result.r = p;
  33139. result.g = v;
  33140. result.b = t;
  33141. break;
  33142. case 3:
  33143. result.r = p;
  33144. result.g = q;
  33145. result.b = v;
  33146. break;
  33147. case 4:
  33148. result.r = t;
  33149. result.g = p;
  33150. result.b = v;
  33151. break;
  33152. default:// case 5:
  33153. result.r = v;
  33154. result.g = p;
  33155. result.b = q;
  33156. break;
  33157. }
  33158. }
  33159. result.a = 1;
  33160. };
  33161. /**
  33162. * Returns a value clamped between min and max
  33163. * @param value The value to clamp
  33164. * @param min The minimum of value
  33165. * @param max The maximum of value
  33166. * @returns The clamped value.
  33167. */
  33168. ColorCurves.clamp = function (value, min, max) {
  33169. return Math.min(Math.max(value, min), max);
  33170. };
  33171. /**
  33172. * Clones the current color curve instance.
  33173. * @return The cloned curves
  33174. */
  33175. ColorCurves.prototype.clone = function () {
  33176. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33177. };
  33178. /**
  33179. * Serializes the current color curve instance to a json representation.
  33180. * @return a JSON representation
  33181. */
  33182. ColorCurves.prototype.serialize = function () {
  33183. return BABYLON.SerializationHelper.Serialize(this);
  33184. };
  33185. /**
  33186. * Parses the color curve from a json representation.
  33187. * @param source the JSON source to parse
  33188. * @return The parsed curves
  33189. */
  33190. ColorCurves.Parse = function (source) {
  33191. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33192. };
  33193. __decorate([
  33194. BABYLON.serialize()
  33195. ], ColorCurves.prototype, "_globalHue", void 0);
  33196. __decorate([
  33197. BABYLON.serialize()
  33198. ], ColorCurves.prototype, "_globalDensity", void 0);
  33199. __decorate([
  33200. BABYLON.serialize()
  33201. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33202. __decorate([
  33203. BABYLON.serialize()
  33204. ], ColorCurves.prototype, "_globalExposure", void 0);
  33205. __decorate([
  33206. BABYLON.serialize()
  33207. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33208. __decorate([
  33209. BABYLON.serialize()
  33210. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33211. __decorate([
  33212. BABYLON.serialize()
  33213. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33214. __decorate([
  33215. BABYLON.serialize()
  33216. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33217. __decorate([
  33218. BABYLON.serialize()
  33219. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33220. __decorate([
  33221. BABYLON.serialize()
  33222. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33223. __decorate([
  33224. BABYLON.serialize()
  33225. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33226. __decorate([
  33227. BABYLON.serialize()
  33228. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33229. return ColorCurves;
  33230. }());
  33231. BABYLON.ColorCurves = ColorCurves;
  33232. })(BABYLON || (BABYLON = {}));
  33233. //# sourceMappingURL=babylon.colorCurves.js.map
  33234. var BABYLON;
  33235. (function (BABYLON) {
  33236. var StandardMaterialDefines = /** @class */ (function (_super) {
  33237. __extends(StandardMaterialDefines, _super);
  33238. function StandardMaterialDefines() {
  33239. var _this = _super.call(this) || this;
  33240. _this.MAINUV1 = false;
  33241. _this.MAINUV2 = false;
  33242. _this.DIFFUSE = false;
  33243. _this.DIFFUSEDIRECTUV = 0;
  33244. _this.AMBIENT = false;
  33245. _this.AMBIENTDIRECTUV = 0;
  33246. _this.OPACITY = false;
  33247. _this.OPACITYDIRECTUV = 0;
  33248. _this.OPACITYRGB = false;
  33249. _this.REFLECTION = false;
  33250. _this.EMISSIVE = false;
  33251. _this.EMISSIVEDIRECTUV = 0;
  33252. _this.SPECULAR = false;
  33253. _this.SPECULARDIRECTUV = 0;
  33254. _this.BUMP = false;
  33255. _this.BUMPDIRECTUV = 0;
  33256. _this.PARALLAX = false;
  33257. _this.PARALLAXOCCLUSION = false;
  33258. _this.SPECULAROVERALPHA = false;
  33259. _this.CLIPPLANE = false;
  33260. _this.ALPHATEST = false;
  33261. _this.DEPTHPREPASS = false;
  33262. _this.ALPHAFROMDIFFUSE = false;
  33263. _this.POINTSIZE = false;
  33264. _this.FOG = false;
  33265. _this.SPECULARTERM = false;
  33266. _this.DIFFUSEFRESNEL = false;
  33267. _this.OPACITYFRESNEL = false;
  33268. _this.REFLECTIONFRESNEL = false;
  33269. _this.REFRACTIONFRESNEL = false;
  33270. _this.EMISSIVEFRESNEL = false;
  33271. _this.FRESNEL = false;
  33272. _this.NORMAL = false;
  33273. _this.UV1 = false;
  33274. _this.UV2 = false;
  33275. _this.VERTEXCOLOR = false;
  33276. _this.VERTEXALPHA = false;
  33277. _this.NUM_BONE_INFLUENCERS = 0;
  33278. _this.BonesPerMesh = 0;
  33279. _this.INSTANCES = false;
  33280. _this.GLOSSINESS = false;
  33281. _this.ROUGHNESS = false;
  33282. _this.EMISSIVEASILLUMINATION = false;
  33283. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33284. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33285. _this.LIGHTMAP = false;
  33286. _this.LIGHTMAPDIRECTUV = 0;
  33287. _this.USELIGHTMAPASSHADOWMAP = false;
  33288. _this.REFLECTIONMAP_3D = false;
  33289. _this.REFLECTIONMAP_SPHERICAL = false;
  33290. _this.REFLECTIONMAP_PLANAR = false;
  33291. _this.REFLECTIONMAP_CUBIC = false;
  33292. _this.REFLECTIONMAP_PROJECTION = false;
  33293. _this.REFLECTIONMAP_SKYBOX = false;
  33294. _this.REFLECTIONMAP_EXPLICIT = false;
  33295. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33296. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33297. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33298. _this.INVERTCUBICMAP = false;
  33299. _this.LOGARITHMICDEPTH = false;
  33300. _this.REFRACTION = false;
  33301. _this.REFRACTIONMAP_3D = false;
  33302. _this.REFLECTIONOVERALPHA = false;
  33303. _this.TWOSIDEDLIGHTING = false;
  33304. _this.SHADOWFLOAT = false;
  33305. _this.MORPHTARGETS = false;
  33306. _this.MORPHTARGETS_NORMAL = false;
  33307. _this.MORPHTARGETS_TANGENT = false;
  33308. _this.NUM_MORPH_INFLUENCERS = 0;
  33309. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33310. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33311. _this.IMAGEPROCESSING = false;
  33312. _this.VIGNETTE = false;
  33313. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33314. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33315. _this.TONEMAPPING = false;
  33316. _this.CONTRAST = false;
  33317. _this.COLORCURVES = false;
  33318. _this.COLORGRADING = false;
  33319. _this.COLORGRADING3D = false;
  33320. _this.SAMPLER3DGREENDEPTH = false;
  33321. _this.SAMPLER3DBGRMAP = false;
  33322. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33323. _this.EXPOSURE = false;
  33324. _this.rebuild();
  33325. return _this;
  33326. }
  33327. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33328. var modes = [
  33329. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33330. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33331. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33332. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33333. ];
  33334. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33335. var mode = modes_1[_i];
  33336. this[mode] = (mode === modeToEnable);
  33337. }
  33338. };
  33339. return StandardMaterialDefines;
  33340. }(BABYLON.MaterialDefines));
  33341. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33342. var StandardMaterial = /** @class */ (function (_super) {
  33343. __extends(StandardMaterial, _super);
  33344. function StandardMaterial(name, scene) {
  33345. var _this = _super.call(this, name, scene) || this;
  33346. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33347. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33348. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33349. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33350. _this.specularPower = 64;
  33351. _this._useAlphaFromDiffuseTexture = false;
  33352. _this._useEmissiveAsIllumination = false;
  33353. _this._linkEmissiveWithDiffuse = false;
  33354. _this._useSpecularOverAlpha = false;
  33355. _this._useReflectionOverAlpha = false;
  33356. _this._disableLighting = false;
  33357. _this._useParallax = false;
  33358. _this._useParallaxOcclusion = false;
  33359. _this.parallaxScaleBias = 0.05;
  33360. _this._roughness = 0;
  33361. _this.indexOfRefraction = 0.98;
  33362. _this.invertRefractionY = true;
  33363. _this._useLightmapAsShadowmap = false;
  33364. _this._useReflectionFresnelFromSpecular = false;
  33365. _this._useGlossinessFromSpecularMapAlpha = false;
  33366. _this._maxSimultaneousLights = 4;
  33367. /**
  33368. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33369. */
  33370. _this._invertNormalMapX = false;
  33371. /**
  33372. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33373. */
  33374. _this._invertNormalMapY = false;
  33375. /**
  33376. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33377. */
  33378. _this._twoSidedLighting = false;
  33379. _this._renderTargets = new BABYLON.SmartArray(16);
  33380. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33381. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33382. // Setup the default processing configuration to the scene.
  33383. _this._attachImageProcessingConfiguration(null);
  33384. _this.getRenderTargetTextures = function () {
  33385. _this._renderTargets.reset();
  33386. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33387. _this._renderTargets.push(_this._reflectionTexture);
  33388. }
  33389. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33390. _this._renderTargets.push(_this._refractionTexture);
  33391. }
  33392. return _this._renderTargets;
  33393. };
  33394. return _this;
  33395. }
  33396. ;
  33397. ;
  33398. ;
  33399. ;
  33400. ;
  33401. ;
  33402. ;
  33403. ;
  33404. ;
  33405. ;
  33406. ;
  33407. ;
  33408. ;
  33409. ;
  33410. ;
  33411. ;
  33412. ;
  33413. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33414. /**
  33415. * Gets the image processing configuration used either in this material.
  33416. */
  33417. get: function () {
  33418. return this._imageProcessingConfiguration;
  33419. },
  33420. /**
  33421. * Sets the Default image processing configuration used either in the this material.
  33422. *
  33423. * If sets to null, the scene one is in use.
  33424. */
  33425. set: function (value) {
  33426. this._attachImageProcessingConfiguration(value);
  33427. // Ensure the effect will be rebuilt.
  33428. this._markAllSubMeshesAsTexturesDirty();
  33429. },
  33430. enumerable: true,
  33431. configurable: true
  33432. });
  33433. /**
  33434. * Attaches a new image processing configuration to the Standard Material.
  33435. * @param configuration
  33436. */
  33437. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33438. var _this = this;
  33439. if (configuration === this._imageProcessingConfiguration) {
  33440. return;
  33441. }
  33442. // Detaches observer.
  33443. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33444. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33445. }
  33446. // Pick the scene configuration if needed.
  33447. if (!configuration) {
  33448. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33449. }
  33450. else {
  33451. this._imageProcessingConfiguration = configuration;
  33452. }
  33453. // Attaches observer.
  33454. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33455. _this._markAllSubMeshesAsImageProcessingDirty();
  33456. });
  33457. };
  33458. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33459. /**
  33460. * Gets wether the color curves effect is enabled.
  33461. */
  33462. get: function () {
  33463. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33464. },
  33465. /**
  33466. * Sets wether the color curves effect is enabled.
  33467. */
  33468. set: function (value) {
  33469. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33470. },
  33471. enumerable: true,
  33472. configurable: true
  33473. });
  33474. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33475. /**
  33476. * Gets wether the color grading effect is enabled.
  33477. */
  33478. get: function () {
  33479. return this.imageProcessingConfiguration.colorGradingEnabled;
  33480. },
  33481. /**
  33482. * Gets wether the color grading effect is enabled.
  33483. */
  33484. set: function (value) {
  33485. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33486. },
  33487. enumerable: true,
  33488. configurable: true
  33489. });
  33490. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  33491. /**
  33492. * Gets wether tonemapping is enabled or not.
  33493. */
  33494. get: function () {
  33495. return this._imageProcessingConfiguration.toneMappingEnabled;
  33496. },
  33497. /**
  33498. * Sets wether tonemapping is enabled or not
  33499. */
  33500. set: function (value) {
  33501. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33502. },
  33503. enumerable: true,
  33504. configurable: true
  33505. });
  33506. ;
  33507. ;
  33508. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  33509. /**
  33510. * The camera exposure used on this material.
  33511. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33512. * This corresponds to a photographic exposure.
  33513. */
  33514. get: function () {
  33515. return this._imageProcessingConfiguration.exposure;
  33516. },
  33517. /**
  33518. * The camera exposure used on this material.
  33519. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33520. * This corresponds to a photographic exposure.
  33521. */
  33522. set: function (value) {
  33523. this._imageProcessingConfiguration.exposure = value;
  33524. },
  33525. enumerable: true,
  33526. configurable: true
  33527. });
  33528. ;
  33529. ;
  33530. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  33531. /**
  33532. * Gets The camera contrast used on this material.
  33533. */
  33534. get: function () {
  33535. return this._imageProcessingConfiguration.contrast;
  33536. },
  33537. /**
  33538. * Sets The camera contrast used on this material.
  33539. */
  33540. set: function (value) {
  33541. this._imageProcessingConfiguration.contrast = value;
  33542. },
  33543. enumerable: true,
  33544. configurable: true
  33545. });
  33546. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  33547. /**
  33548. * Gets the Color Grading 2D Lookup Texture.
  33549. */
  33550. get: function () {
  33551. return this._imageProcessingConfiguration.colorGradingTexture;
  33552. },
  33553. /**
  33554. * Sets the Color Grading 2D Lookup Texture.
  33555. */
  33556. set: function (value) {
  33557. this._imageProcessingConfiguration.colorGradingTexture = value;
  33558. },
  33559. enumerable: true,
  33560. configurable: true
  33561. });
  33562. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  33563. /**
  33564. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33565. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33566. * 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;
  33567. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33568. */
  33569. get: function () {
  33570. return this._imageProcessingConfiguration.colorCurves;
  33571. },
  33572. /**
  33573. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33574. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33575. * 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;
  33576. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33577. */
  33578. set: function (value) {
  33579. this._imageProcessingConfiguration.colorCurves = value;
  33580. },
  33581. enumerable: true,
  33582. configurable: true
  33583. });
  33584. StandardMaterial.prototype.getClassName = function () {
  33585. return "StandardMaterial";
  33586. };
  33587. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  33588. get: function () {
  33589. return this._useLogarithmicDepth;
  33590. },
  33591. set: function (value) {
  33592. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33593. this._markAllSubMeshesAsMiscDirty();
  33594. },
  33595. enumerable: true,
  33596. configurable: true
  33597. });
  33598. StandardMaterial.prototype.needAlphaBlending = function () {
  33599. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  33600. };
  33601. StandardMaterial.prototype.needAlphaTesting = function () {
  33602. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  33603. };
  33604. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  33605. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  33606. };
  33607. StandardMaterial.prototype.getAlphaTestTexture = function () {
  33608. return this._diffuseTexture;
  33609. };
  33610. /**
  33611. * Child classes can use it to update shaders
  33612. */
  33613. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33614. if (useInstances === void 0) { useInstances = false; }
  33615. if (subMesh.effect && this.isFrozen) {
  33616. if (this._wasPreviouslyReady && subMesh.effect) {
  33617. return true;
  33618. }
  33619. }
  33620. if (!subMesh._materialDefines) {
  33621. subMesh._materialDefines = new StandardMaterialDefines();
  33622. }
  33623. var scene = this.getScene();
  33624. var defines = subMesh._materialDefines;
  33625. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33626. if (defines._renderId === scene.getRenderId()) {
  33627. return true;
  33628. }
  33629. }
  33630. var engine = scene.getEngine();
  33631. // Lights
  33632. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33633. // Textures
  33634. if (defines._areTexturesDirty) {
  33635. defines._needUVs = false;
  33636. defines.MAINUV1 = false;
  33637. defines.MAINUV2 = false;
  33638. if (scene.texturesEnabled) {
  33639. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33640. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  33641. return false;
  33642. }
  33643. else {
  33644. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  33645. }
  33646. }
  33647. else {
  33648. defines.DIFFUSE = false;
  33649. }
  33650. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33651. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33652. return false;
  33653. }
  33654. else {
  33655. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33656. }
  33657. }
  33658. else {
  33659. defines.AMBIENT = false;
  33660. }
  33661. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33662. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33663. return false;
  33664. }
  33665. else {
  33666. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33667. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33668. }
  33669. }
  33670. else {
  33671. defines.OPACITY = false;
  33672. }
  33673. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33674. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  33675. return false;
  33676. }
  33677. else {
  33678. defines._needNormals = true;
  33679. defines.REFLECTION = true;
  33680. defines.ROUGHNESS = (this._roughness > 0);
  33681. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  33682. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  33683. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  33684. switch (this._reflectionTexture.coordinatesMode) {
  33685. case BABYLON.Texture.CUBIC_MODE:
  33686. case BABYLON.Texture.INVCUBIC_MODE:
  33687. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33688. break;
  33689. case BABYLON.Texture.EXPLICIT_MODE:
  33690. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33691. break;
  33692. case BABYLON.Texture.PLANAR_MODE:
  33693. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33694. break;
  33695. case BABYLON.Texture.PROJECTION_MODE:
  33696. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33697. break;
  33698. case BABYLON.Texture.SKYBOX_MODE:
  33699. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33700. break;
  33701. case BABYLON.Texture.SPHERICAL_MODE:
  33702. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33703. break;
  33704. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33705. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33706. break;
  33707. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33708. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33709. break;
  33710. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33711. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33712. break;
  33713. }
  33714. }
  33715. }
  33716. else {
  33717. defines.REFLECTION = false;
  33718. }
  33719. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33720. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33721. return false;
  33722. }
  33723. else {
  33724. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33725. }
  33726. }
  33727. else {
  33728. defines.EMISSIVE = false;
  33729. }
  33730. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33731. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33732. return false;
  33733. }
  33734. else {
  33735. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33736. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33737. }
  33738. }
  33739. else {
  33740. defines.LIGHTMAP = false;
  33741. }
  33742. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33743. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33744. return false;
  33745. }
  33746. else {
  33747. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33748. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33749. }
  33750. }
  33751. else {
  33752. defines.SPECULAR = false;
  33753. }
  33754. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33755. // Bump texure can not be not blocking.
  33756. if (!this._bumpTexture.isReady()) {
  33757. return false;
  33758. }
  33759. else {
  33760. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33761. defines.PARALLAX = this._useParallax;
  33762. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33763. }
  33764. }
  33765. else {
  33766. defines.BUMP = false;
  33767. }
  33768. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33769. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33770. return false;
  33771. }
  33772. else {
  33773. defines._needUVs = true;
  33774. defines.REFRACTION = true;
  33775. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33776. }
  33777. }
  33778. else {
  33779. defines.REFRACTION = false;
  33780. }
  33781. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33782. }
  33783. else {
  33784. defines.DIFFUSE = false;
  33785. defines.AMBIENT = false;
  33786. defines.OPACITY = false;
  33787. defines.REFLECTION = false;
  33788. defines.EMISSIVE = false;
  33789. defines.LIGHTMAP = false;
  33790. defines.BUMP = false;
  33791. defines.REFRACTION = false;
  33792. }
  33793. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33794. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33795. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33796. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33797. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33798. }
  33799. if (defines._areImageProcessingDirty) {
  33800. if (!this._imageProcessingConfiguration.isReady()) {
  33801. return false;
  33802. }
  33803. this._imageProcessingConfiguration.prepareDefines(defines);
  33804. }
  33805. if (defines._areFresnelDirty) {
  33806. if (StandardMaterial.FresnelEnabled) {
  33807. // Fresnel
  33808. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33809. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  33810. this._reflectionFresnelParameters) {
  33811. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  33812. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  33813. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  33814. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  33815. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  33816. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  33817. defines._needNormals = true;
  33818. defines.FRESNEL = true;
  33819. }
  33820. }
  33821. else {
  33822. defines.FRESNEL = false;
  33823. }
  33824. }
  33825. // Misc.
  33826. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  33827. // Attribs
  33828. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  33829. // Values that need to be evaluated on every frame
  33830. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  33831. // Get correct effect
  33832. if (defines.isDirty) {
  33833. defines.markAsProcessed();
  33834. scene.resetCachedMaterial();
  33835. // Fallbacks
  33836. var fallbacks = new BABYLON.EffectFallbacks();
  33837. if (defines.REFLECTION) {
  33838. fallbacks.addFallback(0, "REFLECTION");
  33839. }
  33840. if (defines.SPECULAR) {
  33841. fallbacks.addFallback(0, "SPECULAR");
  33842. }
  33843. if (defines.BUMP) {
  33844. fallbacks.addFallback(0, "BUMP");
  33845. }
  33846. if (defines.PARALLAX) {
  33847. fallbacks.addFallback(1, "PARALLAX");
  33848. }
  33849. if (defines.PARALLAXOCCLUSION) {
  33850. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  33851. }
  33852. if (defines.SPECULAROVERALPHA) {
  33853. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  33854. }
  33855. if (defines.FOG) {
  33856. fallbacks.addFallback(1, "FOG");
  33857. }
  33858. if (defines.POINTSIZE) {
  33859. fallbacks.addFallback(0, "POINTSIZE");
  33860. }
  33861. if (defines.LOGARITHMICDEPTH) {
  33862. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  33863. }
  33864. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  33865. if (defines.SPECULARTERM) {
  33866. fallbacks.addFallback(0, "SPECULARTERM");
  33867. }
  33868. if (defines.DIFFUSEFRESNEL) {
  33869. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  33870. }
  33871. if (defines.OPACITYFRESNEL) {
  33872. fallbacks.addFallback(2, "OPACITYFRESNEL");
  33873. }
  33874. if (defines.REFLECTIONFRESNEL) {
  33875. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  33876. }
  33877. if (defines.EMISSIVEFRESNEL) {
  33878. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  33879. }
  33880. if (defines.FRESNEL) {
  33881. fallbacks.addFallback(4, "FRESNEL");
  33882. }
  33883. //Attributes
  33884. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33885. if (defines.NORMAL) {
  33886. attribs.push(BABYLON.VertexBuffer.NormalKind);
  33887. }
  33888. if (defines.UV1) {
  33889. attribs.push(BABYLON.VertexBuffer.UVKind);
  33890. }
  33891. if (defines.UV2) {
  33892. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33893. }
  33894. if (defines.VERTEXCOLOR) {
  33895. attribs.push(BABYLON.VertexBuffer.ColorKind);
  33896. }
  33897. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  33898. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  33899. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  33900. var shaderName = "default";
  33901. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  33902. "vFogInfos", "vFogColor", "pointSize",
  33903. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  33904. "mBones",
  33905. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  33906. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  33907. "logarithmicDepthConstant", "vTangentSpaceParams"
  33908. ];
  33909. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  33910. var uniformBuffers = ["Material", "Scene"];
  33911. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  33912. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  33913. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  33914. uniformsNames: uniforms,
  33915. uniformBuffersNames: uniformBuffers,
  33916. samplers: samplers,
  33917. defines: defines,
  33918. maxSimultaneousLights: this._maxSimultaneousLights
  33919. });
  33920. if (this.customShaderNameResolve) {
  33921. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  33922. }
  33923. var join = defines.toString();
  33924. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  33925. attributes: attribs,
  33926. uniformsNames: uniforms,
  33927. uniformBuffersNames: uniformBuffers,
  33928. samplers: samplers,
  33929. defines: join,
  33930. fallbacks: fallbacks,
  33931. onCompiled: this.onCompiled,
  33932. onError: this.onError,
  33933. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  33934. }, engine), defines);
  33935. this.buildUniformLayout();
  33936. }
  33937. if (!subMesh.effect || !subMesh.effect.isReady()) {
  33938. return false;
  33939. }
  33940. defines._renderId = scene.getRenderId();
  33941. this._wasPreviouslyReady = true;
  33942. return true;
  33943. };
  33944. StandardMaterial.prototype.buildUniformLayout = function () {
  33945. // Order is important !
  33946. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  33947. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  33948. this._uniformBuffer.addUniform("opacityParts", 4);
  33949. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  33950. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  33951. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  33952. this._uniformBuffer.addUniform("refractionRightColor", 4);
  33953. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  33954. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  33955. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  33956. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  33957. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  33958. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  33959. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  33960. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  33961. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  33962. this._uniformBuffer.addUniform("vBumpInfos", 3);
  33963. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  33964. this._uniformBuffer.addUniform("ambientMatrix", 16);
  33965. this._uniformBuffer.addUniform("opacityMatrix", 16);
  33966. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  33967. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  33968. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  33969. this._uniformBuffer.addUniform("specularMatrix", 16);
  33970. this._uniformBuffer.addUniform("bumpMatrix", 16);
  33971. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  33972. this._uniformBuffer.addUniform("refractionMatrix", 16);
  33973. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  33974. this._uniformBuffer.addUniform("vSpecularColor", 4);
  33975. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  33976. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  33977. this._uniformBuffer.addUniform("pointSize", 1);
  33978. this._uniformBuffer.create();
  33979. };
  33980. StandardMaterial.prototype.unbind = function () {
  33981. if (this._activeEffect) {
  33982. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  33983. this._activeEffect.setTexture("reflection2DSampler", null);
  33984. }
  33985. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  33986. this._activeEffect.setTexture("refraction2DSampler", null);
  33987. }
  33988. }
  33989. _super.prototype.unbind.call(this);
  33990. };
  33991. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  33992. var scene = this.getScene();
  33993. var defines = subMesh._materialDefines;
  33994. if (!defines) {
  33995. return;
  33996. }
  33997. var effect = subMesh.effect;
  33998. if (!effect) {
  33999. return;
  34000. }
  34001. this._activeEffect = effect;
  34002. // Matrices
  34003. this.bindOnlyWorldMatrix(world);
  34004. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34005. // Bones
  34006. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34007. if (mustRebind) {
  34008. this._uniformBuffer.bindToEffect(effect, "Material");
  34009. this.bindViewProjection(effect);
  34010. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34011. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34012. // Fresnel
  34013. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34014. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34015. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34016. }
  34017. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34018. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34019. }
  34020. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34021. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34022. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34023. }
  34024. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34025. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34026. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34027. }
  34028. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34029. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34030. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34031. }
  34032. }
  34033. // Textures
  34034. if (scene.texturesEnabled) {
  34035. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34036. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34037. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34038. }
  34039. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34040. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34041. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34042. }
  34043. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34044. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34045. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34046. }
  34047. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34048. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34049. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34050. }
  34051. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34052. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34053. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34054. }
  34055. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34056. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34057. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34058. }
  34059. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34060. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34061. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34062. }
  34063. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34064. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34065. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34066. if (scene._mirroredCameraPosition) {
  34067. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34068. }
  34069. else {
  34070. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34071. }
  34072. }
  34073. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34074. var depth = 1.0;
  34075. if (!this._refractionTexture.isCube) {
  34076. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34077. if (this._refractionTexture.depth) {
  34078. depth = this._refractionTexture.depth;
  34079. }
  34080. }
  34081. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34082. }
  34083. }
  34084. // Point size
  34085. if (this.pointsCloud) {
  34086. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34087. }
  34088. if (defines.SPECULARTERM) {
  34089. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34090. }
  34091. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34092. // Diffuse
  34093. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34094. }
  34095. // Textures
  34096. if (scene.texturesEnabled) {
  34097. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34098. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34099. }
  34100. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34101. effect.setTexture("ambientSampler", this._ambientTexture);
  34102. }
  34103. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34104. effect.setTexture("opacitySampler", this._opacityTexture);
  34105. }
  34106. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34107. if (this._reflectionTexture.isCube) {
  34108. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34109. }
  34110. else {
  34111. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34112. }
  34113. }
  34114. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34115. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34116. }
  34117. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34118. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34119. }
  34120. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34121. effect.setTexture("specularSampler", this._specularTexture);
  34122. }
  34123. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34124. effect.setTexture("bumpSampler", this._bumpTexture);
  34125. }
  34126. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34127. var depth = 1.0;
  34128. if (this._refractionTexture.isCube) {
  34129. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34130. }
  34131. else {
  34132. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34133. }
  34134. }
  34135. }
  34136. // Clip plane
  34137. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34138. // Colors
  34139. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34140. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34141. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34142. }
  34143. if (mustRebind || !this.isFrozen) {
  34144. // Lights
  34145. if (scene.lightsEnabled && !this._disableLighting) {
  34146. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34147. }
  34148. // View
  34149. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34150. this.bindView(effect);
  34151. }
  34152. // Fog
  34153. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34154. // Morph targets
  34155. if (defines.NUM_MORPH_INFLUENCERS) {
  34156. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34157. }
  34158. // Log. depth
  34159. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34160. // image processing
  34161. this._imageProcessingConfiguration.bind(this._activeEffect);
  34162. }
  34163. this._uniformBuffer.update();
  34164. this._afterBind(mesh, this._activeEffect);
  34165. };
  34166. StandardMaterial.prototype.getAnimatables = function () {
  34167. var results = [];
  34168. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34169. results.push(this._diffuseTexture);
  34170. }
  34171. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34172. results.push(this._ambientTexture);
  34173. }
  34174. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34175. results.push(this._opacityTexture);
  34176. }
  34177. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34178. results.push(this._reflectionTexture);
  34179. }
  34180. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34181. results.push(this._emissiveTexture);
  34182. }
  34183. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34184. results.push(this._specularTexture);
  34185. }
  34186. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34187. results.push(this._bumpTexture);
  34188. }
  34189. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34190. results.push(this._lightmapTexture);
  34191. }
  34192. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34193. results.push(this._refractionTexture);
  34194. }
  34195. return results;
  34196. };
  34197. StandardMaterial.prototype.getActiveTextures = function () {
  34198. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34199. if (this._diffuseTexture) {
  34200. activeTextures.push(this._diffuseTexture);
  34201. }
  34202. if (this._ambientTexture) {
  34203. activeTextures.push(this._ambientTexture);
  34204. }
  34205. if (this._opacityTexture) {
  34206. activeTextures.push(this._opacityTexture);
  34207. }
  34208. if (this._reflectionTexture) {
  34209. activeTextures.push(this._reflectionTexture);
  34210. }
  34211. if (this._emissiveTexture) {
  34212. activeTextures.push(this._emissiveTexture);
  34213. }
  34214. if (this._specularTexture) {
  34215. activeTextures.push(this._specularTexture);
  34216. }
  34217. if (this._bumpTexture) {
  34218. activeTextures.push(this._bumpTexture);
  34219. }
  34220. if (this._lightmapTexture) {
  34221. activeTextures.push(this._lightmapTexture);
  34222. }
  34223. if (this._refractionTexture) {
  34224. activeTextures.push(this._refractionTexture);
  34225. }
  34226. return activeTextures;
  34227. };
  34228. StandardMaterial.prototype.hasTexture = function (texture) {
  34229. if (_super.prototype.hasTexture.call(this, texture)) {
  34230. return true;
  34231. }
  34232. if (this._diffuseTexture === texture) {
  34233. return true;
  34234. }
  34235. if (this._ambientTexture === texture) {
  34236. return true;
  34237. }
  34238. if (this._opacityTexture === texture) {
  34239. return true;
  34240. }
  34241. if (this._reflectionTexture === texture) {
  34242. return true;
  34243. }
  34244. if (this._emissiveTexture === texture) {
  34245. return true;
  34246. }
  34247. if (this._specularTexture === texture) {
  34248. return true;
  34249. }
  34250. if (this._bumpTexture === texture) {
  34251. return true;
  34252. }
  34253. if (this._lightmapTexture === texture) {
  34254. return true;
  34255. }
  34256. if (this._refractionTexture === texture) {
  34257. return true;
  34258. }
  34259. return false;
  34260. };
  34261. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34262. if (forceDisposeTextures) {
  34263. if (this._diffuseTexture) {
  34264. this._diffuseTexture.dispose();
  34265. }
  34266. if (this._ambientTexture) {
  34267. this._ambientTexture.dispose();
  34268. }
  34269. if (this._opacityTexture) {
  34270. this._opacityTexture.dispose();
  34271. }
  34272. if (this._reflectionTexture) {
  34273. this._reflectionTexture.dispose();
  34274. }
  34275. if (this._emissiveTexture) {
  34276. this._emissiveTexture.dispose();
  34277. }
  34278. if (this._specularTexture) {
  34279. this._specularTexture.dispose();
  34280. }
  34281. if (this._bumpTexture) {
  34282. this._bumpTexture.dispose();
  34283. }
  34284. if (this._lightmapTexture) {
  34285. this._lightmapTexture.dispose();
  34286. }
  34287. if (this._refractionTexture) {
  34288. this._refractionTexture.dispose();
  34289. }
  34290. }
  34291. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34292. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34293. }
  34294. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34295. };
  34296. StandardMaterial.prototype.clone = function (name) {
  34297. var _this = this;
  34298. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34299. result.name = name;
  34300. result.id = name;
  34301. return result;
  34302. };
  34303. StandardMaterial.prototype.serialize = function () {
  34304. return BABYLON.SerializationHelper.Serialize(this);
  34305. };
  34306. // Statics
  34307. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34308. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34309. };
  34310. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34311. get: function () {
  34312. return StandardMaterial._DiffuseTextureEnabled;
  34313. },
  34314. set: function (value) {
  34315. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34316. return;
  34317. }
  34318. StandardMaterial._DiffuseTextureEnabled = value;
  34319. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34320. },
  34321. enumerable: true,
  34322. configurable: true
  34323. });
  34324. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34325. get: function () {
  34326. return StandardMaterial._AmbientTextureEnabled;
  34327. },
  34328. set: function (value) {
  34329. if (StandardMaterial._AmbientTextureEnabled === value) {
  34330. return;
  34331. }
  34332. StandardMaterial._AmbientTextureEnabled = value;
  34333. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34334. },
  34335. enumerable: true,
  34336. configurable: true
  34337. });
  34338. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34339. get: function () {
  34340. return StandardMaterial._OpacityTextureEnabled;
  34341. },
  34342. set: function (value) {
  34343. if (StandardMaterial._OpacityTextureEnabled === value) {
  34344. return;
  34345. }
  34346. StandardMaterial._OpacityTextureEnabled = value;
  34347. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34348. },
  34349. enumerable: true,
  34350. configurable: true
  34351. });
  34352. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34353. get: function () {
  34354. return StandardMaterial._ReflectionTextureEnabled;
  34355. },
  34356. set: function (value) {
  34357. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34358. return;
  34359. }
  34360. StandardMaterial._ReflectionTextureEnabled = value;
  34361. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34362. },
  34363. enumerable: true,
  34364. configurable: true
  34365. });
  34366. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34367. get: function () {
  34368. return StandardMaterial._EmissiveTextureEnabled;
  34369. },
  34370. set: function (value) {
  34371. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34372. return;
  34373. }
  34374. StandardMaterial._EmissiveTextureEnabled = value;
  34375. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34376. },
  34377. enumerable: true,
  34378. configurable: true
  34379. });
  34380. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34381. get: function () {
  34382. return StandardMaterial._SpecularTextureEnabled;
  34383. },
  34384. set: function (value) {
  34385. if (StandardMaterial._SpecularTextureEnabled === value) {
  34386. return;
  34387. }
  34388. StandardMaterial._SpecularTextureEnabled = value;
  34389. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34390. },
  34391. enumerable: true,
  34392. configurable: true
  34393. });
  34394. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34395. get: function () {
  34396. return StandardMaterial._BumpTextureEnabled;
  34397. },
  34398. set: function (value) {
  34399. if (StandardMaterial._BumpTextureEnabled === value) {
  34400. return;
  34401. }
  34402. StandardMaterial._BumpTextureEnabled = value;
  34403. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34404. },
  34405. enumerable: true,
  34406. configurable: true
  34407. });
  34408. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34409. get: function () {
  34410. return StandardMaterial._LightmapTextureEnabled;
  34411. },
  34412. set: function (value) {
  34413. if (StandardMaterial._LightmapTextureEnabled === value) {
  34414. return;
  34415. }
  34416. StandardMaterial._LightmapTextureEnabled = value;
  34417. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34418. },
  34419. enumerable: true,
  34420. configurable: true
  34421. });
  34422. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34423. get: function () {
  34424. return StandardMaterial._RefractionTextureEnabled;
  34425. },
  34426. set: function (value) {
  34427. if (StandardMaterial._RefractionTextureEnabled === value) {
  34428. return;
  34429. }
  34430. StandardMaterial._RefractionTextureEnabled = value;
  34431. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34432. },
  34433. enumerable: true,
  34434. configurable: true
  34435. });
  34436. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34437. get: function () {
  34438. return StandardMaterial._ColorGradingTextureEnabled;
  34439. },
  34440. set: function (value) {
  34441. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34442. return;
  34443. }
  34444. StandardMaterial._ColorGradingTextureEnabled = value;
  34445. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34446. },
  34447. enumerable: true,
  34448. configurable: true
  34449. });
  34450. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34451. get: function () {
  34452. return StandardMaterial._FresnelEnabled;
  34453. },
  34454. set: function (value) {
  34455. if (StandardMaterial._FresnelEnabled === value) {
  34456. return;
  34457. }
  34458. StandardMaterial._FresnelEnabled = value;
  34459. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34460. },
  34461. enumerable: true,
  34462. configurable: true
  34463. });
  34464. // Flags used to enable or disable a type of texture for all Standard Materials
  34465. StandardMaterial._DiffuseTextureEnabled = true;
  34466. StandardMaterial._AmbientTextureEnabled = true;
  34467. StandardMaterial._OpacityTextureEnabled = true;
  34468. StandardMaterial._ReflectionTextureEnabled = true;
  34469. StandardMaterial._EmissiveTextureEnabled = true;
  34470. StandardMaterial._SpecularTextureEnabled = true;
  34471. StandardMaterial._BumpTextureEnabled = true;
  34472. StandardMaterial._LightmapTextureEnabled = true;
  34473. StandardMaterial._RefractionTextureEnabled = true;
  34474. StandardMaterial._ColorGradingTextureEnabled = true;
  34475. StandardMaterial._FresnelEnabled = true;
  34476. __decorate([
  34477. BABYLON.serializeAsTexture("diffuseTexture")
  34478. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34479. __decorate([
  34480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34481. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34482. __decorate([
  34483. BABYLON.serializeAsTexture("ambientTexture")
  34484. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  34485. __decorate([
  34486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34487. ], StandardMaterial.prototype, "ambientTexture", void 0);
  34488. __decorate([
  34489. BABYLON.serializeAsTexture("opacityTexture")
  34490. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  34491. __decorate([
  34492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34493. ], StandardMaterial.prototype, "opacityTexture", void 0);
  34494. __decorate([
  34495. BABYLON.serializeAsTexture("reflectionTexture")
  34496. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  34497. __decorate([
  34498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34499. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  34500. __decorate([
  34501. BABYLON.serializeAsTexture("emissiveTexture")
  34502. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  34503. __decorate([
  34504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34505. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  34506. __decorate([
  34507. BABYLON.serializeAsTexture("specularTexture")
  34508. ], StandardMaterial.prototype, "_specularTexture", void 0);
  34509. __decorate([
  34510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34511. ], StandardMaterial.prototype, "specularTexture", void 0);
  34512. __decorate([
  34513. BABYLON.serializeAsTexture("bumpTexture")
  34514. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  34515. __decorate([
  34516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34517. ], StandardMaterial.prototype, "bumpTexture", void 0);
  34518. __decorate([
  34519. BABYLON.serializeAsTexture("lightmapTexture")
  34520. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  34521. __decorate([
  34522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34523. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  34524. __decorate([
  34525. BABYLON.serializeAsTexture("refractionTexture")
  34526. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  34527. __decorate([
  34528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34529. ], StandardMaterial.prototype, "refractionTexture", void 0);
  34530. __decorate([
  34531. BABYLON.serializeAsColor3("ambient")
  34532. ], StandardMaterial.prototype, "ambientColor", void 0);
  34533. __decorate([
  34534. BABYLON.serializeAsColor3("diffuse")
  34535. ], StandardMaterial.prototype, "diffuseColor", void 0);
  34536. __decorate([
  34537. BABYLON.serializeAsColor3("specular")
  34538. ], StandardMaterial.prototype, "specularColor", void 0);
  34539. __decorate([
  34540. BABYLON.serializeAsColor3("emissive")
  34541. ], StandardMaterial.prototype, "emissiveColor", void 0);
  34542. __decorate([
  34543. BABYLON.serialize()
  34544. ], StandardMaterial.prototype, "specularPower", void 0);
  34545. __decorate([
  34546. BABYLON.serialize("useAlphaFromDiffuseTexture")
  34547. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  34548. __decorate([
  34549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34550. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  34551. __decorate([
  34552. BABYLON.serialize("useEmissiveAsIllumination")
  34553. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  34554. __decorate([
  34555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34556. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  34557. __decorate([
  34558. BABYLON.serialize("linkEmissiveWithDiffuse")
  34559. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  34560. __decorate([
  34561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34562. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  34563. __decorate([
  34564. BABYLON.serialize("useSpecularOverAlpha")
  34565. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  34566. __decorate([
  34567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34568. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  34569. __decorate([
  34570. BABYLON.serialize("useReflectionOverAlpha")
  34571. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  34572. __decorate([
  34573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34574. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  34575. __decorate([
  34576. BABYLON.serialize("disableLighting")
  34577. ], StandardMaterial.prototype, "_disableLighting", void 0);
  34578. __decorate([
  34579. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34580. ], StandardMaterial.prototype, "disableLighting", void 0);
  34581. __decorate([
  34582. BABYLON.serialize("useParallax")
  34583. ], StandardMaterial.prototype, "_useParallax", void 0);
  34584. __decorate([
  34585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34586. ], StandardMaterial.prototype, "useParallax", void 0);
  34587. __decorate([
  34588. BABYLON.serialize("useParallaxOcclusion")
  34589. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  34590. __decorate([
  34591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34592. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  34593. __decorate([
  34594. BABYLON.serialize()
  34595. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  34596. __decorate([
  34597. BABYLON.serialize("roughness")
  34598. ], StandardMaterial.prototype, "_roughness", void 0);
  34599. __decorate([
  34600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34601. ], StandardMaterial.prototype, "roughness", void 0);
  34602. __decorate([
  34603. BABYLON.serialize()
  34604. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  34605. __decorate([
  34606. BABYLON.serialize()
  34607. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  34608. __decorate([
  34609. BABYLON.serialize("useLightmapAsShadowmap")
  34610. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  34611. __decorate([
  34612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34613. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34614. __decorate([
  34615. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  34616. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  34617. __decorate([
  34618. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34619. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  34620. __decorate([
  34621. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  34622. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  34623. __decorate([
  34624. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34625. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  34626. __decorate([
  34627. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  34628. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  34629. __decorate([
  34630. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34631. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  34632. __decorate([
  34633. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  34634. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  34635. __decorate([
  34636. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34637. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  34638. __decorate([
  34639. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  34640. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  34641. __decorate([
  34642. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34643. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  34644. __decorate([
  34645. BABYLON.serialize("useReflectionFresnelFromSpecular")
  34646. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  34647. __decorate([
  34648. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34649. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  34650. __decorate([
  34651. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  34652. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  34653. __decorate([
  34654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34655. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  34656. __decorate([
  34657. BABYLON.serialize("maxSimultaneousLights")
  34658. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  34659. __decorate([
  34660. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34661. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  34662. __decorate([
  34663. BABYLON.serialize("invertNormalMapX")
  34664. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  34665. __decorate([
  34666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34667. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  34668. __decorate([
  34669. BABYLON.serialize("invertNormalMapY")
  34670. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  34671. __decorate([
  34672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34673. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  34674. __decorate([
  34675. BABYLON.serialize("twoSidedLighting")
  34676. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  34677. __decorate([
  34678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34679. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  34680. __decorate([
  34681. BABYLON.serialize()
  34682. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  34683. return StandardMaterial;
  34684. }(BABYLON.PushMaterial));
  34685. BABYLON.StandardMaterial = StandardMaterial;
  34686. })(BABYLON || (BABYLON = {}));
  34687. //# sourceMappingURL=babylon.standardMaterial.js.map
  34688. var BABYLON;
  34689. (function (BABYLON) {
  34690. var PBRMaterialDefines = /** @class */ (function (_super) {
  34691. __extends(PBRMaterialDefines, _super);
  34692. function PBRMaterialDefines() {
  34693. var _this = _super.call(this) || this;
  34694. _this.PBR = true;
  34695. _this.MAINUV1 = false;
  34696. _this.MAINUV2 = false;
  34697. _this.UV1 = false;
  34698. _this.UV2 = false;
  34699. _this.ALBEDO = false;
  34700. _this.ALBEDODIRECTUV = 0;
  34701. _this.VERTEXCOLOR = false;
  34702. _this.AMBIENT = false;
  34703. _this.AMBIENTDIRECTUV = 0;
  34704. _this.AMBIENTINGRAYSCALE = false;
  34705. _this.OPACITY = false;
  34706. _this.VERTEXALPHA = false;
  34707. _this.OPACITYDIRECTUV = 0;
  34708. _this.OPACITYRGB = false;
  34709. _this.ALPHATEST = false;
  34710. _this.DEPTHPREPASS = false;
  34711. _this.ALPHABLEND = false;
  34712. _this.ALPHAFROMALBEDO = false;
  34713. _this.ALPHATESTVALUE = 0.5;
  34714. _this.SPECULAROVERALPHA = false;
  34715. _this.RADIANCEOVERALPHA = false;
  34716. _this.ALPHAFRESNEL = false;
  34717. _this.PREMULTIPLYALPHA = false;
  34718. _this.EMISSIVE = false;
  34719. _this.EMISSIVEDIRECTUV = 0;
  34720. _this.REFLECTIVITY = false;
  34721. _this.REFLECTIVITYDIRECTUV = 0;
  34722. _this.SPECULARTERM = false;
  34723. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34724. _this.MICROSURFACEAUTOMATIC = false;
  34725. _this.LODBASEDMICROSFURACE = false;
  34726. _this.MICROSURFACEMAP = false;
  34727. _this.MICROSURFACEMAPDIRECTUV = 0;
  34728. _this.METALLICWORKFLOW = false;
  34729. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34730. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34731. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34732. _this.AOSTOREINMETALMAPRED = false;
  34733. _this.ENVIRONMENTBRDF = false;
  34734. _this.NORMAL = false;
  34735. _this.TANGENT = false;
  34736. _this.BUMP = false;
  34737. _this.BUMPDIRECTUV = 0;
  34738. _this.PARALLAX = false;
  34739. _this.PARALLAXOCCLUSION = false;
  34740. _this.NORMALXYSCALE = true;
  34741. _this.LIGHTMAP = false;
  34742. _this.LIGHTMAPDIRECTUV = 0;
  34743. _this.USELIGHTMAPASSHADOWMAP = false;
  34744. _this.REFLECTION = false;
  34745. _this.REFLECTIONMAP_3D = false;
  34746. _this.REFLECTIONMAP_SPHERICAL = false;
  34747. _this.REFLECTIONMAP_PLANAR = false;
  34748. _this.REFLECTIONMAP_CUBIC = false;
  34749. _this.REFLECTIONMAP_PROJECTION = false;
  34750. _this.REFLECTIONMAP_SKYBOX = false;
  34751. _this.REFLECTIONMAP_EXPLICIT = false;
  34752. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34753. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34754. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34755. _this.INVERTCUBICMAP = false;
  34756. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34757. _this.USESPHERICALINVERTEX = false;
  34758. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34759. _this.LODINREFLECTIONALPHA = false;
  34760. _this.GAMMAREFLECTION = false;
  34761. _this.REFRACTION = false;
  34762. _this.REFRACTIONMAP_3D = false;
  34763. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34764. _this.LODINREFRACTIONALPHA = false;
  34765. _this.GAMMAREFRACTION = false;
  34766. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34767. _this.INSTANCES = false;
  34768. _this.NUM_BONE_INFLUENCERS = 0;
  34769. _this.BonesPerMesh = 0;
  34770. _this.NONUNIFORMSCALING = false;
  34771. _this.MORPHTARGETS = false;
  34772. _this.MORPHTARGETS_NORMAL = false;
  34773. _this.MORPHTARGETS_TANGENT = false;
  34774. _this.NUM_MORPH_INFLUENCERS = 0;
  34775. _this.IMAGEPROCESSING = false;
  34776. _this.VIGNETTE = false;
  34777. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34778. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34779. _this.TONEMAPPING = false;
  34780. _this.CONTRAST = false;
  34781. _this.COLORCURVES = false;
  34782. _this.COLORGRADING = false;
  34783. _this.COLORGRADING3D = false;
  34784. _this.SAMPLER3DGREENDEPTH = false;
  34785. _this.SAMPLER3DBGRMAP = false;
  34786. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34787. _this.EXPOSURE = false;
  34788. _this.USEPHYSICALLIGHTFALLOFF = false;
  34789. _this.TWOSIDEDLIGHTING = false;
  34790. _this.SHADOWFLOAT = false;
  34791. _this.CLIPPLANE = false;
  34792. _this.POINTSIZE = false;
  34793. _this.FOG = false;
  34794. _this.LOGARITHMICDEPTH = false;
  34795. _this.FORCENORMALFORWARD = false;
  34796. _this.rebuild();
  34797. return _this;
  34798. }
  34799. PBRMaterialDefines.prototype.reset = function () {
  34800. _super.prototype.reset.call(this);
  34801. this.ALPHATESTVALUE = 0.5;
  34802. this.PBR = true;
  34803. };
  34804. return PBRMaterialDefines;
  34805. }(BABYLON.MaterialDefines));
  34806. /**
  34807. * The Physically based material base class of BJS.
  34808. *
  34809. * This offers the main features of a standard PBR material.
  34810. * For more information, please refer to the documentation :
  34811. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34812. */
  34813. var PBRBaseMaterial = /** @class */ (function (_super) {
  34814. __extends(PBRBaseMaterial, _super);
  34815. /**
  34816. * Instantiates a new PBRMaterial instance.
  34817. *
  34818. * @param name The material name
  34819. * @param scene The scene the material will be use in.
  34820. */
  34821. function PBRBaseMaterial(name, scene) {
  34822. var _this = _super.call(this, name, scene) || this;
  34823. /**
  34824. * Intensity of the direct lights e.g. the four lights available in your scene.
  34825. * This impacts both the direct diffuse and specular highlights.
  34826. */
  34827. _this._directIntensity = 1.0;
  34828. /**
  34829. * Intensity of the emissive part of the material.
  34830. * This helps controlling the emissive effect without modifying the emissive color.
  34831. */
  34832. _this._emissiveIntensity = 1.0;
  34833. /**
  34834. * Intensity of the environment e.g. how much the environment will light the object
  34835. * either through harmonics for rough material or through the refelction for shiny ones.
  34836. */
  34837. _this._environmentIntensity = 1.0;
  34838. /**
  34839. * This is a special control allowing the reduction of the specular highlights coming from the
  34840. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34841. */
  34842. _this._specularIntensity = 1.0;
  34843. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34844. /**
  34845. * Debug Control allowing disabling the bump map on this material.
  34846. */
  34847. _this._disableBumpMap = false;
  34848. /**
  34849. * AKA Occlusion Texture Intensity in other nomenclature.
  34850. */
  34851. _this._ambientTextureStrength = 1.0;
  34852. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34853. /**
  34854. * AKA Diffuse Color in other nomenclature.
  34855. */
  34856. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34857. /**
  34858. * AKA Specular Color in other nomenclature.
  34859. */
  34860. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34861. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  34862. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34863. /**
  34864. * AKA Glossiness in other nomenclature.
  34865. */
  34866. _this._microSurface = 0.9;
  34867. /**
  34868. * source material index of refraction (IOR)' / 'destination material IOR.
  34869. */
  34870. _this._indexOfRefraction = 0.66;
  34871. /**
  34872. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34873. */
  34874. _this._invertRefractionY = false;
  34875. /**
  34876. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34877. * Materials half opaque for instance using refraction could benefit from this control.
  34878. */
  34879. _this._linkRefractionWithTransparency = false;
  34880. _this._useLightmapAsShadowmap = false;
  34881. /**
  34882. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34883. */
  34884. _this._useAlphaFromAlbedoTexture = false;
  34885. /**
  34886. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34887. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34888. */
  34889. _this._useSpecularOverAlpha = true;
  34890. /**
  34891. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34892. */
  34893. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34894. /**
  34895. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34896. */
  34897. _this._useRoughnessFromMetallicTextureAlpha = true;
  34898. /**
  34899. * Specifies if the metallic texture contains the roughness information in its green channel.
  34900. */
  34901. _this._useRoughnessFromMetallicTextureGreen = false;
  34902. /**
  34903. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34904. */
  34905. _this._useMetallnessFromMetallicTextureBlue = false;
  34906. /**
  34907. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34908. */
  34909. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34910. /**
  34911. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34912. */
  34913. _this._useAmbientInGrayScale = false;
  34914. /**
  34915. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34916. * The material will try to infer what glossiness each pixel should be.
  34917. */
  34918. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34919. /**
  34920. * BJS is using an harcoded light falloff based on a manually sets up range.
  34921. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34922. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34923. */
  34924. _this._usePhysicalLightFalloff = true;
  34925. /**
  34926. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34927. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34928. */
  34929. _this._useRadianceOverAlpha = true;
  34930. /**
  34931. * Allows using the bump map in parallax mode.
  34932. */
  34933. _this._useParallax = false;
  34934. /**
  34935. * Allows using the bump map in parallax occlusion mode.
  34936. */
  34937. _this._useParallaxOcclusion = false;
  34938. /**
  34939. * Controls the scale bias of the parallax mode.
  34940. */
  34941. _this._parallaxScaleBias = 0.05;
  34942. /**
  34943. * If sets to true, disables all the lights affecting the material.
  34944. */
  34945. _this._disableLighting = false;
  34946. /**
  34947. * Number of Simultaneous lights allowed on the material.
  34948. */
  34949. _this._maxSimultaneousLights = 4;
  34950. /**
  34951. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  34952. */
  34953. _this._invertNormalMapX = false;
  34954. /**
  34955. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  34956. */
  34957. _this._invertNormalMapY = false;
  34958. /**
  34959. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34960. */
  34961. _this._twoSidedLighting = false;
  34962. /**
  34963. * Defines the alpha limits in alpha test mode.
  34964. */
  34965. _this._alphaCutOff = 0.4;
  34966. /**
  34967. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34968. */
  34969. _this._forceAlphaTest = false;
  34970. /**
  34971. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34972. * And/Or occlude the blended part.
  34973. */
  34974. _this._useAlphaFresnel = false;
  34975. /**
  34976. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  34977. * from cos thetav and roughness:
  34978. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  34979. */
  34980. _this._environmentBRDFTexture = null;
  34981. /**
  34982. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  34983. */
  34984. _this._forceIrradianceInFragment = false;
  34985. /**
  34986. * Force normal to face away from face.
  34987. * (Temporary internal fix to remove before 3.1)
  34988. */
  34989. _this._forceNormalForward = false;
  34990. _this._renderTargets = new BABYLON.SmartArray(16);
  34991. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34992. // Setup the default processing configuration to the scene.
  34993. _this._attachImageProcessingConfiguration(null);
  34994. _this.getRenderTargetTextures = function () {
  34995. _this._renderTargets.reset();
  34996. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34997. _this._renderTargets.push(_this._reflectionTexture);
  34998. }
  34999. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35000. _this._renderTargets.push(_this._refractionTexture);
  35001. }
  35002. return _this._renderTargets;
  35003. };
  35004. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35005. return _this;
  35006. }
  35007. /**
  35008. * Attaches a new image processing configuration to the PBR Material.
  35009. * @param configuration
  35010. */
  35011. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35012. var _this = this;
  35013. if (configuration === this._imageProcessingConfiguration) {
  35014. return;
  35015. }
  35016. // Detaches observer.
  35017. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35018. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35019. }
  35020. // Pick the scene configuration if needed.
  35021. if (!configuration) {
  35022. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35023. }
  35024. else {
  35025. this._imageProcessingConfiguration = configuration;
  35026. }
  35027. // Attaches observer.
  35028. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35029. _this._markAllSubMeshesAsImageProcessingDirty();
  35030. });
  35031. };
  35032. PBRBaseMaterial.prototype.getClassName = function () {
  35033. return "PBRBaseMaterial";
  35034. };
  35035. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35036. get: function () {
  35037. return this._useLogarithmicDepth;
  35038. },
  35039. set: function (value) {
  35040. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35041. },
  35042. enumerable: true,
  35043. configurable: true
  35044. });
  35045. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35046. if (this._linkRefractionWithTransparency) {
  35047. return false;
  35048. }
  35049. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35050. };
  35051. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35052. if (this._forceAlphaTest) {
  35053. return true;
  35054. }
  35055. if (this._linkRefractionWithTransparency) {
  35056. return false;
  35057. }
  35058. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  35059. };
  35060. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35061. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  35062. };
  35063. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35064. return this._albedoTexture;
  35065. };
  35066. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35067. var _this = this;
  35068. if (subMesh.effect && this.isFrozen) {
  35069. if (this._wasPreviouslyReady) {
  35070. return true;
  35071. }
  35072. }
  35073. if (!subMesh._materialDefines) {
  35074. subMesh._materialDefines = new PBRMaterialDefines();
  35075. }
  35076. var scene = this.getScene();
  35077. var defines = subMesh._materialDefines;
  35078. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35079. if (defines._renderId === scene.getRenderId()) {
  35080. return true;
  35081. }
  35082. }
  35083. var engine = scene.getEngine();
  35084. // Lights
  35085. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35086. defines._needNormals = true;
  35087. // Textures
  35088. if (defines._areTexturesDirty) {
  35089. defines._needUVs = false;
  35090. if (scene.texturesEnabled) {
  35091. if (scene.getEngine().getCaps().textureLOD) {
  35092. defines.LODBASEDMICROSFURACE = true;
  35093. }
  35094. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35095. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35096. return false;
  35097. }
  35098. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35099. }
  35100. else {
  35101. defines.ALBEDO = false;
  35102. }
  35103. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35104. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35105. return false;
  35106. }
  35107. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35108. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35109. }
  35110. else {
  35111. defines.AMBIENT = false;
  35112. }
  35113. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35114. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35115. return false;
  35116. }
  35117. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35118. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35119. }
  35120. else {
  35121. defines.OPACITY = false;
  35122. }
  35123. var reflectionTexture = this._getReflectionTexture();
  35124. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35125. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35126. return false;
  35127. }
  35128. defines.REFLECTION = true;
  35129. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35130. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35131. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35132. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35133. defines.INVERTCUBICMAP = true;
  35134. }
  35135. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35136. switch (reflectionTexture.coordinatesMode) {
  35137. case BABYLON.Texture.CUBIC_MODE:
  35138. case BABYLON.Texture.INVCUBIC_MODE:
  35139. defines.REFLECTIONMAP_CUBIC = true;
  35140. break;
  35141. case BABYLON.Texture.EXPLICIT_MODE:
  35142. defines.REFLECTIONMAP_EXPLICIT = true;
  35143. break;
  35144. case BABYLON.Texture.PLANAR_MODE:
  35145. defines.REFLECTIONMAP_PLANAR = true;
  35146. break;
  35147. case BABYLON.Texture.PROJECTION_MODE:
  35148. defines.REFLECTIONMAP_PROJECTION = true;
  35149. break;
  35150. case BABYLON.Texture.SKYBOX_MODE:
  35151. defines.REFLECTIONMAP_SKYBOX = true;
  35152. break;
  35153. case BABYLON.Texture.SPHERICAL_MODE:
  35154. defines.REFLECTIONMAP_SPHERICAL = true;
  35155. break;
  35156. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35157. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35158. break;
  35159. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35160. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35161. break;
  35162. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35163. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35164. break;
  35165. }
  35166. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35167. if (reflectionTexture.sphericalPolynomial) {
  35168. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35169. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35170. defines.USESPHERICALINVERTEX = false;
  35171. }
  35172. else {
  35173. defines.USESPHERICALINVERTEX = true;
  35174. }
  35175. }
  35176. }
  35177. }
  35178. else {
  35179. defines.REFLECTION = false;
  35180. defines.REFLECTIONMAP_3D = false;
  35181. defines.REFLECTIONMAP_SPHERICAL = false;
  35182. defines.REFLECTIONMAP_PLANAR = false;
  35183. defines.REFLECTIONMAP_CUBIC = false;
  35184. defines.REFLECTIONMAP_PROJECTION = false;
  35185. defines.REFLECTIONMAP_SKYBOX = false;
  35186. defines.REFLECTIONMAP_EXPLICIT = false;
  35187. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35188. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35189. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35190. defines.INVERTCUBICMAP = false;
  35191. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35192. defines.USESPHERICALINVERTEX = false;
  35193. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35194. defines.LODINREFLECTIONALPHA = false;
  35195. defines.GAMMAREFLECTION = false;
  35196. }
  35197. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35198. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35199. return false;
  35200. }
  35201. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35202. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35203. }
  35204. else {
  35205. defines.LIGHTMAP = false;
  35206. }
  35207. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35208. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35209. return false;
  35210. }
  35211. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35212. }
  35213. else {
  35214. defines.EMISSIVE = false;
  35215. }
  35216. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35217. if (this._metallicTexture) {
  35218. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35219. return false;
  35220. }
  35221. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35222. defines.METALLICWORKFLOW = true;
  35223. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35224. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35225. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35226. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35227. }
  35228. else if (this._reflectivityTexture) {
  35229. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35230. return false;
  35231. }
  35232. defines.METALLICWORKFLOW = false;
  35233. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35234. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35235. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35236. }
  35237. else {
  35238. defines.METALLICWORKFLOW = false;
  35239. defines.REFLECTIVITY = false;
  35240. }
  35241. if (this._microSurfaceTexture) {
  35242. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35243. return false;
  35244. }
  35245. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35246. }
  35247. else {
  35248. defines.MICROSURFACEMAP = false;
  35249. }
  35250. }
  35251. else {
  35252. defines.REFLECTIVITY = false;
  35253. defines.MICROSURFACEMAP = false;
  35254. }
  35255. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35256. // Bump texure can not be none blocking.
  35257. if (!this._bumpTexture.isReady()) {
  35258. return false;
  35259. }
  35260. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35261. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35262. defines.PARALLAX = true;
  35263. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35264. }
  35265. else {
  35266. defines.PARALLAX = false;
  35267. }
  35268. }
  35269. else {
  35270. defines.BUMP = false;
  35271. }
  35272. var refractionTexture = this._getRefractionTexture();
  35273. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35274. if (!refractionTexture.isReadyOrNotBlocking()) {
  35275. return false;
  35276. }
  35277. defines.REFRACTION = true;
  35278. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35279. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35280. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35281. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35282. if (this._linkRefractionWithTransparency) {
  35283. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35284. }
  35285. }
  35286. else {
  35287. defines.REFRACTION = false;
  35288. }
  35289. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35290. // This is blocking.
  35291. if (!this._environmentBRDFTexture.isReady()) {
  35292. return false;
  35293. }
  35294. defines.ENVIRONMENTBRDF = true;
  35295. }
  35296. else {
  35297. defines.ENVIRONMENTBRDF = false;
  35298. }
  35299. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35300. defines.ALPHAFROMALBEDO = true;
  35301. }
  35302. else {
  35303. defines.ALPHAFROMALBEDO = false;
  35304. }
  35305. }
  35306. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35307. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35308. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35309. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35310. defines.METALLICWORKFLOW = true;
  35311. }
  35312. else {
  35313. defines.METALLICWORKFLOW = false;
  35314. }
  35315. if (!this.backFaceCulling && this._twoSidedLighting) {
  35316. defines.TWOSIDEDLIGHTING = true;
  35317. }
  35318. else {
  35319. defines.TWOSIDEDLIGHTING = false;
  35320. }
  35321. defines.ALPHATESTVALUE = this._alphaCutOff;
  35322. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35323. defines.ALPHABLEND = this.needAlphaBlending();
  35324. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35325. }
  35326. if (defines._areImageProcessingDirty) {
  35327. if (!this._imageProcessingConfiguration.isReady()) {
  35328. return false;
  35329. }
  35330. this._imageProcessingConfiguration.prepareDefines(defines);
  35331. }
  35332. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35333. // Misc.
  35334. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35335. // Values that need to be evaluated on every frame
  35336. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35337. // Attribs
  35338. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35339. if (mesh) {
  35340. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35341. mesh.createNormals(true);
  35342. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35343. }
  35344. }
  35345. }
  35346. // Get correct effect
  35347. if (defines.isDirty) {
  35348. defines.markAsProcessed();
  35349. scene.resetCachedMaterial();
  35350. // Fallbacks
  35351. var fallbacks = new BABYLON.EffectFallbacks();
  35352. var fallbackRank = 0;
  35353. if (defines.USESPHERICALINVERTEX) {
  35354. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  35355. }
  35356. if (defines.FOG) {
  35357. fallbacks.addFallback(fallbackRank, "FOG");
  35358. }
  35359. if (defines.POINTSIZE) {
  35360. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  35361. }
  35362. if (defines.LOGARITHMICDEPTH) {
  35363. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  35364. }
  35365. if (defines.PARALLAX) {
  35366. fallbacks.addFallback(fallbackRank, "PARALLAX");
  35367. }
  35368. if (defines.PARALLAXOCCLUSION) {
  35369. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  35370. }
  35371. if (defines.ENVIRONMENTBRDF) {
  35372. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  35373. }
  35374. if (defines.TANGENT) {
  35375. fallbacks.addFallback(fallbackRank++, "TANGENT");
  35376. }
  35377. if (defines.BUMP) {
  35378. fallbacks.addFallback(fallbackRank++, "BUMP");
  35379. }
  35380. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  35381. if (defines.SPECULARTERM) {
  35382. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  35383. }
  35384. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35385. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  35386. }
  35387. if (defines.LIGHTMAP) {
  35388. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  35389. }
  35390. if (defines.NORMAL) {
  35391. fallbacks.addFallback(fallbackRank++, "NORMAL");
  35392. }
  35393. if (defines.AMBIENT) {
  35394. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  35395. }
  35396. if (defines.EMISSIVE) {
  35397. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  35398. }
  35399. if (defines.VERTEXCOLOR) {
  35400. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  35401. }
  35402. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35403. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  35404. }
  35405. if (defines.MORPHTARGETS) {
  35406. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  35407. }
  35408. //Attributes
  35409. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35410. if (defines.NORMAL) {
  35411. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35412. }
  35413. if (defines.TANGENT) {
  35414. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35415. }
  35416. if (defines.UV1) {
  35417. attribs.push(BABYLON.VertexBuffer.UVKind);
  35418. }
  35419. if (defines.UV2) {
  35420. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35421. }
  35422. if (defines.VERTEXCOLOR) {
  35423. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35424. }
  35425. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35426. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35427. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35428. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35429. "vFogInfos", "vFogColor", "pointSize",
  35430. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35431. "mBones",
  35432. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35433. "vLightingIntensity",
  35434. "logarithmicDepthConstant",
  35435. "vSphericalX", "vSphericalY", "vSphericalZ",
  35436. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35437. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35438. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  35439. "vTangentSpaceParams"
  35440. ];
  35441. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35442. "bumpSampler", "lightmapSampler", "opacitySampler",
  35443. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35444. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35445. "microSurfaceSampler", "environmentBrdfSampler"];
  35446. var uniformBuffers = ["Material", "Scene"];
  35447. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35448. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35449. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35450. uniformsNames: uniforms,
  35451. uniformBuffersNames: uniformBuffers,
  35452. samplers: samplers,
  35453. defines: defines,
  35454. maxSimultaneousLights: this._maxSimultaneousLights
  35455. });
  35456. var onCompiled = function (effect) {
  35457. if (_this.onCompiled) {
  35458. _this.onCompiled(effect);
  35459. }
  35460. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35461. };
  35462. var join = defines.toString();
  35463. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35464. attributes: attribs,
  35465. uniformsNames: uniforms,
  35466. uniformBuffersNames: uniformBuffers,
  35467. samplers: samplers,
  35468. defines: join,
  35469. fallbacks: fallbacks,
  35470. onCompiled: onCompiled,
  35471. onError: this.onError,
  35472. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35473. }, engine), defines);
  35474. this.buildUniformLayout();
  35475. }
  35476. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35477. return false;
  35478. }
  35479. defines._renderId = scene.getRenderId();
  35480. this._wasPreviouslyReady = true;
  35481. return true;
  35482. };
  35483. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35484. // Order is important !
  35485. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35486. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35487. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35488. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35489. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35490. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35491. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35492. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35493. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35494. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35495. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35496. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35497. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35498. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35499. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35500. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35501. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35502. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35503. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35504. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35505. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35506. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35507. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35508. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35509. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35510. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35511. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35512. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35513. this._uniformBuffer.addUniform("pointSize", 1);
  35514. this._uniformBuffer.create();
  35515. };
  35516. PBRBaseMaterial.prototype.unbind = function () {
  35517. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35518. this._uniformBuffer.setTexture("reflectionSampler", null);
  35519. }
  35520. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35521. this._uniformBuffer.setTexture("refractionSampler", null);
  35522. }
  35523. _super.prototype.unbind.call(this);
  35524. };
  35525. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35526. this._activeEffect.setMatrix("world", world);
  35527. };
  35528. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35529. var scene = this.getScene();
  35530. var defines = subMesh._materialDefines;
  35531. if (!defines) {
  35532. return;
  35533. }
  35534. var effect = subMesh.effect;
  35535. if (!effect) {
  35536. return;
  35537. }
  35538. this._activeEffect = effect;
  35539. // Matrices
  35540. this.bindOnlyWorldMatrix(world);
  35541. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35542. // Bones
  35543. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35544. var reflectionTexture = null;
  35545. if (mustRebind) {
  35546. this._uniformBuffer.bindToEffect(effect, "Material");
  35547. this.bindViewProjection(effect);
  35548. reflectionTexture = this._getReflectionTexture();
  35549. var refractionTexture = this._getRefractionTexture();
  35550. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35551. // Texture uniforms
  35552. if (scene.texturesEnabled) {
  35553. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35554. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35555. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35556. }
  35557. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35558. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35559. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35560. }
  35561. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35562. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35563. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35564. }
  35565. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35566. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35567. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35568. var polynomials = reflectionTexture.sphericalPolynomial;
  35569. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  35570. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35571. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35572. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35573. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35574. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35575. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35576. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35577. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35578. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35579. }
  35580. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35581. }
  35582. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35583. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35584. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35585. }
  35586. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35587. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35588. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35589. }
  35590. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35591. if (this._metallicTexture) {
  35592. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35593. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35594. }
  35595. else if (this._reflectivityTexture) {
  35596. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35597. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35598. }
  35599. if (this._microSurfaceTexture) {
  35600. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35601. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35602. }
  35603. }
  35604. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35605. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35606. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35607. if (scene._mirroredCameraPosition) {
  35608. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35609. }
  35610. else {
  35611. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35612. }
  35613. }
  35614. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35615. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35616. var depth = 1.0;
  35617. if (!refractionTexture.isCube) {
  35618. if (refractionTexture.depth) {
  35619. depth = refractionTexture.depth;
  35620. }
  35621. }
  35622. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35623. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35624. }
  35625. }
  35626. // Point size
  35627. if (this.pointsCloud) {
  35628. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35629. }
  35630. // Colors
  35631. if (defines.METALLICWORKFLOW) {
  35632. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35633. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35634. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35635. }
  35636. else {
  35637. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35638. }
  35639. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35640. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35641. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35642. // Misc
  35643. this._lightingInfos.x = this._directIntensity;
  35644. this._lightingInfos.y = this._emissiveIntensity;
  35645. this._lightingInfos.z = this._environmentIntensity;
  35646. this._lightingInfos.w = this._specularIntensity;
  35647. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35648. }
  35649. // Textures
  35650. if (scene.texturesEnabled) {
  35651. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35652. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35653. }
  35654. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35655. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35656. }
  35657. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35658. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35659. }
  35660. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35661. if (defines.LODBASEDMICROSFURACE) {
  35662. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35663. }
  35664. else {
  35665. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35666. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35667. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35668. }
  35669. }
  35670. if (defines.ENVIRONMENTBRDF) {
  35671. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35672. }
  35673. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35674. if (defines.LODBASEDMICROSFURACE) {
  35675. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35676. }
  35677. else {
  35678. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35679. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35680. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35681. }
  35682. }
  35683. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35684. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35685. }
  35686. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35687. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35688. }
  35689. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35690. if (this._metallicTexture) {
  35691. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35692. }
  35693. else if (this._reflectivityTexture) {
  35694. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35695. }
  35696. if (this._microSurfaceTexture) {
  35697. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35698. }
  35699. }
  35700. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35701. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35702. }
  35703. }
  35704. // Clip plane
  35705. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35706. // Colors
  35707. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35708. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35709. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  35710. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  35711. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35712. }
  35713. if (mustRebind || !this.isFrozen) {
  35714. // Lights
  35715. if (scene.lightsEnabled && !this._disableLighting) {
  35716. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35717. }
  35718. // View
  35719. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35720. this.bindView(effect);
  35721. }
  35722. // Fog
  35723. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35724. // Morph targets
  35725. if (defines.NUM_MORPH_INFLUENCERS) {
  35726. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35727. }
  35728. // image processing
  35729. this._imageProcessingConfiguration.bind(this._activeEffect);
  35730. // Log. depth
  35731. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35732. }
  35733. this._uniformBuffer.update();
  35734. this._afterBind(mesh);
  35735. };
  35736. PBRBaseMaterial.prototype.getAnimatables = function () {
  35737. var results = [];
  35738. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35739. results.push(this._albedoTexture);
  35740. }
  35741. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35742. results.push(this._ambientTexture);
  35743. }
  35744. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35745. results.push(this._opacityTexture);
  35746. }
  35747. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35748. results.push(this._reflectionTexture);
  35749. }
  35750. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35751. results.push(this._emissiveTexture);
  35752. }
  35753. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35754. results.push(this._metallicTexture);
  35755. }
  35756. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35757. results.push(this._reflectivityTexture);
  35758. }
  35759. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35760. results.push(this._bumpTexture);
  35761. }
  35762. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35763. results.push(this._lightmapTexture);
  35764. }
  35765. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35766. results.push(this._refractionTexture);
  35767. }
  35768. return results;
  35769. };
  35770. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  35771. if (this._reflectionTexture) {
  35772. return this._reflectionTexture;
  35773. }
  35774. return this.getScene().environmentTexture;
  35775. };
  35776. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  35777. if (this._refractionTexture) {
  35778. return this._refractionTexture;
  35779. }
  35780. if (this._linkRefractionWithTransparency) {
  35781. return this.getScene().environmentTexture;
  35782. }
  35783. return null;
  35784. };
  35785. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35786. if (forceDisposeTextures) {
  35787. if (this._albedoTexture) {
  35788. this._albedoTexture.dispose();
  35789. }
  35790. if (this._ambientTexture) {
  35791. this._ambientTexture.dispose();
  35792. }
  35793. if (this._opacityTexture) {
  35794. this._opacityTexture.dispose();
  35795. }
  35796. if (this._reflectionTexture) {
  35797. this._reflectionTexture.dispose();
  35798. }
  35799. if (this._environmentBRDFTexture) {
  35800. this._environmentBRDFTexture.dispose();
  35801. }
  35802. if (this._emissiveTexture) {
  35803. this._emissiveTexture.dispose();
  35804. }
  35805. if (this._metallicTexture) {
  35806. this._metallicTexture.dispose();
  35807. }
  35808. if (this._reflectivityTexture) {
  35809. this._reflectivityTexture.dispose();
  35810. }
  35811. if (this._bumpTexture) {
  35812. this._bumpTexture.dispose();
  35813. }
  35814. if (this._lightmapTexture) {
  35815. this._lightmapTexture.dispose();
  35816. }
  35817. if (this._refractionTexture) {
  35818. this._refractionTexture.dispose();
  35819. }
  35820. }
  35821. this._renderTargets.dispose();
  35822. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35823. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35824. }
  35825. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35826. };
  35827. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35828. __decorate([
  35829. BABYLON.serializeAsImageProcessingConfiguration()
  35830. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35831. __decorate([
  35832. BABYLON.serialize()
  35833. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35834. return PBRBaseMaterial;
  35835. }(BABYLON.PushMaterial));
  35836. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35837. })(BABYLON || (BABYLON = {}));
  35838. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35839. var BABYLON;
  35840. (function (BABYLON) {
  35841. var Internals;
  35842. (function (Internals) {
  35843. /**
  35844. * The Physically based simple base material of BJS.
  35845. *
  35846. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35847. * It is used as the base class for both the specGloss and metalRough conventions.
  35848. */
  35849. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  35850. __extends(PBRBaseSimpleMaterial, _super);
  35851. /**
  35852. * Instantiates a new PBRMaterial instance.
  35853. *
  35854. * @param name The material name
  35855. * @param scene The scene the material will be use in.
  35856. */
  35857. function PBRBaseSimpleMaterial(name, scene) {
  35858. var _this = _super.call(this, name, scene) || this;
  35859. /**
  35860. * Number of Simultaneous lights allowed on the material.
  35861. */
  35862. _this.maxSimultaneousLights = 4;
  35863. /**
  35864. * If sets to true, disables all the lights affecting the material.
  35865. */
  35866. _this.disableLighting = false;
  35867. /**
  35868. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35869. */
  35870. _this.invertNormalMapX = false;
  35871. /**
  35872. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35873. */
  35874. _this.invertNormalMapY = false;
  35875. /**
  35876. * Emissivie color used to self-illuminate the model.
  35877. */
  35878. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35879. /**
  35880. * Occlusion Channel Strenght.
  35881. */
  35882. _this.occlusionStrength = 1.0;
  35883. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35884. _this._useAmbientInGrayScale = true;
  35885. return _this;
  35886. }
  35887. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35888. /**
  35889. * Gets the current transparency mode.
  35890. */
  35891. get: function () {
  35892. return this._transparencyMode;
  35893. },
  35894. /**
  35895. * Sets the transparency mode of the material.
  35896. */
  35897. set: function (value) {
  35898. if (this._transparencyMode === value) {
  35899. return;
  35900. }
  35901. this._transparencyMode = value;
  35902. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35903. this._forceAlphaTest = true;
  35904. }
  35905. else {
  35906. this._forceAlphaTest = false;
  35907. }
  35908. this._markAllSubMeshesAsTexturesDirty();
  35909. },
  35910. enumerable: true,
  35911. configurable: true
  35912. });
  35913. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35914. /**
  35915. * Gets the current double sided mode.
  35916. */
  35917. get: function () {
  35918. return this._twoSidedLighting;
  35919. },
  35920. /**
  35921. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35922. */
  35923. set: function (value) {
  35924. if (this._twoSidedLighting === value) {
  35925. return;
  35926. }
  35927. this._twoSidedLighting = value;
  35928. this.backFaceCulling = !value;
  35929. this._markAllSubMeshesAsTexturesDirty();
  35930. },
  35931. enumerable: true,
  35932. configurable: true
  35933. });
  35934. /**
  35935. * Specifies wether or not the alpha value of the albedo texture should be used.
  35936. */
  35937. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35938. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35939. };
  35940. /**
  35941. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35942. */
  35943. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35944. if (this._linkRefractionWithTransparency) {
  35945. return false;
  35946. }
  35947. return (this.alpha < 1.0) ||
  35948. (this._shouldUseAlphaFromAlbedoTexture() &&
  35949. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35950. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35951. };
  35952. /**
  35953. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35954. */
  35955. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35956. if (this._linkRefractionWithTransparency) {
  35957. return false;
  35958. }
  35959. return this._shouldUseAlphaFromAlbedoTexture() &&
  35960. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35961. };
  35962. /**
  35963. * Return the active textures of the material.
  35964. */
  35965. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  35966. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35967. if (this.environmentTexture) {
  35968. activeTextures.push(this.environmentTexture);
  35969. }
  35970. if (this.normalTexture) {
  35971. activeTextures.push(this.normalTexture);
  35972. }
  35973. if (this.emissiveTexture) {
  35974. activeTextures.push(this.emissiveTexture);
  35975. }
  35976. if (this.occlusionTexture) {
  35977. activeTextures.push(this.occlusionTexture);
  35978. }
  35979. return activeTextures;
  35980. };
  35981. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  35982. return "PBRBaseSimpleMaterial";
  35983. };
  35984. __decorate([
  35985. BABYLON.serialize(),
  35986. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35987. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35988. __decorate([
  35989. BABYLON.serialize(),
  35990. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35991. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35992. __decorate([
  35993. BABYLON.serializeAsTexture(),
  35994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35995. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35996. __decorate([
  35997. BABYLON.serialize(),
  35998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35999. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36000. __decorate([
  36001. BABYLON.serialize(),
  36002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36003. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36004. __decorate([
  36005. BABYLON.serializeAsTexture(),
  36006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36007. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36008. __decorate([
  36009. BABYLON.serializeAsColor3("emissive"),
  36010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36011. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36012. __decorate([
  36013. BABYLON.serializeAsTexture(),
  36014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36015. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36016. __decorate([
  36017. BABYLON.serialize(),
  36018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36019. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36020. __decorate([
  36021. BABYLON.serializeAsTexture(),
  36022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36023. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36024. __decorate([
  36025. BABYLON.serialize(),
  36026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36027. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36028. __decorate([
  36029. BABYLON.serialize()
  36030. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  36031. __decorate([
  36032. BABYLON.serialize()
  36033. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36034. return PBRBaseSimpleMaterial;
  36035. }(BABYLON.PBRBaseMaterial));
  36036. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36037. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36038. })(BABYLON || (BABYLON = {}));
  36039. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36040. var BABYLON;
  36041. (function (BABYLON) {
  36042. /**
  36043. * The Physically based material of BJS.
  36044. *
  36045. * This offers the main features of a standard PBR material.
  36046. * For more information, please refer to the documentation :
  36047. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36048. */
  36049. var PBRMaterial = /** @class */ (function (_super) {
  36050. __extends(PBRMaterial, _super);
  36051. /**
  36052. * Instantiates a new PBRMaterial instance.
  36053. *
  36054. * @param name The material name
  36055. * @param scene The scene the material will be use in.
  36056. */
  36057. function PBRMaterial(name, scene) {
  36058. var _this = _super.call(this, name, scene) || this;
  36059. /**
  36060. * Intensity of the direct lights e.g. the four lights available in your scene.
  36061. * This impacts both the direct diffuse and specular highlights.
  36062. */
  36063. _this.directIntensity = 1.0;
  36064. /**
  36065. * Intensity of the emissive part of the material.
  36066. * This helps controlling the emissive effect without modifying the emissive color.
  36067. */
  36068. _this.emissiveIntensity = 1.0;
  36069. /**
  36070. * Intensity of the environment e.g. how much the environment will light the object
  36071. * either through harmonics for rough material or through the refelction for shiny ones.
  36072. */
  36073. _this.environmentIntensity = 1.0;
  36074. /**
  36075. * This is a special control allowing the reduction of the specular highlights coming from the
  36076. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36077. */
  36078. _this.specularIntensity = 1.0;
  36079. /**
  36080. * Debug Control allowing disabling the bump map on this material.
  36081. */
  36082. _this.disableBumpMap = false;
  36083. /**
  36084. * AKA Occlusion Texture Intensity in other nomenclature.
  36085. */
  36086. _this.ambientTextureStrength = 1.0;
  36087. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36088. /**
  36089. * AKA Diffuse Color in other nomenclature.
  36090. */
  36091. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36092. /**
  36093. * AKA Specular Color in other nomenclature.
  36094. */
  36095. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36096. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36097. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36098. /**
  36099. * AKA Glossiness in other nomenclature.
  36100. */
  36101. _this.microSurface = 1.0;
  36102. /**
  36103. * source material index of refraction (IOR)' / 'destination material IOR.
  36104. */
  36105. _this.indexOfRefraction = 0.66;
  36106. /**
  36107. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36108. */
  36109. _this.invertRefractionY = false;
  36110. /**
  36111. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36112. * Materials half opaque for instance using refraction could benefit from this control.
  36113. */
  36114. _this.linkRefractionWithTransparency = false;
  36115. _this.useLightmapAsShadowmap = false;
  36116. /**
  36117. * Specifies that the alpha is coming form the albedo channel alpha channel.
  36118. */
  36119. _this.useAlphaFromAlbedoTexture = false;
  36120. /**
  36121. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36122. */
  36123. _this.forceAlphaTest = false;
  36124. /**
  36125. * Defines the alpha limits in alpha test mode.
  36126. */
  36127. _this.alphaCutOff = 0.4;
  36128. /**
  36129. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36130. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36131. */
  36132. _this.useSpecularOverAlpha = true;
  36133. /**
  36134. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36135. */
  36136. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36137. /**
  36138. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36139. */
  36140. _this.useRoughnessFromMetallicTextureAlpha = true;
  36141. /**
  36142. * Specifies if the metallic texture contains the roughness information in its green channel.
  36143. */
  36144. _this.useRoughnessFromMetallicTextureGreen = false;
  36145. /**
  36146. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36147. */
  36148. _this.useMetallnessFromMetallicTextureBlue = false;
  36149. /**
  36150. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36151. */
  36152. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36153. /**
  36154. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36155. */
  36156. _this.useAmbientInGrayScale = false;
  36157. /**
  36158. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36159. * The material will try to infer what glossiness each pixel should be.
  36160. */
  36161. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36162. /**
  36163. * BJS is using an harcoded light falloff based on a manually sets up range.
  36164. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36165. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36166. */
  36167. _this.usePhysicalLightFalloff = true;
  36168. /**
  36169. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36170. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36171. */
  36172. _this.useRadianceOverAlpha = true;
  36173. /**
  36174. * Allows using the bump map in parallax mode.
  36175. */
  36176. _this.useParallax = false;
  36177. /**
  36178. * Allows using the bump map in parallax occlusion mode.
  36179. */
  36180. _this.useParallaxOcclusion = false;
  36181. /**
  36182. * Controls the scale bias of the parallax mode.
  36183. */
  36184. _this.parallaxScaleBias = 0.05;
  36185. /**
  36186. * If sets to true, disables all the lights affecting the material.
  36187. */
  36188. _this.disableLighting = false;
  36189. /**
  36190. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36191. */
  36192. _this.forceIrradianceInFragment = false;
  36193. /**
  36194. * Number of Simultaneous lights allowed on the material.
  36195. */
  36196. _this.maxSimultaneousLights = 4;
  36197. /**
  36198. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36199. */
  36200. _this.invertNormalMapX = false;
  36201. /**
  36202. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36203. */
  36204. _this.invertNormalMapY = false;
  36205. /**
  36206. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36207. */
  36208. _this.twoSidedLighting = false;
  36209. /**
  36210. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36211. * And/Or occlude the blended part.
  36212. */
  36213. _this.useAlphaFresnel = false;
  36214. /**
  36215. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36216. * And/Or occlude the blended part.
  36217. */
  36218. _this.environmentBRDFTexture = null;
  36219. /**
  36220. * Force normal to face away from face.
  36221. * (Temporary internal fix to remove before 3.1)
  36222. */
  36223. _this.forceNormalForward = false;
  36224. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36225. return _this;
  36226. }
  36227. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36228. /**
  36229. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36230. */
  36231. get: function () {
  36232. return this._PBRMATERIAL_OPAQUE;
  36233. },
  36234. enumerable: true,
  36235. configurable: true
  36236. });
  36237. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36238. /**
  36239. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36240. */
  36241. get: function () {
  36242. return this._PBRMATERIAL_ALPHATEST;
  36243. },
  36244. enumerable: true,
  36245. configurable: true
  36246. });
  36247. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36248. /**
  36249. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36250. */
  36251. get: function () {
  36252. return this._PBRMATERIAL_ALPHABLEND;
  36253. },
  36254. enumerable: true,
  36255. configurable: true
  36256. });
  36257. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36258. /**
  36259. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36260. * They are also discarded below the alpha cutoff threshold to improve performances.
  36261. */
  36262. get: function () {
  36263. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36264. },
  36265. enumerable: true,
  36266. configurable: true
  36267. });
  36268. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36269. /**
  36270. * Gets the image processing configuration used either in this material.
  36271. */
  36272. get: function () {
  36273. return this._imageProcessingConfiguration;
  36274. },
  36275. /**
  36276. * Sets the Default image processing configuration used either in the this material.
  36277. *
  36278. * If sets to null, the scene one is in use.
  36279. */
  36280. set: function (value) {
  36281. this._attachImageProcessingConfiguration(value);
  36282. // Ensure the effect will be rebuilt.
  36283. this._markAllSubMeshesAsTexturesDirty();
  36284. },
  36285. enumerable: true,
  36286. configurable: true
  36287. });
  36288. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36289. /**
  36290. * Gets wether the color curves effect is enabled.
  36291. */
  36292. get: function () {
  36293. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36294. },
  36295. /**
  36296. * Sets wether the color curves effect is enabled.
  36297. */
  36298. set: function (value) {
  36299. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36300. },
  36301. enumerable: true,
  36302. configurable: true
  36303. });
  36304. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36305. /**
  36306. * Gets wether the color grading effect is enabled.
  36307. */
  36308. get: function () {
  36309. return this.imageProcessingConfiguration.colorGradingEnabled;
  36310. },
  36311. /**
  36312. * Gets wether the color grading effect is enabled.
  36313. */
  36314. set: function (value) {
  36315. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36316. },
  36317. enumerable: true,
  36318. configurable: true
  36319. });
  36320. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36321. /**
  36322. * Gets wether tonemapping is enabled or not.
  36323. */
  36324. get: function () {
  36325. return this._imageProcessingConfiguration.toneMappingEnabled;
  36326. },
  36327. /**
  36328. * Sets wether tonemapping is enabled or not
  36329. */
  36330. set: function (value) {
  36331. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36332. },
  36333. enumerable: true,
  36334. configurable: true
  36335. });
  36336. ;
  36337. ;
  36338. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36339. /**
  36340. * The camera exposure used on this material.
  36341. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36342. * This corresponds to a photographic exposure.
  36343. */
  36344. get: function () {
  36345. return this._imageProcessingConfiguration.exposure;
  36346. },
  36347. /**
  36348. * The camera exposure used on this material.
  36349. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36350. * This corresponds to a photographic exposure.
  36351. */
  36352. set: function (value) {
  36353. this._imageProcessingConfiguration.exposure = value;
  36354. },
  36355. enumerable: true,
  36356. configurable: true
  36357. });
  36358. ;
  36359. ;
  36360. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36361. /**
  36362. * Gets The camera contrast used on this material.
  36363. */
  36364. get: function () {
  36365. return this._imageProcessingConfiguration.contrast;
  36366. },
  36367. /**
  36368. * Sets The camera contrast used on this material.
  36369. */
  36370. set: function (value) {
  36371. this._imageProcessingConfiguration.contrast = value;
  36372. },
  36373. enumerable: true,
  36374. configurable: true
  36375. });
  36376. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36377. /**
  36378. * Gets the Color Grading 2D Lookup Texture.
  36379. */
  36380. get: function () {
  36381. return this._imageProcessingConfiguration.colorGradingTexture;
  36382. },
  36383. /**
  36384. * Sets the Color Grading 2D Lookup Texture.
  36385. */
  36386. set: function (value) {
  36387. this._imageProcessingConfiguration.colorGradingTexture = value;
  36388. },
  36389. enumerable: true,
  36390. configurable: true
  36391. });
  36392. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36393. /**
  36394. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36395. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36396. * 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;
  36397. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36398. */
  36399. get: function () {
  36400. return this._imageProcessingConfiguration.colorCurves;
  36401. },
  36402. /**
  36403. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36404. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36405. * 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;
  36406. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36407. */
  36408. set: function (value) {
  36409. this._imageProcessingConfiguration.colorCurves = value;
  36410. },
  36411. enumerable: true,
  36412. configurable: true
  36413. });
  36414. PBRMaterial.prototype.getClassName = function () {
  36415. return "PBRMaterial";
  36416. };
  36417. PBRMaterial.prototype.getActiveTextures = function () {
  36418. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36419. if (this._albedoTexture) {
  36420. activeTextures.push(this._albedoTexture);
  36421. }
  36422. if (this._ambientTexture) {
  36423. activeTextures.push(this._ambientTexture);
  36424. }
  36425. if (this._opacityTexture) {
  36426. activeTextures.push(this._opacityTexture);
  36427. }
  36428. if (this._reflectionTexture) {
  36429. activeTextures.push(this._reflectionTexture);
  36430. }
  36431. if (this._emissiveTexture) {
  36432. activeTextures.push(this._emissiveTexture);
  36433. }
  36434. if (this._reflectivityTexture) {
  36435. activeTextures.push(this._reflectivityTexture);
  36436. }
  36437. if (this._metallicTexture) {
  36438. activeTextures.push(this._metallicTexture);
  36439. }
  36440. if (this._microSurfaceTexture) {
  36441. activeTextures.push(this._microSurfaceTexture);
  36442. }
  36443. if (this._bumpTexture) {
  36444. activeTextures.push(this._bumpTexture);
  36445. }
  36446. if (this._lightmapTexture) {
  36447. activeTextures.push(this._lightmapTexture);
  36448. }
  36449. if (this._refractionTexture) {
  36450. activeTextures.push(this._refractionTexture);
  36451. }
  36452. return activeTextures;
  36453. };
  36454. PBRMaterial.prototype.hasTexture = function (texture) {
  36455. if (_super.prototype.hasTexture.call(this, texture)) {
  36456. return true;
  36457. }
  36458. if (this._albedoTexture === texture) {
  36459. return true;
  36460. }
  36461. if (this._ambientTexture === texture) {
  36462. return true;
  36463. }
  36464. if (this._opacityTexture === texture) {
  36465. return true;
  36466. }
  36467. if (this._reflectionTexture === texture) {
  36468. return true;
  36469. }
  36470. if (this._reflectivityTexture === texture) {
  36471. return true;
  36472. }
  36473. if (this._metallicTexture === texture) {
  36474. return true;
  36475. }
  36476. if (this._microSurfaceTexture === texture) {
  36477. return true;
  36478. }
  36479. if (this._bumpTexture === texture) {
  36480. return true;
  36481. }
  36482. if (this._lightmapTexture === texture) {
  36483. return true;
  36484. }
  36485. if (this._refractionTexture === texture) {
  36486. return true;
  36487. }
  36488. return false;
  36489. };
  36490. PBRMaterial.prototype.clone = function (name) {
  36491. var _this = this;
  36492. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36493. clone.id = name;
  36494. clone.name = name;
  36495. return clone;
  36496. };
  36497. PBRMaterial.prototype.serialize = function () {
  36498. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36499. serializationObject.customType = "BABYLON.PBRMaterial";
  36500. return serializationObject;
  36501. };
  36502. // Statics
  36503. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36504. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36505. };
  36506. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36507. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36508. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36509. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36510. __decorate([
  36511. BABYLON.serialize(),
  36512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36513. ], PBRMaterial.prototype, "directIntensity", void 0);
  36514. __decorate([
  36515. BABYLON.serialize(),
  36516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36517. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36518. __decorate([
  36519. BABYLON.serialize(),
  36520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36521. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36522. __decorate([
  36523. BABYLON.serialize(),
  36524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36525. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36526. __decorate([
  36527. BABYLON.serialize(),
  36528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36529. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36530. __decorate([
  36531. BABYLON.serializeAsTexture(),
  36532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36533. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36534. __decorate([
  36535. BABYLON.serializeAsTexture(),
  36536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36537. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36538. __decorate([
  36539. BABYLON.serialize(),
  36540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36541. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36542. __decorate([
  36543. BABYLON.serializeAsTexture(),
  36544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36545. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36546. __decorate([
  36547. BABYLON.serializeAsTexture(),
  36548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36549. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36550. __decorate([
  36551. BABYLON.serializeAsTexture(),
  36552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36553. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36554. __decorate([
  36555. BABYLON.serializeAsTexture(),
  36556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36557. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36558. __decorate([
  36559. BABYLON.serializeAsTexture(),
  36560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36561. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36562. __decorate([
  36563. BABYLON.serialize(),
  36564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36565. ], PBRMaterial.prototype, "metallic", void 0);
  36566. __decorate([
  36567. BABYLON.serialize(),
  36568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36569. ], PBRMaterial.prototype, "roughness", void 0);
  36570. __decorate([
  36571. BABYLON.serializeAsTexture(),
  36572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36573. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36574. __decorate([
  36575. BABYLON.serializeAsTexture(),
  36576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36577. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36578. __decorate([
  36579. BABYLON.serializeAsTexture(),
  36580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36581. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36582. __decorate([
  36583. BABYLON.serializeAsTexture(),
  36584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36585. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36586. __decorate([
  36587. BABYLON.serializeAsColor3("ambient"),
  36588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36589. ], PBRMaterial.prototype, "ambientColor", void 0);
  36590. __decorate([
  36591. BABYLON.serializeAsColor3("albedo"),
  36592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36593. ], PBRMaterial.prototype, "albedoColor", void 0);
  36594. __decorate([
  36595. BABYLON.serializeAsColor3("reflectivity"),
  36596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36597. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36598. __decorate([
  36599. BABYLON.serializeAsColor3("reflection"),
  36600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36601. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36602. __decorate([
  36603. BABYLON.serializeAsColor3("emissive"),
  36604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36605. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36606. __decorate([
  36607. BABYLON.serialize(),
  36608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36609. ], PBRMaterial.prototype, "microSurface", void 0);
  36610. __decorate([
  36611. BABYLON.serialize(),
  36612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36613. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36614. __decorate([
  36615. BABYLON.serialize(),
  36616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36617. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36618. __decorate([
  36619. BABYLON.serialize(),
  36620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36621. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36622. __decorate([
  36623. BABYLON.serialize(),
  36624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36625. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36626. __decorate([
  36627. BABYLON.serialize(),
  36628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36629. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36630. __decorate([
  36631. BABYLON.serialize(),
  36632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36633. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  36634. __decorate([
  36635. BABYLON.serialize(),
  36636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36637. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  36638. __decorate([
  36639. BABYLON.serialize(),
  36640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36641. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36642. __decorate([
  36643. BABYLON.serialize(),
  36644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36645. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36646. __decorate([
  36647. BABYLON.serialize(),
  36648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36649. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36650. __decorate([
  36651. BABYLON.serialize(),
  36652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36653. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36654. __decorate([
  36655. BABYLON.serialize(),
  36656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36657. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36658. __decorate([
  36659. BABYLON.serialize(),
  36660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36661. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36662. __decorate([
  36663. BABYLON.serialize(),
  36664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36665. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36666. __decorate([
  36667. BABYLON.serialize(),
  36668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36669. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36670. __decorate([
  36671. BABYLON.serialize(),
  36672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36673. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36674. __decorate([
  36675. BABYLON.serialize(),
  36676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36677. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36678. __decorate([
  36679. BABYLON.serialize(),
  36680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36681. ], PBRMaterial.prototype, "useParallax", void 0);
  36682. __decorate([
  36683. BABYLON.serialize(),
  36684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36685. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36686. __decorate([
  36687. BABYLON.serialize(),
  36688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36689. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36690. __decorate([
  36691. BABYLON.serialize(),
  36692. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36693. ], PBRMaterial.prototype, "disableLighting", void 0);
  36694. __decorate([
  36695. BABYLON.serialize(),
  36696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36697. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  36698. __decorate([
  36699. BABYLON.serialize(),
  36700. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36701. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36702. __decorate([
  36703. BABYLON.serialize(),
  36704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36705. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36706. __decorate([
  36707. BABYLON.serialize(),
  36708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36709. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36710. __decorate([
  36711. BABYLON.serialize(),
  36712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36713. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36714. __decorate([
  36715. BABYLON.serialize(),
  36716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36717. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36718. __decorate([
  36719. BABYLON.serializeAsTexture(),
  36720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36721. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36722. __decorate([
  36723. BABYLON.serialize(),
  36724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36725. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36726. return PBRMaterial;
  36727. }(BABYLON.PBRBaseMaterial));
  36728. BABYLON.PBRMaterial = PBRMaterial;
  36729. })(BABYLON || (BABYLON = {}));
  36730. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36731. var BABYLON;
  36732. (function (BABYLON) {
  36733. /**
  36734. * The PBR material of BJS following the metal roughness convention.
  36735. *
  36736. * This fits to the PBR convention in the GLTF definition:
  36737. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36738. */
  36739. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36740. __extends(PBRMetallicRoughnessMaterial, _super);
  36741. /**
  36742. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36743. *
  36744. * @param name The material name
  36745. * @param scene The scene the material will be use in.
  36746. */
  36747. function PBRMetallicRoughnessMaterial(name, scene) {
  36748. var _this = _super.call(this, name, scene) || this;
  36749. _this._useRoughnessFromMetallicTextureAlpha = false;
  36750. _this._useRoughnessFromMetallicTextureGreen = true;
  36751. _this._useMetallnessFromMetallicTextureBlue = true;
  36752. return _this;
  36753. }
  36754. /**
  36755. * Return the currrent class name of the material.
  36756. */
  36757. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36758. return "PBRMetallicRoughnessMaterial";
  36759. };
  36760. /**
  36761. * Return the active textures of the material.
  36762. */
  36763. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36764. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36765. if (this.baseTexture) {
  36766. activeTextures.push(this.baseTexture);
  36767. }
  36768. if (this.metallicRoughnessTexture) {
  36769. activeTextures.push(this.metallicRoughnessTexture);
  36770. }
  36771. return activeTextures;
  36772. };
  36773. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36774. if (_super.prototype.hasTexture.call(this, texture)) {
  36775. return true;
  36776. }
  36777. if (this.baseTexture === texture) {
  36778. return true;
  36779. }
  36780. if (this.metallicRoughnessTexture === texture) {
  36781. return true;
  36782. }
  36783. return false;
  36784. };
  36785. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36786. var _this = this;
  36787. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36788. clone.id = name;
  36789. clone.name = name;
  36790. return clone;
  36791. };
  36792. /**
  36793. * Serialize the material to a parsable JSON object.
  36794. */
  36795. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36796. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36797. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36798. return serializationObject;
  36799. };
  36800. /**
  36801. * Parses a JSON object correponding to the serialize function.
  36802. */
  36803. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36804. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36805. };
  36806. __decorate([
  36807. BABYLON.serializeAsColor3(),
  36808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36809. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36810. __decorate([
  36811. BABYLON.serializeAsTexture(),
  36812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36813. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36814. __decorate([
  36815. BABYLON.serialize(),
  36816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36817. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36818. __decorate([
  36819. BABYLON.serialize(),
  36820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36821. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36822. __decorate([
  36823. BABYLON.serializeAsTexture(),
  36824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36825. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36826. return PBRMetallicRoughnessMaterial;
  36827. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36828. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36829. })(BABYLON || (BABYLON = {}));
  36830. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36831. var BABYLON;
  36832. (function (BABYLON) {
  36833. /**
  36834. * The PBR material of BJS following the specular glossiness convention.
  36835. *
  36836. * This fits to the PBR convention in the GLTF definition:
  36837. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36838. */
  36839. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  36840. __extends(PBRSpecularGlossinessMaterial, _super);
  36841. /**
  36842. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36843. *
  36844. * @param name The material name
  36845. * @param scene The scene the material will be use in.
  36846. */
  36847. function PBRSpecularGlossinessMaterial(name, scene) {
  36848. var _this = _super.call(this, name, scene) || this;
  36849. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36850. return _this;
  36851. }
  36852. /**
  36853. * Return the currrent class name of the material.
  36854. */
  36855. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36856. return "PBRSpecularGlossinessMaterial";
  36857. };
  36858. /**
  36859. * Return the active textures of the material.
  36860. */
  36861. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36862. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36863. if (this.diffuseTexture) {
  36864. activeTextures.push(this.diffuseTexture);
  36865. }
  36866. if (this.specularGlossinessTexture) {
  36867. activeTextures.push(this.specularGlossinessTexture);
  36868. }
  36869. return activeTextures;
  36870. };
  36871. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  36872. if (_super.prototype.hasTexture.call(this, texture)) {
  36873. return true;
  36874. }
  36875. if (this.diffuseTexture === texture) {
  36876. return true;
  36877. }
  36878. if (this.specularGlossinessTexture === texture) {
  36879. return true;
  36880. }
  36881. return false;
  36882. };
  36883. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36884. var _this = this;
  36885. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36886. clone.id = name;
  36887. clone.name = name;
  36888. return clone;
  36889. };
  36890. /**
  36891. * Serialize the material to a parsable JSON object.
  36892. */
  36893. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36894. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36895. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36896. return serializationObject;
  36897. };
  36898. /**
  36899. * Parses a JSON object correponding to the serialize function.
  36900. */
  36901. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36902. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36903. };
  36904. __decorate([
  36905. BABYLON.serializeAsColor3("diffuse"),
  36906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36907. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36908. __decorate([
  36909. BABYLON.serializeAsTexture(),
  36910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36911. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36912. __decorate([
  36913. BABYLON.serializeAsColor3("specular"),
  36914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36915. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36916. __decorate([
  36917. BABYLON.serialize(),
  36918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36919. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36920. __decorate([
  36921. BABYLON.serializeAsTexture(),
  36922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36923. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36924. return PBRSpecularGlossinessMaterial;
  36925. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36926. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36927. })(BABYLON || (BABYLON = {}));
  36928. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36929. var BABYLON;
  36930. (function (BABYLON) {
  36931. BABYLON.CameraInputTypes = {};
  36932. var CameraInputsManager = /** @class */ (function () {
  36933. function CameraInputsManager(camera) {
  36934. this.attached = {};
  36935. this.camera = camera;
  36936. this.checkInputs = function () { };
  36937. }
  36938. CameraInputsManager.prototype.add = function (input) {
  36939. var type = input.getSimpleName();
  36940. if (this.attached[type]) {
  36941. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  36942. return;
  36943. }
  36944. this.attached[type] = input;
  36945. input.camera = this.camera;
  36946. //for checkInputs, we are dynamically creating a function
  36947. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  36948. if (input.checkInputs) {
  36949. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36950. }
  36951. if (this.attachedElement) {
  36952. input.attachControl(this.attachedElement);
  36953. }
  36954. };
  36955. CameraInputsManager.prototype.remove = function (inputToRemove) {
  36956. for (var cam in this.attached) {
  36957. var input = this.attached[cam];
  36958. if (input === inputToRemove) {
  36959. input.detachControl(this.attachedElement);
  36960. input.camera = null;
  36961. delete this.attached[cam];
  36962. this.rebuildInputCheck();
  36963. }
  36964. }
  36965. };
  36966. CameraInputsManager.prototype.removeByType = function (inputType) {
  36967. for (var cam in this.attached) {
  36968. var input = this.attached[cam];
  36969. if (input.getClassName() === inputType) {
  36970. input.detachControl(this.attachedElement);
  36971. input.camera = null;
  36972. delete this.attached[cam];
  36973. this.rebuildInputCheck();
  36974. }
  36975. }
  36976. };
  36977. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  36978. var current = this.checkInputs;
  36979. return function () {
  36980. current();
  36981. fn();
  36982. };
  36983. };
  36984. CameraInputsManager.prototype.attachInput = function (input) {
  36985. if (this.attachedElement) {
  36986. input.attachControl(this.attachedElement, this.noPreventDefault);
  36987. }
  36988. };
  36989. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  36990. if (noPreventDefault === void 0) { noPreventDefault = false; }
  36991. if (this.attachedElement) {
  36992. return;
  36993. }
  36994. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  36995. this.attachedElement = element;
  36996. this.noPreventDefault = noPreventDefault;
  36997. for (var cam in this.attached) {
  36998. this.attached[cam].attachControl(element, noPreventDefault);
  36999. }
  37000. };
  37001. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37002. if (disconnect === void 0) { disconnect = false; }
  37003. if (this.attachedElement !== element) {
  37004. return;
  37005. }
  37006. for (var cam in this.attached) {
  37007. this.attached[cam].detachControl(element);
  37008. if (disconnect) {
  37009. this.attached[cam].camera = null;
  37010. }
  37011. }
  37012. this.attachedElement = null;
  37013. };
  37014. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37015. this.checkInputs = function () { };
  37016. for (var cam in this.attached) {
  37017. var input = this.attached[cam];
  37018. if (input.checkInputs) {
  37019. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37020. }
  37021. }
  37022. };
  37023. CameraInputsManager.prototype.clear = function () {
  37024. if (this.attachedElement) {
  37025. this.detachElement(this.attachedElement, true);
  37026. }
  37027. this.attached = {};
  37028. this.attachedElement = null;
  37029. this.checkInputs = function () { };
  37030. };
  37031. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37032. var inputs = {};
  37033. for (var cam in this.attached) {
  37034. var input = this.attached[cam];
  37035. var res = BABYLON.SerializationHelper.Serialize(input);
  37036. inputs[input.getClassName()] = res;
  37037. }
  37038. serializedCamera.inputsmgr = inputs;
  37039. };
  37040. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37041. var parsedInputs = parsedCamera.inputsmgr;
  37042. if (parsedInputs) {
  37043. this.clear();
  37044. for (var n in parsedInputs) {
  37045. var construct = BABYLON.CameraInputTypes[n];
  37046. if (construct) {
  37047. var parsedinput = parsedInputs[n];
  37048. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37049. this.add(input);
  37050. }
  37051. }
  37052. }
  37053. else {
  37054. //2016-03-08 this part is for managing backward compatibility
  37055. for (var n in this.attached) {
  37056. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37057. if (construct) {
  37058. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37059. this.remove(this.attached[n]);
  37060. this.add(input);
  37061. }
  37062. }
  37063. }
  37064. };
  37065. return CameraInputsManager;
  37066. }());
  37067. BABYLON.CameraInputsManager = CameraInputsManager;
  37068. })(BABYLON || (BABYLON = {}));
  37069. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37070. var BABYLON;
  37071. (function (BABYLON) {
  37072. var FreeCameraMouseInput = /** @class */ (function () {
  37073. function FreeCameraMouseInput(touchEnabled) {
  37074. if (touchEnabled === void 0) { touchEnabled = true; }
  37075. this.touchEnabled = touchEnabled;
  37076. this.buttons = [0, 1, 2];
  37077. this.angularSensibility = 2000.0;
  37078. this.previousPosition = null;
  37079. }
  37080. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37081. var _this = this;
  37082. var engine = this.camera.getEngine();
  37083. if (!this._pointerInput) {
  37084. this._pointerInput = function (p, s) {
  37085. var evt = p.event;
  37086. if (engine.isInVRExclusivePointerMode) {
  37087. return;
  37088. }
  37089. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37090. return;
  37091. }
  37092. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37093. return;
  37094. }
  37095. var srcElement = (evt.srcElement || evt.target);
  37096. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37097. try {
  37098. srcElement.setPointerCapture(evt.pointerId);
  37099. }
  37100. catch (e) {
  37101. //Nothing to do with the error. Execution will continue.
  37102. }
  37103. _this.previousPosition = {
  37104. x: evt.clientX,
  37105. y: evt.clientY
  37106. };
  37107. if (!noPreventDefault) {
  37108. evt.preventDefault();
  37109. element.focus();
  37110. }
  37111. }
  37112. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37113. try {
  37114. srcElement.releasePointerCapture(evt.pointerId);
  37115. }
  37116. catch (e) {
  37117. //Nothing to do with the error.
  37118. }
  37119. _this.previousPosition = null;
  37120. if (!noPreventDefault) {
  37121. evt.preventDefault();
  37122. }
  37123. }
  37124. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37125. if (!_this.previousPosition || engine.isPointerLock) {
  37126. return;
  37127. }
  37128. var offsetX = evt.clientX - _this.previousPosition.x;
  37129. var offsetY = evt.clientY - _this.previousPosition.y;
  37130. if (_this.camera.getScene().useRightHandedSystem) {
  37131. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37132. }
  37133. else {
  37134. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37135. }
  37136. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37137. _this.previousPosition = {
  37138. x: evt.clientX,
  37139. y: evt.clientY
  37140. };
  37141. if (!noPreventDefault) {
  37142. evt.preventDefault();
  37143. }
  37144. }
  37145. };
  37146. }
  37147. this._onMouseMove = function (evt) {
  37148. if (!engine.isPointerLock) {
  37149. return;
  37150. }
  37151. if (engine.isInVRExclusivePointerMode) {
  37152. return;
  37153. }
  37154. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37155. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37156. if (_this.camera.getScene().useRightHandedSystem) {
  37157. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37158. }
  37159. else {
  37160. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37161. }
  37162. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37163. _this.previousPosition = null;
  37164. if (!noPreventDefault) {
  37165. evt.preventDefault();
  37166. }
  37167. };
  37168. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37169. element.addEventListener("mousemove", this._onMouseMove, false);
  37170. };
  37171. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37172. if (this._observer && element) {
  37173. this.camera.getScene().onPointerObservable.remove(this._observer);
  37174. if (this._onMouseMove) {
  37175. element.removeEventListener("mousemove", this._onMouseMove);
  37176. }
  37177. this._observer = null;
  37178. this._onMouseMove = null;
  37179. this.previousPosition = null;
  37180. }
  37181. };
  37182. FreeCameraMouseInput.prototype.getClassName = function () {
  37183. return "FreeCameraMouseInput";
  37184. };
  37185. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37186. return "mouse";
  37187. };
  37188. __decorate([
  37189. BABYLON.serialize()
  37190. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37191. __decorate([
  37192. BABYLON.serialize()
  37193. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37194. return FreeCameraMouseInput;
  37195. }());
  37196. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37197. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37198. })(BABYLON || (BABYLON = {}));
  37199. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37200. var BABYLON;
  37201. (function (BABYLON) {
  37202. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37203. function FreeCameraKeyboardMoveInput() {
  37204. this._keys = new Array();
  37205. this.keysUp = [38];
  37206. this.keysDown = [40];
  37207. this.keysLeft = [37];
  37208. this.keysRight = [39];
  37209. }
  37210. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37211. var _this = this;
  37212. if (this._onCanvasBlurObserver) {
  37213. return;
  37214. }
  37215. this._scene = this.camera.getScene();
  37216. this._engine = this._scene.getEngine();
  37217. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37218. _this._keys = [];
  37219. });
  37220. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37221. var evt = info.event;
  37222. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37223. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37224. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37225. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37226. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37227. var index = _this._keys.indexOf(evt.keyCode);
  37228. if (index === -1) {
  37229. _this._keys.push(evt.keyCode);
  37230. }
  37231. if (!noPreventDefault) {
  37232. evt.preventDefault();
  37233. }
  37234. }
  37235. }
  37236. else {
  37237. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37238. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37239. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37240. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37241. var index = _this._keys.indexOf(evt.keyCode);
  37242. if (index >= 0) {
  37243. _this._keys.splice(index, 1);
  37244. }
  37245. if (!noPreventDefault) {
  37246. evt.preventDefault();
  37247. }
  37248. }
  37249. }
  37250. });
  37251. };
  37252. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37253. if (this._scene) {
  37254. if (this._onKeyboardObserver) {
  37255. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37256. }
  37257. if (this._onCanvasBlurObserver) {
  37258. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37259. }
  37260. this._onKeyboardObserver = null;
  37261. this._onCanvasBlurObserver = null;
  37262. }
  37263. this._keys = [];
  37264. };
  37265. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37266. if (this._onKeyboardObserver) {
  37267. var camera = this.camera;
  37268. // Keyboard
  37269. for (var index = 0; index < this._keys.length; index++) {
  37270. var keyCode = this._keys[index];
  37271. var speed = camera._computeLocalCameraSpeed();
  37272. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37273. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37274. }
  37275. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37276. camera._localDirection.copyFromFloats(0, 0, speed);
  37277. }
  37278. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37279. camera._localDirection.copyFromFloats(speed, 0, 0);
  37280. }
  37281. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37282. camera._localDirection.copyFromFloats(0, 0, -speed);
  37283. }
  37284. if (camera.getScene().useRightHandedSystem) {
  37285. camera._localDirection.z *= -1;
  37286. }
  37287. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37288. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37289. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37290. }
  37291. }
  37292. };
  37293. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37294. return "FreeCameraKeyboardMoveInput";
  37295. };
  37296. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37297. this._keys = [];
  37298. };
  37299. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37300. return "keyboard";
  37301. };
  37302. __decorate([
  37303. BABYLON.serialize()
  37304. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37305. __decorate([
  37306. BABYLON.serialize()
  37307. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37308. __decorate([
  37309. BABYLON.serialize()
  37310. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37311. __decorate([
  37312. BABYLON.serialize()
  37313. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37314. return FreeCameraKeyboardMoveInput;
  37315. }());
  37316. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37317. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37318. })(BABYLON || (BABYLON = {}));
  37319. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37320. var BABYLON;
  37321. (function (BABYLON) {
  37322. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37323. __extends(FreeCameraInputsManager, _super);
  37324. function FreeCameraInputsManager(camera) {
  37325. return _super.call(this, camera) || this;
  37326. }
  37327. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37328. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37329. return this;
  37330. };
  37331. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37332. if (touchEnabled === void 0) { touchEnabled = true; }
  37333. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37334. return this;
  37335. };
  37336. FreeCameraInputsManager.prototype.addGamepad = function () {
  37337. this.add(new BABYLON.FreeCameraGamepadInput());
  37338. return this;
  37339. };
  37340. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37341. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37342. return this;
  37343. };
  37344. FreeCameraInputsManager.prototype.addTouch = function () {
  37345. this.add(new BABYLON.FreeCameraTouchInput());
  37346. return this;
  37347. };
  37348. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37349. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37350. return this;
  37351. };
  37352. return FreeCameraInputsManager;
  37353. }(BABYLON.CameraInputsManager));
  37354. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37355. })(BABYLON || (BABYLON = {}));
  37356. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37357. var BABYLON;
  37358. (function (BABYLON) {
  37359. var TargetCamera = /** @class */ (function (_super) {
  37360. __extends(TargetCamera, _super);
  37361. function TargetCamera(name, position, scene) {
  37362. var _this = _super.call(this, name, position, scene) || this;
  37363. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37364. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37365. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37366. _this.speed = 2.0;
  37367. _this.noRotationConstraint = false;
  37368. _this.lockedTarget = null;
  37369. _this._currentTarget = BABYLON.Vector3.Zero();
  37370. _this._viewMatrix = BABYLON.Matrix.Zero();
  37371. _this._camMatrix = BABYLON.Matrix.Zero();
  37372. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37373. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37374. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37375. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37376. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37377. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37378. _this._tempMatrix = BABYLON.Matrix.Zero();
  37379. return _this;
  37380. }
  37381. TargetCamera.prototype.getFrontPosition = function (distance) {
  37382. var direction = this.getTarget().subtract(this.position);
  37383. direction.normalize();
  37384. direction.scaleInPlace(distance);
  37385. return this.globalPosition.add(direction);
  37386. };
  37387. TargetCamera.prototype._getLockedTargetPosition = function () {
  37388. if (!this.lockedTarget) {
  37389. return null;
  37390. }
  37391. if (this.lockedTarget.absolutePosition) {
  37392. this.lockedTarget.computeWorldMatrix();
  37393. }
  37394. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37395. };
  37396. TargetCamera.prototype.storeState = function () {
  37397. this._storedPosition = this.position.clone();
  37398. this._storedRotation = this.rotation.clone();
  37399. if (this.rotationQuaternion) {
  37400. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37401. }
  37402. return _super.prototype.storeState.call(this);
  37403. };
  37404. /**
  37405. * Restored camera state. You must call storeState() first
  37406. */
  37407. TargetCamera.prototype._restoreStateValues = function () {
  37408. if (!_super.prototype._restoreStateValues.call(this)) {
  37409. return false;
  37410. }
  37411. this.position = this._storedPosition.clone();
  37412. this.rotation = this._storedRotation.clone();
  37413. if (this.rotationQuaternion) {
  37414. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37415. }
  37416. this.cameraDirection.copyFromFloats(0, 0, 0);
  37417. this.cameraRotation.copyFromFloats(0, 0);
  37418. return true;
  37419. };
  37420. // Cache
  37421. TargetCamera.prototype._initCache = function () {
  37422. _super.prototype._initCache.call(this);
  37423. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37424. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37425. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37426. };
  37427. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37428. if (!ignoreParentClass) {
  37429. _super.prototype._updateCache.call(this);
  37430. }
  37431. var lockedTargetPosition = this._getLockedTargetPosition();
  37432. if (!lockedTargetPosition) {
  37433. this._cache.lockedTarget = null;
  37434. }
  37435. else {
  37436. if (!this._cache.lockedTarget) {
  37437. this._cache.lockedTarget = lockedTargetPosition.clone();
  37438. }
  37439. else {
  37440. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37441. }
  37442. }
  37443. this._cache.rotation.copyFrom(this.rotation);
  37444. if (this.rotationQuaternion)
  37445. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37446. };
  37447. // Synchronized
  37448. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37449. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37450. return false;
  37451. }
  37452. var lockedTargetPosition = this._getLockedTargetPosition();
  37453. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37454. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37455. };
  37456. // Methods
  37457. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37458. var engine = this.getEngine();
  37459. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37460. };
  37461. // Target
  37462. TargetCamera.prototype.setTarget = function (target) {
  37463. this.upVector.normalize();
  37464. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37465. this._camMatrix.invert();
  37466. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37467. var vDir = target.subtract(this.position);
  37468. if (vDir.x >= 0.0) {
  37469. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37470. }
  37471. else {
  37472. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37473. }
  37474. this.rotation.z = 0;
  37475. if (isNaN(this.rotation.x)) {
  37476. this.rotation.x = 0;
  37477. }
  37478. if (isNaN(this.rotation.y)) {
  37479. this.rotation.y = 0;
  37480. }
  37481. if (isNaN(this.rotation.z)) {
  37482. this.rotation.z = 0;
  37483. }
  37484. if (this.rotationQuaternion) {
  37485. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37486. }
  37487. };
  37488. /**
  37489. * Return the current target position of the camera. This value is expressed in local space.
  37490. */
  37491. TargetCamera.prototype.getTarget = function () {
  37492. return this._currentTarget;
  37493. };
  37494. TargetCamera.prototype._decideIfNeedsToMove = function () {
  37495. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37496. };
  37497. TargetCamera.prototype._updatePosition = function () {
  37498. if (this.parent) {
  37499. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  37500. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  37501. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  37502. return;
  37503. }
  37504. this.position.addInPlace(this.cameraDirection);
  37505. };
  37506. TargetCamera.prototype._checkInputs = function () {
  37507. var needToMove = this._decideIfNeedsToMove();
  37508. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  37509. // Move
  37510. if (needToMove) {
  37511. this._updatePosition();
  37512. }
  37513. // Rotate
  37514. if (needToRotate) {
  37515. this.rotation.x += this.cameraRotation.x;
  37516. this.rotation.y += this.cameraRotation.y;
  37517. //rotate, if quaternion is set and rotation was used
  37518. if (this.rotationQuaternion) {
  37519. var len = this.rotation.lengthSquared();
  37520. if (len) {
  37521. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37522. }
  37523. }
  37524. if (!this.noRotationConstraint) {
  37525. var limit = (Math.PI / 2) * 0.95;
  37526. if (this.rotation.x > limit)
  37527. this.rotation.x = limit;
  37528. if (this.rotation.x < -limit)
  37529. this.rotation.x = -limit;
  37530. }
  37531. }
  37532. // Inertia
  37533. if (needToMove) {
  37534. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  37535. this.cameraDirection.x = 0;
  37536. }
  37537. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  37538. this.cameraDirection.y = 0;
  37539. }
  37540. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  37541. this.cameraDirection.z = 0;
  37542. }
  37543. this.cameraDirection.scaleInPlace(this.inertia);
  37544. }
  37545. if (needToRotate) {
  37546. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  37547. this.cameraRotation.x = 0;
  37548. }
  37549. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  37550. this.cameraRotation.y = 0;
  37551. }
  37552. this.cameraRotation.scaleInPlace(this.inertia);
  37553. }
  37554. _super.prototype._checkInputs.call(this);
  37555. };
  37556. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  37557. if (this.rotationQuaternion) {
  37558. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  37559. }
  37560. else {
  37561. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  37562. }
  37563. //update the up vector!
  37564. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  37565. };
  37566. TargetCamera.prototype._getViewMatrix = function () {
  37567. if (!this.lockedTarget) {
  37568. // Compute
  37569. this._updateCameraRotationMatrix();
  37570. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  37571. // Computing target and final matrix
  37572. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  37573. }
  37574. else {
  37575. var targetPosition = this._getLockedTargetPosition();
  37576. if (targetPosition) {
  37577. this._currentTarget.copyFrom(targetPosition);
  37578. }
  37579. }
  37580. if (this.getScene().useRightHandedSystem) {
  37581. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37582. }
  37583. else {
  37584. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37585. }
  37586. return this._viewMatrix;
  37587. };
  37588. /**
  37589. * @override
  37590. * Override Camera.createRigCamera
  37591. */
  37592. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37593. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  37594. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  37595. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  37596. if (!this.rotationQuaternion) {
  37597. this.rotationQuaternion = new BABYLON.Quaternion();
  37598. }
  37599. rigCamera._cameraRigParams = {};
  37600. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  37601. }
  37602. return rigCamera;
  37603. }
  37604. return null;
  37605. };
  37606. /**
  37607. * @override
  37608. * Override Camera._updateRigCameras
  37609. */
  37610. TargetCamera.prototype._updateRigCameras = function () {
  37611. var camLeft = this._rigCameras[0];
  37612. var camRight = this._rigCameras[1];
  37613. switch (this.cameraRigMode) {
  37614. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37615. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37616. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37617. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37618. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  37619. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  37620. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  37621. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  37622. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  37623. camLeft.setTarget(this.getTarget());
  37624. camRight.setTarget(this.getTarget());
  37625. break;
  37626. case BABYLON.Camera.RIG_MODE_VR:
  37627. if (camLeft.rotationQuaternion) {
  37628. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37629. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37630. }
  37631. else {
  37632. camLeft.rotation.copyFrom(this.rotation);
  37633. camRight.rotation.copyFrom(this.rotation);
  37634. }
  37635. camLeft.position.copyFrom(this.position);
  37636. camRight.position.copyFrom(this.position);
  37637. break;
  37638. }
  37639. _super.prototype._updateRigCameras.call(this);
  37640. };
  37641. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  37642. if (!this._rigCamTransformMatrix) {
  37643. this._rigCamTransformMatrix = new BABYLON.Matrix();
  37644. }
  37645. var target = this.getTarget();
  37646. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  37647. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  37648. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  37649. };
  37650. TargetCamera.prototype.getClassName = function () {
  37651. return "TargetCamera";
  37652. };
  37653. __decorate([
  37654. BABYLON.serializeAsVector3()
  37655. ], TargetCamera.prototype, "rotation", void 0);
  37656. __decorate([
  37657. BABYLON.serialize()
  37658. ], TargetCamera.prototype, "speed", void 0);
  37659. __decorate([
  37660. BABYLON.serializeAsMeshReference("lockedTargetId")
  37661. ], TargetCamera.prototype, "lockedTarget", void 0);
  37662. return TargetCamera;
  37663. }(BABYLON.Camera));
  37664. BABYLON.TargetCamera = TargetCamera;
  37665. })(BABYLON || (BABYLON = {}));
  37666. //# sourceMappingURL=babylon.targetCamera.js.map
  37667. var BABYLON;
  37668. (function (BABYLON) {
  37669. var FreeCamera = /** @class */ (function (_super) {
  37670. __extends(FreeCamera, _super);
  37671. function FreeCamera(name, position, scene) {
  37672. var _this = _super.call(this, name, position, scene) || this;
  37673. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  37674. _this.checkCollisions = false;
  37675. _this.applyGravity = false;
  37676. _this._needMoveForGravity = false;
  37677. _this._oldPosition = BABYLON.Vector3.Zero();
  37678. _this._diffPosition = BABYLON.Vector3.Zero();
  37679. _this._newPosition = BABYLON.Vector3.Zero();
  37680. // Collisions
  37681. _this._collisionMask = -1;
  37682. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37683. if (collidedMesh === void 0) { collidedMesh = null; }
  37684. //TODO move this to the collision coordinator!
  37685. if (_this.getScene().workerCollisions)
  37686. newPosition.multiplyInPlace(_this._collider.radius);
  37687. var updatePosition = function (newPos) {
  37688. _this._newPosition.copyFrom(newPos);
  37689. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  37690. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  37691. _this.position.addInPlace(_this._diffPosition);
  37692. if (_this.onCollide && collidedMesh) {
  37693. _this.onCollide(collidedMesh);
  37694. }
  37695. }
  37696. };
  37697. updatePosition(newPosition);
  37698. };
  37699. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  37700. _this.inputs.addKeyboard().addMouse();
  37701. return _this;
  37702. }
  37703. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  37704. //-- begin properties for backward compatibility for inputs
  37705. get: function () {
  37706. var mouse = this.inputs.attached["mouse"];
  37707. if (mouse)
  37708. return mouse.angularSensibility;
  37709. return 0;
  37710. },
  37711. set: function (value) {
  37712. var mouse = this.inputs.attached["mouse"];
  37713. if (mouse)
  37714. mouse.angularSensibility = value;
  37715. },
  37716. enumerable: true,
  37717. configurable: true
  37718. });
  37719. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37720. get: function () {
  37721. var keyboard = this.inputs.attached["keyboard"];
  37722. if (keyboard)
  37723. return keyboard.keysUp;
  37724. return [];
  37725. },
  37726. set: function (value) {
  37727. var keyboard = this.inputs.attached["keyboard"];
  37728. if (keyboard)
  37729. keyboard.keysUp = value;
  37730. },
  37731. enumerable: true,
  37732. configurable: true
  37733. });
  37734. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37735. get: function () {
  37736. var keyboard = this.inputs.attached["keyboard"];
  37737. if (keyboard)
  37738. return keyboard.keysDown;
  37739. return [];
  37740. },
  37741. set: function (value) {
  37742. var keyboard = this.inputs.attached["keyboard"];
  37743. if (keyboard)
  37744. keyboard.keysDown = value;
  37745. },
  37746. enumerable: true,
  37747. configurable: true
  37748. });
  37749. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37750. get: function () {
  37751. var keyboard = this.inputs.attached["keyboard"];
  37752. if (keyboard)
  37753. return keyboard.keysLeft;
  37754. return [];
  37755. },
  37756. set: function (value) {
  37757. var keyboard = this.inputs.attached["keyboard"];
  37758. if (keyboard)
  37759. keyboard.keysLeft = value;
  37760. },
  37761. enumerable: true,
  37762. configurable: true
  37763. });
  37764. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37765. get: function () {
  37766. var keyboard = this.inputs.attached["keyboard"];
  37767. if (keyboard)
  37768. return keyboard.keysRight;
  37769. return [];
  37770. },
  37771. set: function (value) {
  37772. var keyboard = this.inputs.attached["keyboard"];
  37773. if (keyboard)
  37774. keyboard.keysRight = value;
  37775. },
  37776. enumerable: true,
  37777. configurable: true
  37778. });
  37779. // Controls
  37780. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37781. this.inputs.attachElement(element, noPreventDefault);
  37782. };
  37783. FreeCamera.prototype.detachControl = function (element) {
  37784. this.inputs.detachElement(element);
  37785. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37786. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37787. };
  37788. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37789. get: function () {
  37790. return this._collisionMask;
  37791. },
  37792. set: function (mask) {
  37793. this._collisionMask = !isNaN(mask) ? mask : -1;
  37794. },
  37795. enumerable: true,
  37796. configurable: true
  37797. });
  37798. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37799. var globalPosition;
  37800. if (this.parent) {
  37801. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37802. }
  37803. else {
  37804. globalPosition = this.position;
  37805. }
  37806. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37807. if (!this._collider) {
  37808. this._collider = new BABYLON.Collider();
  37809. }
  37810. this._collider.radius = this.ellipsoid;
  37811. this._collider.collisionMask = this._collisionMask;
  37812. //no need for clone, as long as gravity is not on.
  37813. var actualDisplacement = displacement;
  37814. //add gravity to the direction to prevent the dual-collision checking
  37815. if (this.applyGravity) {
  37816. //this prevents mending with cameraDirection, a global variable of the free camera class.
  37817. actualDisplacement = displacement.add(this.getScene().gravity);
  37818. }
  37819. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37820. };
  37821. FreeCamera.prototype._checkInputs = function () {
  37822. if (!this._localDirection) {
  37823. this._localDirection = BABYLON.Vector3.Zero();
  37824. this._transformedDirection = BABYLON.Vector3.Zero();
  37825. }
  37826. this.inputs.checkInputs();
  37827. _super.prototype._checkInputs.call(this);
  37828. };
  37829. FreeCamera.prototype._decideIfNeedsToMove = function () {
  37830. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37831. };
  37832. FreeCamera.prototype._updatePosition = function () {
  37833. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  37834. this._collideWithWorld(this.cameraDirection);
  37835. }
  37836. else {
  37837. _super.prototype._updatePosition.call(this);
  37838. }
  37839. };
  37840. FreeCamera.prototype.dispose = function () {
  37841. this.inputs.clear();
  37842. _super.prototype.dispose.call(this);
  37843. };
  37844. FreeCamera.prototype.getClassName = function () {
  37845. return "FreeCamera";
  37846. };
  37847. __decorate([
  37848. BABYLON.serializeAsVector3()
  37849. ], FreeCamera.prototype, "ellipsoid", void 0);
  37850. __decorate([
  37851. BABYLON.serialize()
  37852. ], FreeCamera.prototype, "checkCollisions", void 0);
  37853. __decorate([
  37854. BABYLON.serialize()
  37855. ], FreeCamera.prototype, "applyGravity", void 0);
  37856. return FreeCamera;
  37857. }(BABYLON.TargetCamera));
  37858. BABYLON.FreeCamera = FreeCamera;
  37859. })(BABYLON || (BABYLON = {}));
  37860. //# sourceMappingURL=babylon.freeCamera.js.map
  37861. var BABYLON;
  37862. (function (BABYLON) {
  37863. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  37864. function ArcRotateCameraKeyboardMoveInput() {
  37865. this._keys = new Array();
  37866. this.keysUp = [38];
  37867. this.keysDown = [40];
  37868. this.keysLeft = [37];
  37869. this.keysRight = [39];
  37870. this.keysReset = [220];
  37871. this.panningSensibility = 50.0;
  37872. this.zoomingSensibility = 25.0;
  37873. this.useAltToZoom = true;
  37874. }
  37875. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37876. var _this = this;
  37877. if (this._onCanvasBlurObserver) {
  37878. return;
  37879. }
  37880. this._scene = this.camera.getScene();
  37881. this._engine = this._scene.getEngine();
  37882. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37883. _this._keys = [];
  37884. });
  37885. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37886. var evt = info.event;
  37887. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37888. _this._ctrlPressed = evt.ctrlKey;
  37889. _this._altPressed = evt.altKey;
  37890. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37891. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37892. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37893. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37894. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37895. var index = _this._keys.indexOf(evt.keyCode);
  37896. if (index === -1) {
  37897. _this._keys.push(evt.keyCode);
  37898. }
  37899. if (evt.preventDefault) {
  37900. if (!noPreventDefault) {
  37901. evt.preventDefault();
  37902. }
  37903. }
  37904. }
  37905. }
  37906. else {
  37907. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37908. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37909. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37910. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37911. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37912. var index = _this._keys.indexOf(evt.keyCode);
  37913. if (index >= 0) {
  37914. _this._keys.splice(index, 1);
  37915. }
  37916. if (evt.preventDefault) {
  37917. if (!noPreventDefault) {
  37918. evt.preventDefault();
  37919. }
  37920. }
  37921. }
  37922. }
  37923. });
  37924. };
  37925. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37926. if (this._scene) {
  37927. if (this._onKeyboardObserver) {
  37928. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37929. }
  37930. if (this._onCanvasBlurObserver) {
  37931. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37932. }
  37933. this._onKeyboardObserver = null;
  37934. this._onCanvasBlurObserver = null;
  37935. }
  37936. this._keys = [];
  37937. };
  37938. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37939. if (this._onKeyboardObserver) {
  37940. var camera = this.camera;
  37941. for (var index = 0; index < this._keys.length; index++) {
  37942. var keyCode = this._keys[index];
  37943. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37944. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37945. camera.inertialPanningX -= 1 / this.panningSensibility;
  37946. }
  37947. else {
  37948. camera.inertialAlphaOffset -= 0.01;
  37949. }
  37950. }
  37951. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37952. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37953. camera.inertialPanningY += 1 / this.panningSensibility;
  37954. }
  37955. else if (this._altPressed && this.useAltToZoom) {
  37956. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  37957. }
  37958. else {
  37959. camera.inertialBetaOffset -= 0.01;
  37960. }
  37961. }
  37962. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37963. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37964. camera.inertialPanningX += 1 / this.panningSensibility;
  37965. }
  37966. else {
  37967. camera.inertialAlphaOffset += 0.01;
  37968. }
  37969. }
  37970. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37971. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37972. camera.inertialPanningY -= 1 / this.panningSensibility;
  37973. }
  37974. else if (this._altPressed && this.useAltToZoom) {
  37975. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  37976. }
  37977. else {
  37978. camera.inertialBetaOffset += 0.01;
  37979. }
  37980. }
  37981. else if (this.keysReset.indexOf(keyCode) !== -1) {
  37982. camera.restoreState();
  37983. }
  37984. }
  37985. }
  37986. };
  37987. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  37988. return "ArcRotateCameraKeyboardMoveInput";
  37989. };
  37990. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37991. return "keyboard";
  37992. };
  37993. __decorate([
  37994. BABYLON.serialize()
  37995. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37996. __decorate([
  37997. BABYLON.serialize()
  37998. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37999. __decorate([
  38000. BABYLON.serialize()
  38001. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38002. __decorate([
  38003. BABYLON.serialize()
  38004. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38005. __decorate([
  38006. BABYLON.serialize()
  38007. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38008. __decorate([
  38009. BABYLON.serialize()
  38010. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38011. __decorate([
  38012. BABYLON.serialize()
  38013. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38014. __decorate([
  38015. BABYLON.serialize()
  38016. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38017. return ArcRotateCameraKeyboardMoveInput;
  38018. }());
  38019. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38020. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38021. })(BABYLON || (BABYLON = {}));
  38022. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38023. var BABYLON;
  38024. (function (BABYLON) {
  38025. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38026. function ArcRotateCameraMouseWheelInput() {
  38027. this.wheelPrecision = 3.0;
  38028. /**
  38029. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38030. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38031. */
  38032. this.wheelDeltaPercentage = 0;
  38033. }
  38034. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38035. var _this = this;
  38036. this._wheel = function (p, s) {
  38037. //sanity check - this should be a PointerWheel event.
  38038. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38039. return;
  38040. var event = p.event;
  38041. var delta = 0;
  38042. if (event.wheelDelta) {
  38043. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38044. }
  38045. else if (event.detail) {
  38046. delta = -event.detail / _this.wheelPrecision;
  38047. }
  38048. if (delta)
  38049. _this.camera.inertialRadiusOffset += delta;
  38050. if (event.preventDefault) {
  38051. if (!noPreventDefault) {
  38052. event.preventDefault();
  38053. }
  38054. }
  38055. };
  38056. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38057. };
  38058. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38059. if (this._observer && element) {
  38060. this.camera.getScene().onPointerObservable.remove(this._observer);
  38061. this._observer = null;
  38062. this._wheel = null;
  38063. }
  38064. };
  38065. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38066. return "ArcRotateCameraMouseWheelInput";
  38067. };
  38068. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38069. return "mousewheel";
  38070. };
  38071. __decorate([
  38072. BABYLON.serialize()
  38073. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38074. __decorate([
  38075. BABYLON.serialize()
  38076. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38077. return ArcRotateCameraMouseWheelInput;
  38078. }());
  38079. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38080. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38081. })(BABYLON || (BABYLON = {}));
  38082. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38083. var BABYLON;
  38084. (function (BABYLON) {
  38085. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38086. function ArcRotateCameraPointersInput() {
  38087. this.buttons = [0, 1, 2];
  38088. this.angularSensibilityX = 1000.0;
  38089. this.angularSensibilityY = 1000.0;
  38090. this.pinchPrecision = 12.0;
  38091. /**
  38092. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38093. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38094. */
  38095. this.pinchDeltaPercentage = 0;
  38096. this.panningSensibility = 1000.0;
  38097. this.multiTouchPanning = true;
  38098. this.multiTouchPanAndZoom = true;
  38099. this._isPanClick = false;
  38100. this.pinchInwards = true;
  38101. }
  38102. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38103. var _this = this;
  38104. var engine = this.camera.getEngine();
  38105. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38106. var pointA = null;
  38107. var pointB = null;
  38108. var previousPinchSquaredDistance = 0;
  38109. var initialDistance = 0;
  38110. var twoFingerActivityCount = 0;
  38111. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38112. this._pointerInput = function (p, s) {
  38113. var evt = p.event;
  38114. var isTouch = p.event.pointerType === "touch";
  38115. if (engine.isInVRExclusivePointerMode) {
  38116. return;
  38117. }
  38118. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38119. return;
  38120. }
  38121. var srcElement = (evt.srcElement || evt.target);
  38122. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38123. try {
  38124. srcElement.setPointerCapture(evt.pointerId);
  38125. }
  38126. catch (e) {
  38127. //Nothing to do with the error. Execution will continue.
  38128. }
  38129. // Manage panning with pan button click
  38130. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38131. // manage pointers
  38132. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38133. if (pointA === null) {
  38134. pointA = cacheSoloPointer;
  38135. }
  38136. else if (pointB === null) {
  38137. pointB = cacheSoloPointer;
  38138. }
  38139. if (!noPreventDefault) {
  38140. evt.preventDefault();
  38141. element.focus();
  38142. }
  38143. }
  38144. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38145. _this.camera.restoreState();
  38146. }
  38147. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38148. try {
  38149. srcElement.releasePointerCapture(evt.pointerId);
  38150. }
  38151. catch (e) {
  38152. //Nothing to do with the error.
  38153. }
  38154. cacheSoloPointer = null;
  38155. previousPinchSquaredDistance = 0;
  38156. previousMultiTouchPanPosition.isPaning = false;
  38157. previousMultiTouchPanPosition.isPinching = false;
  38158. twoFingerActivityCount = 0;
  38159. initialDistance = 0;
  38160. if (!isTouch) {
  38161. pointB = null; // Mouse and pen are mono pointer
  38162. }
  38163. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38164. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38165. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38166. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38167. if (engine.badOS) {
  38168. pointA = pointB = null;
  38169. }
  38170. else {
  38171. //only remove the impacted pointer in case of multitouch allowing on most
  38172. //platforms switching from rotate to zoom and pan seamlessly.
  38173. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38174. pointA = pointB;
  38175. pointB = null;
  38176. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38177. }
  38178. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38179. pointB = null;
  38180. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38181. }
  38182. else {
  38183. pointA = pointB = null;
  38184. }
  38185. }
  38186. if (!noPreventDefault) {
  38187. evt.preventDefault();
  38188. }
  38189. }
  38190. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38191. if (!noPreventDefault) {
  38192. evt.preventDefault();
  38193. }
  38194. // One button down
  38195. if (pointA && pointB === null && cacheSoloPointer) {
  38196. if (_this.panningSensibility !== 0 &&
  38197. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38198. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38199. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38200. }
  38201. else {
  38202. var offsetX = evt.clientX - cacheSoloPointer.x;
  38203. var offsetY = evt.clientY - cacheSoloPointer.y;
  38204. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38205. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38206. }
  38207. cacheSoloPointer.x = evt.clientX;
  38208. cacheSoloPointer.y = evt.clientY;
  38209. }
  38210. else if (pointA && pointB) {
  38211. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38212. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38213. ed.x = evt.clientX;
  38214. ed.y = evt.clientY;
  38215. var direction = _this.pinchInwards ? 1 : -1;
  38216. var distX = pointA.x - pointB.x;
  38217. var distY = pointA.y - pointB.y;
  38218. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38219. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38220. if (previousPinchSquaredDistance === 0) {
  38221. initialDistance = pinchDistance;
  38222. previousPinchSquaredDistance = pinchSquaredDistance;
  38223. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38224. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38225. return;
  38226. }
  38227. if (_this.multiTouchPanAndZoom) {
  38228. if (_this.pinchDeltaPercentage) {
  38229. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38230. }
  38231. else {
  38232. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38233. (_this.pinchPrecision *
  38234. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38235. direction);
  38236. }
  38237. if (_this.panningSensibility !== 0) {
  38238. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38239. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38240. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38241. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38242. previousMultiTouchPanPosition.x = pointersCenterX;
  38243. previousMultiTouchPanPosition.y = pointersCenterY;
  38244. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38245. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38246. }
  38247. }
  38248. else {
  38249. twoFingerActivityCount++;
  38250. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38251. if (_this.pinchDeltaPercentage) {
  38252. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38253. }
  38254. else {
  38255. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38256. (_this.pinchPrecision *
  38257. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38258. direction);
  38259. }
  38260. previousMultiTouchPanPosition.isPaning = false;
  38261. previousMultiTouchPanPosition.isPinching = true;
  38262. }
  38263. else {
  38264. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38265. if (!previousMultiTouchPanPosition.isPaning) {
  38266. previousMultiTouchPanPosition.isPaning = true;
  38267. previousMultiTouchPanPosition.isPinching = false;
  38268. previousMultiTouchPanPosition.x = ed.x;
  38269. previousMultiTouchPanPosition.y = ed.y;
  38270. return;
  38271. }
  38272. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38273. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38274. }
  38275. }
  38276. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38277. previousMultiTouchPanPosition.x = ed.x;
  38278. previousMultiTouchPanPosition.y = ed.y;
  38279. }
  38280. }
  38281. previousPinchSquaredDistance = pinchSquaredDistance;
  38282. }
  38283. }
  38284. };
  38285. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38286. this._onContextMenu = function (evt) {
  38287. evt.preventDefault();
  38288. };
  38289. if (!this.camera._useCtrlForPanning) {
  38290. element.addEventListener("contextmenu", this._onContextMenu, false);
  38291. }
  38292. this._onLostFocus = function () {
  38293. //this._keys = [];
  38294. pointA = pointB = null;
  38295. previousPinchSquaredDistance = 0;
  38296. previousMultiTouchPanPosition.isPaning = false;
  38297. previousMultiTouchPanPosition.isPinching = false;
  38298. twoFingerActivityCount = 0;
  38299. cacheSoloPointer = null;
  38300. initialDistance = 0;
  38301. };
  38302. this._onMouseMove = function (evt) {
  38303. if (!engine.isPointerLock) {
  38304. return;
  38305. }
  38306. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38307. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38308. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38309. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38310. if (!noPreventDefault) {
  38311. evt.preventDefault();
  38312. }
  38313. };
  38314. this._onGestureStart = function (e) {
  38315. if (window.MSGesture === undefined) {
  38316. return;
  38317. }
  38318. if (!_this._MSGestureHandler) {
  38319. _this._MSGestureHandler = new MSGesture();
  38320. _this._MSGestureHandler.target = element;
  38321. }
  38322. _this._MSGestureHandler.addPointer(e.pointerId);
  38323. };
  38324. this._onGesture = function (e) {
  38325. _this.camera.radius *= e.scale;
  38326. if (e.preventDefault) {
  38327. if (!noPreventDefault) {
  38328. e.stopPropagation();
  38329. e.preventDefault();
  38330. }
  38331. }
  38332. };
  38333. element.addEventListener("mousemove", this._onMouseMove, false);
  38334. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38335. element.addEventListener("MSGestureChange", this._onGesture, false);
  38336. BABYLON.Tools.RegisterTopRootEvents([
  38337. { name: "blur", handler: this._onLostFocus }
  38338. ]);
  38339. };
  38340. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38341. if (this._onLostFocus) {
  38342. BABYLON.Tools.UnregisterTopRootEvents([
  38343. { name: "blur", handler: this._onLostFocus }
  38344. ]);
  38345. }
  38346. if (element && this._observer) {
  38347. this.camera.getScene().onPointerObservable.remove(this._observer);
  38348. this._observer = null;
  38349. if (this._onContextMenu) {
  38350. element.removeEventListener("contextmenu", this._onContextMenu);
  38351. }
  38352. if (this._onMouseMove) {
  38353. element.removeEventListener("mousemove", this._onMouseMove);
  38354. }
  38355. if (this._onGestureStart) {
  38356. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38357. }
  38358. if (this._onGesture) {
  38359. element.removeEventListener("MSGestureChange", this._onGesture);
  38360. }
  38361. this._isPanClick = false;
  38362. this.pinchInwards = true;
  38363. this._onMouseMove = null;
  38364. this._onGestureStart = null;
  38365. this._onGesture = null;
  38366. this._MSGestureHandler = null;
  38367. this._onLostFocus = null;
  38368. this._onContextMenu = null;
  38369. }
  38370. };
  38371. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38372. return "ArcRotateCameraPointersInput";
  38373. };
  38374. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38375. return "pointers";
  38376. };
  38377. __decorate([
  38378. BABYLON.serialize()
  38379. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38380. __decorate([
  38381. BABYLON.serialize()
  38382. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38383. __decorate([
  38384. BABYLON.serialize()
  38385. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38386. __decorate([
  38387. BABYLON.serialize()
  38388. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38389. __decorate([
  38390. BABYLON.serialize()
  38391. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38392. __decorate([
  38393. BABYLON.serialize()
  38394. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38395. __decorate([
  38396. BABYLON.serialize()
  38397. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38398. __decorate([
  38399. BABYLON.serialize()
  38400. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38401. return ArcRotateCameraPointersInput;
  38402. }());
  38403. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38404. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38405. })(BABYLON || (BABYLON = {}));
  38406. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38407. var BABYLON;
  38408. (function (BABYLON) {
  38409. var ArcRotateCamera = /** @class */ (function (_super) {
  38410. __extends(ArcRotateCamera, _super);
  38411. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38412. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38413. _this.inertialAlphaOffset = 0;
  38414. _this.inertialBetaOffset = 0;
  38415. _this.inertialRadiusOffset = 0;
  38416. _this.lowerAlphaLimit = null;
  38417. _this.upperAlphaLimit = null;
  38418. _this.lowerBetaLimit = 0.01;
  38419. _this.upperBetaLimit = Math.PI;
  38420. _this.lowerRadiusLimit = null;
  38421. _this.upperRadiusLimit = null;
  38422. _this.inertialPanningX = 0;
  38423. _this.inertialPanningY = 0;
  38424. _this.pinchToPanMaxDistance = 20;
  38425. _this.panningDistanceLimit = null;
  38426. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38427. _this.panningInertia = 0.9;
  38428. //-- end properties for backward compatibility for inputs
  38429. _this.zoomOnFactor = 1;
  38430. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38431. _this.allowUpsideDown = true;
  38432. _this._viewMatrix = new BABYLON.Matrix();
  38433. // Panning
  38434. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38435. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38436. _this.checkCollisions = false;
  38437. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38438. _this._previousPosition = BABYLON.Vector3.Zero();
  38439. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38440. _this._newPosition = BABYLON.Vector3.Zero();
  38441. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38442. if (collidedMesh === void 0) { collidedMesh = null; }
  38443. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38444. newPosition.multiplyInPlace(_this._collider.radius);
  38445. }
  38446. if (!collidedMesh) {
  38447. _this._previousPosition.copyFrom(_this.position);
  38448. }
  38449. else {
  38450. _this.setPosition(newPosition);
  38451. if (_this.onCollide) {
  38452. _this.onCollide(collidedMesh);
  38453. }
  38454. }
  38455. // Recompute because of constraints
  38456. var cosa = Math.cos(_this.alpha);
  38457. var sina = Math.sin(_this.alpha);
  38458. var cosb = Math.cos(_this.beta);
  38459. var sinb = Math.sin(_this.beta);
  38460. if (sinb === 0) {
  38461. sinb = 0.0001;
  38462. }
  38463. var target = _this._getTargetPosition();
  38464. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38465. _this.position.copyFrom(_this._newPosition);
  38466. var up = _this.upVector;
  38467. if (_this.allowUpsideDown && _this.beta < 0) {
  38468. up = up.clone();
  38469. up = up.negate();
  38470. }
  38471. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38472. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38473. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38474. _this._collisionTriggered = false;
  38475. };
  38476. _this._target = BABYLON.Vector3.Zero();
  38477. if (target) {
  38478. _this.setTarget(target);
  38479. }
  38480. _this.alpha = alpha;
  38481. _this.beta = beta;
  38482. _this.radius = radius;
  38483. _this.getViewMatrix();
  38484. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  38485. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  38486. return _this;
  38487. }
  38488. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  38489. get: function () {
  38490. return this._target;
  38491. },
  38492. set: function (value) {
  38493. this.setTarget(value);
  38494. },
  38495. enumerable: true,
  38496. configurable: true
  38497. });
  38498. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  38499. //-- begin properties for backward compatibility for inputs
  38500. get: function () {
  38501. var pointers = this.inputs.attached["pointers"];
  38502. if (pointers)
  38503. return pointers.angularSensibilityX;
  38504. return 0;
  38505. },
  38506. set: function (value) {
  38507. var pointers = this.inputs.attached["pointers"];
  38508. if (pointers) {
  38509. pointers.angularSensibilityX = value;
  38510. }
  38511. },
  38512. enumerable: true,
  38513. configurable: true
  38514. });
  38515. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  38516. get: function () {
  38517. var pointers = this.inputs.attached["pointers"];
  38518. if (pointers)
  38519. return pointers.angularSensibilityY;
  38520. return 0;
  38521. },
  38522. set: function (value) {
  38523. var pointers = this.inputs.attached["pointers"];
  38524. if (pointers) {
  38525. pointers.angularSensibilityY = value;
  38526. }
  38527. },
  38528. enumerable: true,
  38529. configurable: true
  38530. });
  38531. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  38532. get: function () {
  38533. var pointers = this.inputs.attached["pointers"];
  38534. if (pointers)
  38535. return pointers.pinchPrecision;
  38536. return 0;
  38537. },
  38538. set: function (value) {
  38539. var pointers = this.inputs.attached["pointers"];
  38540. if (pointers) {
  38541. pointers.pinchPrecision = value;
  38542. }
  38543. },
  38544. enumerable: true,
  38545. configurable: true
  38546. });
  38547. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  38548. get: function () {
  38549. var pointers = this.inputs.attached["pointers"];
  38550. if (pointers)
  38551. return pointers.pinchDeltaPercentage;
  38552. return 0;
  38553. },
  38554. set: function (value) {
  38555. var pointers = this.inputs.attached["pointers"];
  38556. if (pointers) {
  38557. pointers.pinchDeltaPercentage = value;
  38558. }
  38559. },
  38560. enumerable: true,
  38561. configurable: true
  38562. });
  38563. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  38564. get: function () {
  38565. var pointers = this.inputs.attached["pointers"];
  38566. if (pointers)
  38567. return pointers.panningSensibility;
  38568. return 0;
  38569. },
  38570. set: function (value) {
  38571. var pointers = this.inputs.attached["pointers"];
  38572. if (pointers) {
  38573. pointers.panningSensibility = value;
  38574. }
  38575. },
  38576. enumerable: true,
  38577. configurable: true
  38578. });
  38579. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  38580. get: function () {
  38581. var keyboard = this.inputs.attached["keyboard"];
  38582. if (keyboard)
  38583. return keyboard.keysUp;
  38584. return [];
  38585. },
  38586. set: function (value) {
  38587. var keyboard = this.inputs.attached["keyboard"];
  38588. if (keyboard)
  38589. keyboard.keysUp = value;
  38590. },
  38591. enumerable: true,
  38592. configurable: true
  38593. });
  38594. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  38595. get: function () {
  38596. var keyboard = this.inputs.attached["keyboard"];
  38597. if (keyboard)
  38598. return keyboard.keysDown;
  38599. return [];
  38600. },
  38601. set: function (value) {
  38602. var keyboard = this.inputs.attached["keyboard"];
  38603. if (keyboard)
  38604. keyboard.keysDown = value;
  38605. },
  38606. enumerable: true,
  38607. configurable: true
  38608. });
  38609. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  38610. get: function () {
  38611. var keyboard = this.inputs.attached["keyboard"];
  38612. if (keyboard)
  38613. return keyboard.keysLeft;
  38614. return [];
  38615. },
  38616. set: function (value) {
  38617. var keyboard = this.inputs.attached["keyboard"];
  38618. if (keyboard)
  38619. keyboard.keysLeft = value;
  38620. },
  38621. enumerable: true,
  38622. configurable: true
  38623. });
  38624. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  38625. get: function () {
  38626. var keyboard = this.inputs.attached["keyboard"];
  38627. if (keyboard)
  38628. return keyboard.keysRight;
  38629. return [];
  38630. },
  38631. set: function (value) {
  38632. var keyboard = this.inputs.attached["keyboard"];
  38633. if (keyboard)
  38634. keyboard.keysRight = value;
  38635. },
  38636. enumerable: true,
  38637. configurable: true
  38638. });
  38639. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  38640. get: function () {
  38641. var mousewheel = this.inputs.attached["mousewheel"];
  38642. if (mousewheel)
  38643. return mousewheel.wheelPrecision;
  38644. return 0;
  38645. },
  38646. set: function (value) {
  38647. var mousewheel = this.inputs.attached["mousewheel"];
  38648. if (mousewheel)
  38649. mousewheel.wheelPrecision = value;
  38650. },
  38651. enumerable: true,
  38652. configurable: true
  38653. });
  38654. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  38655. get: function () {
  38656. var mousewheel = this.inputs.attached["mousewheel"];
  38657. if (mousewheel)
  38658. return mousewheel.wheelDeltaPercentage;
  38659. return 0;
  38660. },
  38661. set: function (value) {
  38662. var mousewheel = this.inputs.attached["mousewheel"];
  38663. if (mousewheel)
  38664. mousewheel.wheelDeltaPercentage = value;
  38665. },
  38666. enumerable: true,
  38667. configurable: true
  38668. });
  38669. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  38670. get: function () {
  38671. return this._bouncingBehavior;
  38672. },
  38673. enumerable: true,
  38674. configurable: true
  38675. });
  38676. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  38677. get: function () {
  38678. return this._bouncingBehavior != null;
  38679. },
  38680. set: function (value) {
  38681. if (value === this.useBouncingBehavior) {
  38682. return;
  38683. }
  38684. if (value) {
  38685. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  38686. this.addBehavior(this._bouncingBehavior);
  38687. }
  38688. else if (this._bouncingBehavior) {
  38689. this.removeBehavior(this._bouncingBehavior);
  38690. this._bouncingBehavior = null;
  38691. }
  38692. },
  38693. enumerable: true,
  38694. configurable: true
  38695. });
  38696. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  38697. get: function () {
  38698. return this._framingBehavior;
  38699. },
  38700. enumerable: true,
  38701. configurable: true
  38702. });
  38703. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  38704. get: function () {
  38705. return this._framingBehavior != null;
  38706. },
  38707. set: function (value) {
  38708. if (value === this.useFramingBehavior) {
  38709. return;
  38710. }
  38711. if (value) {
  38712. this._framingBehavior = new BABYLON.FramingBehavior();
  38713. this.addBehavior(this._framingBehavior);
  38714. }
  38715. else if (this._framingBehavior) {
  38716. this.removeBehavior(this._framingBehavior);
  38717. this._framingBehavior = null;
  38718. }
  38719. },
  38720. enumerable: true,
  38721. configurable: true
  38722. });
  38723. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38724. get: function () {
  38725. return this._autoRotationBehavior;
  38726. },
  38727. enumerable: true,
  38728. configurable: true
  38729. });
  38730. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38731. get: function () {
  38732. return this._autoRotationBehavior != null;
  38733. },
  38734. set: function (value) {
  38735. if (value === this.useAutoRotationBehavior) {
  38736. return;
  38737. }
  38738. if (value) {
  38739. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38740. this.addBehavior(this._autoRotationBehavior);
  38741. }
  38742. else if (this._autoRotationBehavior) {
  38743. this.removeBehavior(this._autoRotationBehavior);
  38744. this._autoRotationBehavior = null;
  38745. }
  38746. },
  38747. enumerable: true,
  38748. configurable: true
  38749. });
  38750. // Cache
  38751. ArcRotateCamera.prototype._initCache = function () {
  38752. _super.prototype._initCache.call(this);
  38753. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38754. this._cache.alpha = undefined;
  38755. this._cache.beta = undefined;
  38756. this._cache.radius = undefined;
  38757. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38758. };
  38759. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38760. if (!ignoreParentClass) {
  38761. _super.prototype._updateCache.call(this);
  38762. }
  38763. this._cache._target.copyFrom(this._getTargetPosition());
  38764. this._cache.alpha = this.alpha;
  38765. this._cache.beta = this.beta;
  38766. this._cache.radius = this.radius;
  38767. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38768. };
  38769. ArcRotateCamera.prototype._getTargetPosition = function () {
  38770. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38771. var pos = this._targetHost.getAbsolutePosition();
  38772. if (this._targetBoundingCenter) {
  38773. pos.addToRef(this._targetBoundingCenter, this._target);
  38774. }
  38775. else {
  38776. this._target.copyFrom(pos);
  38777. }
  38778. }
  38779. var lockedTargetPosition = this._getLockedTargetPosition();
  38780. if (lockedTargetPosition) {
  38781. return lockedTargetPosition;
  38782. }
  38783. return this._target;
  38784. };
  38785. ArcRotateCamera.prototype.storeState = function () {
  38786. this._storedAlpha = this.alpha;
  38787. this._storedBeta = this.beta;
  38788. this._storedRadius = this.radius;
  38789. this._storedTarget = this._getTargetPosition().clone();
  38790. return _super.prototype.storeState.call(this);
  38791. };
  38792. /**
  38793. * Restored camera state. You must call storeState() first
  38794. */
  38795. ArcRotateCamera.prototype._restoreStateValues = function () {
  38796. if (!_super.prototype._restoreStateValues.call(this)) {
  38797. return false;
  38798. }
  38799. this.alpha = this._storedAlpha;
  38800. this.beta = this._storedBeta;
  38801. this.radius = this._storedRadius;
  38802. this.setTarget(this._storedTarget.clone());
  38803. this.inertialAlphaOffset = 0;
  38804. this.inertialBetaOffset = 0;
  38805. this.inertialRadiusOffset = 0;
  38806. this.inertialPanningX = 0;
  38807. this.inertialPanningY = 0;
  38808. return true;
  38809. };
  38810. // Synchronized
  38811. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38812. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38813. return false;
  38814. return this._cache._target.equals(this._getTargetPosition())
  38815. && this._cache.alpha === this.alpha
  38816. && this._cache.beta === this.beta
  38817. && this._cache.radius === this.radius
  38818. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  38819. };
  38820. // Methods
  38821. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  38822. var _this = this;
  38823. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  38824. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  38825. this._useCtrlForPanning = useCtrlForPanning;
  38826. this._panningMouseButton = panningMouseButton;
  38827. this.inputs.attachElement(element, noPreventDefault);
  38828. this._reset = function () {
  38829. _this.inertialAlphaOffset = 0;
  38830. _this.inertialBetaOffset = 0;
  38831. _this.inertialRadiusOffset = 0;
  38832. _this.inertialPanningX = 0;
  38833. _this.inertialPanningY = 0;
  38834. };
  38835. };
  38836. ArcRotateCamera.prototype.detachControl = function (element) {
  38837. this.inputs.detachElement(element);
  38838. if (this._reset) {
  38839. this._reset();
  38840. }
  38841. };
  38842. ArcRotateCamera.prototype._checkInputs = function () {
  38843. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  38844. if (this._collisionTriggered) {
  38845. return;
  38846. }
  38847. this.inputs.checkInputs();
  38848. // Inertia
  38849. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  38850. if (this.getScene().useRightHandedSystem) {
  38851. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38852. }
  38853. else {
  38854. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38855. }
  38856. this.beta += this.inertialBetaOffset;
  38857. this.radius -= this.inertialRadiusOffset;
  38858. this.inertialAlphaOffset *= this.inertia;
  38859. this.inertialBetaOffset *= this.inertia;
  38860. this.inertialRadiusOffset *= this.inertia;
  38861. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  38862. this.inertialAlphaOffset = 0;
  38863. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  38864. this.inertialBetaOffset = 0;
  38865. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  38866. this.inertialRadiusOffset = 0;
  38867. }
  38868. // Panning inertia
  38869. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  38870. if (!this._localDirection) {
  38871. this._localDirection = BABYLON.Vector3.Zero();
  38872. this._transformedDirection = BABYLON.Vector3.Zero();
  38873. }
  38874. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  38875. this._localDirection.multiplyInPlace(this.panningAxis);
  38876. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  38877. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  38878. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  38879. if (!this.panningAxis.y) {
  38880. this._transformedDirection.y = 0;
  38881. }
  38882. if (!this._targetHost) {
  38883. if (this.panningDistanceLimit) {
  38884. this._transformedDirection.addInPlace(this._target);
  38885. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  38886. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  38887. this._target.copyFrom(this._transformedDirection);
  38888. }
  38889. }
  38890. else {
  38891. this._target.addInPlace(this._transformedDirection);
  38892. }
  38893. }
  38894. this.inertialPanningX *= this.panningInertia;
  38895. this.inertialPanningY *= this.panningInertia;
  38896. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  38897. this.inertialPanningX = 0;
  38898. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  38899. this.inertialPanningY = 0;
  38900. }
  38901. // Limits
  38902. this._checkLimits();
  38903. _super.prototype._checkInputs.call(this);
  38904. };
  38905. ArcRotateCamera.prototype._checkLimits = function () {
  38906. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  38907. if (this.allowUpsideDown && this.beta > Math.PI) {
  38908. this.beta = this.beta - (2 * Math.PI);
  38909. }
  38910. }
  38911. else {
  38912. if (this.beta < this.lowerBetaLimit) {
  38913. this.beta = this.lowerBetaLimit;
  38914. }
  38915. }
  38916. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  38917. if (this.allowUpsideDown && this.beta < -Math.PI) {
  38918. this.beta = this.beta + (2 * Math.PI);
  38919. }
  38920. }
  38921. else {
  38922. if (this.beta > this.upperBetaLimit) {
  38923. this.beta = this.upperBetaLimit;
  38924. }
  38925. }
  38926. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  38927. this.alpha = this.lowerAlphaLimit;
  38928. }
  38929. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  38930. this.alpha = this.upperAlphaLimit;
  38931. }
  38932. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  38933. this.radius = this.lowerRadiusLimit;
  38934. }
  38935. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  38936. this.radius = this.upperRadiusLimit;
  38937. }
  38938. };
  38939. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  38940. var radiusv3 = this.position.subtract(this._getTargetPosition());
  38941. this.radius = radiusv3.length();
  38942. if (this.radius === 0) {
  38943. this.radius = 0.0001; // Just to avoid division by zero
  38944. }
  38945. // Alpha
  38946. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  38947. if (radiusv3.z < 0) {
  38948. this.alpha = 2 * Math.PI - this.alpha;
  38949. }
  38950. // Beta
  38951. this.beta = Math.acos(radiusv3.y / this.radius);
  38952. this._checkLimits();
  38953. };
  38954. ArcRotateCamera.prototype.setPosition = function (position) {
  38955. if (this.position.equals(position)) {
  38956. return;
  38957. }
  38958. this.position.copyFrom(position);
  38959. this.rebuildAnglesAndRadius();
  38960. };
  38961. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  38962. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  38963. if (allowSamePosition === void 0) { allowSamePosition = false; }
  38964. if (target.getBoundingInfo) {
  38965. if (toBoundingCenter) {
  38966. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  38967. }
  38968. else {
  38969. this._targetBoundingCenter = null;
  38970. }
  38971. this._targetHost = target;
  38972. this._target = this._getTargetPosition();
  38973. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  38974. }
  38975. else {
  38976. var newTarget = target;
  38977. var currentTarget = this._getTargetPosition();
  38978. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  38979. return;
  38980. }
  38981. this._targetHost = null;
  38982. this._target = newTarget;
  38983. this._targetBoundingCenter = null;
  38984. this.onMeshTargetChangedObservable.notifyObservers(null);
  38985. }
  38986. this.rebuildAnglesAndRadius();
  38987. };
  38988. ArcRotateCamera.prototype._getViewMatrix = function () {
  38989. // Compute
  38990. var cosa = Math.cos(this.alpha);
  38991. var sina = Math.sin(this.alpha);
  38992. var cosb = Math.cos(this.beta);
  38993. var sinb = Math.sin(this.beta);
  38994. if (sinb === 0) {
  38995. sinb = 0.0001;
  38996. }
  38997. var target = this._getTargetPosition();
  38998. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  38999. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  39000. if (!this._collider) {
  39001. this._collider = new BABYLON.Collider();
  39002. }
  39003. this._collider.radius = this.collisionRadius;
  39004. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39005. this._collisionTriggered = true;
  39006. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39007. }
  39008. else {
  39009. this.position.copyFrom(this._newPosition);
  39010. var up = this.upVector;
  39011. if (this.allowUpsideDown && sinb < 0) {
  39012. up = up.clone();
  39013. up = up.negate();
  39014. }
  39015. if (this.getScene().useRightHandedSystem) {
  39016. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39017. }
  39018. else {
  39019. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39020. }
  39021. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39022. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39023. }
  39024. this._currentTarget = target;
  39025. return this._viewMatrix;
  39026. };
  39027. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39028. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39029. meshes = meshes || this.getScene().meshes;
  39030. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39031. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39032. this.radius = distance * this.zoomOnFactor;
  39033. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39034. };
  39035. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39036. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39037. var meshesOrMinMaxVector;
  39038. var distance;
  39039. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39040. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39041. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39042. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39043. }
  39044. else {
  39045. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39046. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39047. distance = minMaxVectorAndDistance.distance;
  39048. }
  39049. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39050. if (!doNotUpdateMaxZ) {
  39051. this.maxZ = distance * 2;
  39052. }
  39053. };
  39054. /**
  39055. * @override
  39056. * Override Camera.createRigCamera
  39057. */
  39058. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39059. var alphaShift = 0;
  39060. switch (this.cameraRigMode) {
  39061. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39062. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39063. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39064. case BABYLON.Camera.RIG_MODE_VR:
  39065. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39066. break;
  39067. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39068. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39069. break;
  39070. }
  39071. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39072. rigCam._cameraRigParams = {};
  39073. return rigCam;
  39074. };
  39075. /**
  39076. * @override
  39077. * Override Camera._updateRigCameras
  39078. */
  39079. ArcRotateCamera.prototype._updateRigCameras = function () {
  39080. var camLeft = this._rigCameras[0];
  39081. var camRight = this._rigCameras[1];
  39082. camLeft.beta = camRight.beta = this.beta;
  39083. camLeft.radius = camRight.radius = this.radius;
  39084. switch (this.cameraRigMode) {
  39085. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39086. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39087. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39088. case BABYLON.Camera.RIG_MODE_VR:
  39089. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39090. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39091. break;
  39092. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39093. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39094. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39095. break;
  39096. }
  39097. _super.prototype._updateRigCameras.call(this);
  39098. };
  39099. ArcRotateCamera.prototype.dispose = function () {
  39100. this.inputs.clear();
  39101. _super.prototype.dispose.call(this);
  39102. };
  39103. ArcRotateCamera.prototype.getClassName = function () {
  39104. return "ArcRotateCamera";
  39105. };
  39106. __decorate([
  39107. BABYLON.serialize()
  39108. ], ArcRotateCamera.prototype, "alpha", void 0);
  39109. __decorate([
  39110. BABYLON.serialize()
  39111. ], ArcRotateCamera.prototype, "beta", void 0);
  39112. __decorate([
  39113. BABYLON.serialize()
  39114. ], ArcRotateCamera.prototype, "radius", void 0);
  39115. __decorate([
  39116. BABYLON.serializeAsVector3("target")
  39117. ], ArcRotateCamera.prototype, "_target", void 0);
  39118. __decorate([
  39119. BABYLON.serialize()
  39120. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39121. __decorate([
  39122. BABYLON.serialize()
  39123. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39124. __decorate([
  39125. BABYLON.serialize()
  39126. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39127. __decorate([
  39128. BABYLON.serialize()
  39129. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39130. __decorate([
  39131. BABYLON.serialize()
  39132. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39133. __decorate([
  39134. BABYLON.serialize()
  39135. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39136. __decorate([
  39137. BABYLON.serialize()
  39138. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39139. __decorate([
  39140. BABYLON.serialize()
  39141. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39142. __decorate([
  39143. BABYLON.serialize()
  39144. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39145. __decorate([
  39146. BABYLON.serialize()
  39147. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39148. __decorate([
  39149. BABYLON.serialize()
  39150. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39151. __decorate([
  39152. BABYLON.serialize()
  39153. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39154. __decorate([
  39155. BABYLON.serialize()
  39156. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39157. __decorate([
  39158. BABYLON.serializeAsVector3()
  39159. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39160. __decorate([
  39161. BABYLON.serialize()
  39162. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39163. __decorate([
  39164. BABYLON.serialize()
  39165. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39166. __decorate([
  39167. BABYLON.serialize()
  39168. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39169. return ArcRotateCamera;
  39170. }(BABYLON.TargetCamera));
  39171. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39172. })(BABYLON || (BABYLON = {}));
  39173. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39174. var BABYLON;
  39175. (function (BABYLON) {
  39176. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39177. __extends(ArcRotateCameraInputsManager, _super);
  39178. function ArcRotateCameraInputsManager(camera) {
  39179. return _super.call(this, camera) || this;
  39180. }
  39181. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39182. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39183. return this;
  39184. };
  39185. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39186. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39187. return this;
  39188. };
  39189. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39190. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39191. return this;
  39192. };
  39193. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39194. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39195. return this;
  39196. };
  39197. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39198. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39199. return this;
  39200. };
  39201. return ArcRotateCameraInputsManager;
  39202. }(BABYLON.CameraInputsManager));
  39203. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39204. })(BABYLON || (BABYLON = {}));
  39205. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39206. var BABYLON;
  39207. (function (BABYLON) {
  39208. var HemisphericLight = /** @class */ (function (_super) {
  39209. __extends(HemisphericLight, _super);
  39210. /**
  39211. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39212. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39213. * The HemisphericLight can't cast shadows.
  39214. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39215. */
  39216. function HemisphericLight(name, direction, scene) {
  39217. var _this = _super.call(this, name, scene) || this;
  39218. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39219. _this.direction = direction || BABYLON.Vector3.Up();
  39220. return _this;
  39221. }
  39222. HemisphericLight.prototype._buildUniformLayout = function () {
  39223. this._uniformBuffer.addUniform("vLightData", 4);
  39224. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39225. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39226. this._uniformBuffer.addUniform("vLightGround", 3);
  39227. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39228. this._uniformBuffer.addUniform("depthValues", 2);
  39229. this._uniformBuffer.create();
  39230. };
  39231. /**
  39232. * Returns the string "HemisphericLight".
  39233. */
  39234. HemisphericLight.prototype.getClassName = function () {
  39235. return "HemisphericLight";
  39236. };
  39237. /**
  39238. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39239. * Returns the updated direction.
  39240. */
  39241. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39242. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39243. return this.direction;
  39244. };
  39245. HemisphericLight.prototype.getShadowGenerator = function () {
  39246. return null;
  39247. };
  39248. /**
  39249. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39250. * Returns the HemisphericLight.
  39251. */
  39252. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39253. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39254. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39255. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39256. return this;
  39257. };
  39258. HemisphericLight.prototype._getWorldMatrix = function () {
  39259. if (!this._worldMatrix) {
  39260. this._worldMatrix = BABYLON.Matrix.Identity();
  39261. }
  39262. return this._worldMatrix;
  39263. };
  39264. /**
  39265. * Returns the integer 3.
  39266. */
  39267. HemisphericLight.prototype.getTypeID = function () {
  39268. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39269. };
  39270. __decorate([
  39271. BABYLON.serializeAsColor3()
  39272. ], HemisphericLight.prototype, "groundColor", void 0);
  39273. __decorate([
  39274. BABYLON.serializeAsVector3()
  39275. ], HemisphericLight.prototype, "direction", void 0);
  39276. return HemisphericLight;
  39277. }(BABYLON.Light));
  39278. BABYLON.HemisphericLight = HemisphericLight;
  39279. })(BABYLON || (BABYLON = {}));
  39280. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39281. var BABYLON;
  39282. (function (BABYLON) {
  39283. var ShadowLight = /** @class */ (function (_super) {
  39284. __extends(ShadowLight, _super);
  39285. function ShadowLight() {
  39286. var _this = _super !== null && _super.apply(this, arguments) || this;
  39287. _this._needProjectionMatrixCompute = true;
  39288. return _this;
  39289. }
  39290. Object.defineProperty(ShadowLight.prototype, "direction", {
  39291. get: function () {
  39292. return this._direction;
  39293. },
  39294. set: function (value) {
  39295. this._direction = value;
  39296. },
  39297. enumerable: true,
  39298. configurable: true
  39299. });
  39300. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39301. get: function () {
  39302. return this._shadowMinZ;
  39303. },
  39304. set: function (value) {
  39305. this._shadowMinZ = value;
  39306. this.forceProjectionMatrixCompute();
  39307. },
  39308. enumerable: true,
  39309. configurable: true
  39310. });
  39311. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39312. get: function () {
  39313. return this._shadowMaxZ;
  39314. },
  39315. set: function (value) {
  39316. this._shadowMaxZ = value;
  39317. this.forceProjectionMatrixCompute();
  39318. },
  39319. enumerable: true,
  39320. configurable: true
  39321. });
  39322. /**
  39323. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39324. */
  39325. ShadowLight.prototype.computeTransformedInformation = function () {
  39326. if (this.parent && this.parent.getWorldMatrix) {
  39327. if (!this.transformedPosition) {
  39328. this.transformedPosition = BABYLON.Vector3.Zero();
  39329. }
  39330. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39331. // In case the direction is present.
  39332. if (this.direction) {
  39333. if (!this.transformedDirection) {
  39334. this.transformedDirection = BABYLON.Vector3.Zero();
  39335. }
  39336. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39337. }
  39338. return true;
  39339. }
  39340. return false;
  39341. };
  39342. /**
  39343. * Return the depth scale used for the shadow map.
  39344. */
  39345. ShadowLight.prototype.getDepthScale = function () {
  39346. return 50.0;
  39347. };
  39348. /**
  39349. * Returns the light direction (Vector3) for any passed face index.
  39350. */
  39351. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39352. return this.transformedDirection ? this.transformedDirection : this.direction;
  39353. };
  39354. /**
  39355. * Returns the DirectionalLight absolute position in the World.
  39356. */
  39357. ShadowLight.prototype.getAbsolutePosition = function () {
  39358. return this.transformedPosition ? this.transformedPosition : this.position;
  39359. };
  39360. /**
  39361. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39362. * Returns the updated DirectionalLight direction (Vector3).
  39363. */
  39364. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39365. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39366. return this.direction;
  39367. };
  39368. /**
  39369. * Returns the light rotation (Vector3).
  39370. */
  39371. ShadowLight.prototype.getRotation = function () {
  39372. this.direction.normalize();
  39373. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39374. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39375. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39376. };
  39377. /**
  39378. * Boolean : false by default.
  39379. */
  39380. ShadowLight.prototype.needCube = function () {
  39381. return false;
  39382. };
  39383. /**
  39384. * Specifies wether or not the projection matrix should be recomputed this frame.
  39385. */
  39386. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39387. return this._needProjectionMatrixCompute;
  39388. };
  39389. /**
  39390. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39391. */
  39392. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39393. this._needProjectionMatrixCompute = true;
  39394. };
  39395. /**
  39396. * Get the world matrix of the sahdow lights.
  39397. */
  39398. ShadowLight.prototype._getWorldMatrix = function () {
  39399. if (!this._worldMatrix) {
  39400. this._worldMatrix = BABYLON.Matrix.Identity();
  39401. }
  39402. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39403. return this._worldMatrix;
  39404. };
  39405. /**
  39406. * Gets the minZ used for shadow according to both the scene and the light.
  39407. * @param activeCamera
  39408. */
  39409. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39410. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39411. };
  39412. /**
  39413. * Gets the maxZ used for shadow according to both the scene and the light.
  39414. * @param activeCamera
  39415. */
  39416. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39417. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39418. };
  39419. /**
  39420. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39421. * Returns the light.
  39422. */
  39423. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39424. if (this.customProjectionMatrixBuilder) {
  39425. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39426. }
  39427. else {
  39428. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39429. }
  39430. return this;
  39431. };
  39432. __decorate([
  39433. BABYLON.serializeAsVector3()
  39434. ], ShadowLight.prototype, "position", void 0);
  39435. __decorate([
  39436. BABYLON.serializeAsVector3()
  39437. ], ShadowLight.prototype, "direction", null);
  39438. __decorate([
  39439. BABYLON.serialize()
  39440. ], ShadowLight.prototype, "shadowMinZ", null);
  39441. __decorate([
  39442. BABYLON.serialize()
  39443. ], ShadowLight.prototype, "shadowMaxZ", null);
  39444. return ShadowLight;
  39445. }(BABYLON.Light));
  39446. BABYLON.ShadowLight = ShadowLight;
  39447. })(BABYLON || (BABYLON = {}));
  39448. //# sourceMappingURL=babylon.shadowLight.js.map
  39449. var BABYLON;
  39450. (function (BABYLON) {
  39451. var PointLight = /** @class */ (function (_super) {
  39452. __extends(PointLight, _super);
  39453. /**
  39454. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39455. * A PointLight emits the light in every direction.
  39456. * It can cast shadows.
  39457. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39458. * ```javascript
  39459. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39460. * ```
  39461. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39462. */
  39463. function PointLight(name, position, scene) {
  39464. var _this = _super.call(this, name, scene) || this;
  39465. _this._shadowAngle = Math.PI / 2;
  39466. _this.position = position;
  39467. return _this;
  39468. }
  39469. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39470. /**
  39471. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39472. * This specifies what angle the shadow will use to be created.
  39473. *
  39474. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39475. */
  39476. get: function () {
  39477. return this._shadowAngle;
  39478. },
  39479. /**
  39480. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39481. * This specifies what angle the shadow will use to be created.
  39482. *
  39483. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39484. */
  39485. set: function (value) {
  39486. this._shadowAngle = value;
  39487. this.forceProjectionMatrixCompute();
  39488. },
  39489. enumerable: true,
  39490. configurable: true
  39491. });
  39492. Object.defineProperty(PointLight.prototype, "direction", {
  39493. get: function () {
  39494. return this._direction;
  39495. },
  39496. /**
  39497. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39498. */
  39499. set: function (value) {
  39500. var previousNeedCube = this.needCube();
  39501. this._direction = value;
  39502. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  39503. this._shadowGenerator.recreateShadowMap();
  39504. }
  39505. },
  39506. enumerable: true,
  39507. configurable: true
  39508. });
  39509. /**
  39510. * Returns the string "PointLight"
  39511. */
  39512. PointLight.prototype.getClassName = function () {
  39513. return "PointLight";
  39514. };
  39515. /**
  39516. * Returns the integer 0.
  39517. */
  39518. PointLight.prototype.getTypeID = function () {
  39519. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  39520. };
  39521. /**
  39522. * Specifies wether or not the shadowmap should be a cube texture.
  39523. */
  39524. PointLight.prototype.needCube = function () {
  39525. return !this.direction;
  39526. };
  39527. /**
  39528. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  39529. */
  39530. PointLight.prototype.getShadowDirection = function (faceIndex) {
  39531. if (this.direction) {
  39532. return _super.prototype.getShadowDirection.call(this, faceIndex);
  39533. }
  39534. else {
  39535. switch (faceIndex) {
  39536. case 0:
  39537. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  39538. case 1:
  39539. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  39540. case 2:
  39541. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  39542. case 3:
  39543. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  39544. case 4:
  39545. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  39546. case 5:
  39547. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  39548. }
  39549. }
  39550. return BABYLON.Vector3.Zero();
  39551. };
  39552. /**
  39553. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  39554. * - fov = PI / 2
  39555. * - aspect ratio : 1.0
  39556. * - z-near and far equal to the active camera minZ and maxZ.
  39557. * Returns the PointLight.
  39558. */
  39559. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39560. var activeCamera = this.getScene().activeCamera;
  39561. if (!activeCamera) {
  39562. return;
  39563. }
  39564. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39565. };
  39566. PointLight.prototype._buildUniformLayout = function () {
  39567. this._uniformBuffer.addUniform("vLightData", 4);
  39568. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39569. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39570. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39571. this._uniformBuffer.addUniform("depthValues", 2);
  39572. this._uniformBuffer.create();
  39573. };
  39574. /**
  39575. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  39576. * Returns the PointLight.
  39577. */
  39578. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  39579. if (this.computeTransformedInformation()) {
  39580. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  39581. return this;
  39582. }
  39583. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  39584. return this;
  39585. };
  39586. __decorate([
  39587. BABYLON.serialize()
  39588. ], PointLight.prototype, "shadowAngle", null);
  39589. return PointLight;
  39590. }(BABYLON.ShadowLight));
  39591. BABYLON.PointLight = PointLight;
  39592. })(BABYLON || (BABYLON = {}));
  39593. //# sourceMappingURL=babylon.pointLight.js.map
  39594. var BABYLON;
  39595. (function (BABYLON) {
  39596. var DirectionalLight = /** @class */ (function (_super) {
  39597. __extends(DirectionalLight, _super);
  39598. /**
  39599. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  39600. * The directional light is emitted from everywhere in the given direction.
  39601. * It can cast shawdows.
  39602. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39603. */
  39604. function DirectionalLight(name, direction, scene) {
  39605. var _this = _super.call(this, name, scene) || this;
  39606. _this._shadowFrustumSize = 0;
  39607. _this._shadowOrthoScale = 0.5;
  39608. _this.autoUpdateExtends = true;
  39609. // Cache
  39610. _this._orthoLeft = Number.MAX_VALUE;
  39611. _this._orthoRight = Number.MIN_VALUE;
  39612. _this._orthoTop = Number.MIN_VALUE;
  39613. _this._orthoBottom = Number.MAX_VALUE;
  39614. _this.position = direction.scale(-1.0);
  39615. _this.direction = direction;
  39616. return _this;
  39617. }
  39618. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  39619. /**
  39620. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  39621. */
  39622. get: function () {
  39623. return this._shadowFrustumSize;
  39624. },
  39625. /**
  39626. * Specifies a fix frustum size for the shadow generation.
  39627. */
  39628. set: function (value) {
  39629. this._shadowFrustumSize = value;
  39630. this.forceProjectionMatrixCompute();
  39631. },
  39632. enumerable: true,
  39633. configurable: true
  39634. });
  39635. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  39636. get: function () {
  39637. return this._shadowOrthoScale;
  39638. },
  39639. set: function (value) {
  39640. this._shadowOrthoScale = value;
  39641. this.forceProjectionMatrixCompute();
  39642. },
  39643. enumerable: true,
  39644. configurable: true
  39645. });
  39646. /**
  39647. * Returns the string "DirectionalLight".
  39648. */
  39649. DirectionalLight.prototype.getClassName = function () {
  39650. return "DirectionalLight";
  39651. };
  39652. /**
  39653. * Returns the integer 1.
  39654. */
  39655. DirectionalLight.prototype.getTypeID = function () {
  39656. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  39657. };
  39658. /**
  39659. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  39660. * Returns the DirectionalLight Shadow projection matrix.
  39661. */
  39662. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39663. if (this.shadowFrustumSize > 0) {
  39664. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  39665. }
  39666. else {
  39667. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39668. }
  39669. };
  39670. /**
  39671. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  39672. * Returns the DirectionalLight Shadow projection matrix.
  39673. */
  39674. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  39675. var activeCamera = this.getScene().activeCamera;
  39676. if (!activeCamera) {
  39677. return;
  39678. }
  39679. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39680. };
  39681. /**
  39682. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  39683. * Returns the DirectionalLight Shadow projection matrix.
  39684. */
  39685. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39686. var activeCamera = this.getScene().activeCamera;
  39687. if (!activeCamera) {
  39688. return;
  39689. }
  39690. // Check extends
  39691. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  39692. var tempVector3 = BABYLON.Vector3.Zero();
  39693. this._orthoLeft = Number.MAX_VALUE;
  39694. this._orthoRight = Number.MIN_VALUE;
  39695. this._orthoTop = Number.MIN_VALUE;
  39696. this._orthoBottom = Number.MAX_VALUE;
  39697. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  39698. var mesh = renderList[meshIndex];
  39699. if (!mesh) {
  39700. continue;
  39701. }
  39702. var boundingInfo = mesh.getBoundingInfo();
  39703. if (!boundingInfo) {
  39704. continue;
  39705. }
  39706. var boundingBox = boundingInfo.boundingBox;
  39707. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  39708. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  39709. if (tempVector3.x < this._orthoLeft)
  39710. this._orthoLeft = tempVector3.x;
  39711. if (tempVector3.y < this._orthoBottom)
  39712. this._orthoBottom = tempVector3.y;
  39713. if (tempVector3.x > this._orthoRight)
  39714. this._orthoRight = tempVector3.x;
  39715. if (tempVector3.y > this._orthoTop)
  39716. this._orthoTop = tempVector3.y;
  39717. }
  39718. }
  39719. }
  39720. var xOffset = this._orthoRight - this._orthoLeft;
  39721. var yOffset = this._orthoTop - this._orthoBottom;
  39722. 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);
  39723. };
  39724. DirectionalLight.prototype._buildUniformLayout = function () {
  39725. this._uniformBuffer.addUniform("vLightData", 4);
  39726. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39727. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39728. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39729. this._uniformBuffer.addUniform("depthValues", 2);
  39730. this._uniformBuffer.create();
  39731. };
  39732. /**
  39733. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39734. * Returns the DirectionalLight.
  39735. */
  39736. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39737. if (this.computeTransformedInformation()) {
  39738. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39739. return this;
  39740. }
  39741. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39742. return this;
  39743. };
  39744. /**
  39745. * Gets the minZ used for shadow according to both the scene and the light.
  39746. *
  39747. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39748. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39749. * @param activeCamera
  39750. */
  39751. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39752. return 1;
  39753. };
  39754. /**
  39755. * Gets the maxZ used for shadow according to both the scene and the light.
  39756. *
  39757. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39758. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39759. * @param activeCamera
  39760. */
  39761. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39762. return 1;
  39763. };
  39764. __decorate([
  39765. BABYLON.serialize()
  39766. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39767. __decorate([
  39768. BABYLON.serialize()
  39769. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39770. __decorate([
  39771. BABYLON.serialize()
  39772. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39773. return DirectionalLight;
  39774. }(BABYLON.ShadowLight));
  39775. BABYLON.DirectionalLight = DirectionalLight;
  39776. })(BABYLON || (BABYLON = {}));
  39777. //# sourceMappingURL=babylon.directionalLight.js.map
  39778. var BABYLON;
  39779. (function (BABYLON) {
  39780. var SpotLight = /** @class */ (function (_super) {
  39781. __extends(SpotLight, _super);
  39782. /**
  39783. * Creates a SpotLight object in the scene with the passed parameters :
  39784. * - `position` (Vector3) is the initial SpotLight position,
  39785. * - `direction` (Vector3) is the initial SpotLight direction,
  39786. * - `angle` (float, in radians) is the spot light cone angle,
  39787. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39788. * A spot light is a simply light oriented cone.
  39789. * It can cast shadows.
  39790. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39791. */
  39792. function SpotLight(name, position, direction, angle, exponent, scene) {
  39793. var _this = _super.call(this, name, scene) || this;
  39794. _this.position = position;
  39795. _this.direction = direction;
  39796. _this.angle = angle;
  39797. _this.exponent = exponent;
  39798. return _this;
  39799. }
  39800. Object.defineProperty(SpotLight.prototype, "angle", {
  39801. get: function () {
  39802. return this._angle;
  39803. },
  39804. set: function (value) {
  39805. this._angle = value;
  39806. this.forceProjectionMatrixCompute();
  39807. },
  39808. enumerable: true,
  39809. configurable: true
  39810. });
  39811. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39812. get: function () {
  39813. return this._shadowAngleScale;
  39814. },
  39815. /**
  39816. * Allows scaling the angle of the light for shadow generation only.
  39817. */
  39818. set: function (value) {
  39819. this._shadowAngleScale = value;
  39820. this.forceProjectionMatrixCompute();
  39821. },
  39822. enumerable: true,
  39823. configurable: true
  39824. });
  39825. /**
  39826. * Returns the string "SpotLight".
  39827. */
  39828. SpotLight.prototype.getClassName = function () {
  39829. return "SpotLight";
  39830. };
  39831. /**
  39832. * Returns the integer 2.
  39833. */
  39834. SpotLight.prototype.getTypeID = function () {
  39835. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  39836. };
  39837. /**
  39838. * 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.
  39839. * Returns the SpotLight.
  39840. */
  39841. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39842. var activeCamera = this.getScene().activeCamera;
  39843. if (!activeCamera) {
  39844. return;
  39845. }
  39846. this._shadowAngleScale = this._shadowAngleScale || 1;
  39847. var angle = this._shadowAngleScale * this._angle;
  39848. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39849. };
  39850. SpotLight.prototype._buildUniformLayout = function () {
  39851. this._uniformBuffer.addUniform("vLightData", 4);
  39852. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39853. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39854. this._uniformBuffer.addUniform("vLightDirection", 3);
  39855. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39856. this._uniformBuffer.addUniform("depthValues", 2);
  39857. this._uniformBuffer.create();
  39858. };
  39859. /**
  39860. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  39861. * Return the SpotLight.
  39862. */
  39863. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  39864. var normalizeDirection;
  39865. if (this.computeTransformedInformation()) {
  39866. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  39867. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  39868. }
  39869. else {
  39870. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  39871. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39872. }
  39873. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  39874. return this;
  39875. };
  39876. __decorate([
  39877. BABYLON.serialize()
  39878. ], SpotLight.prototype, "angle", null);
  39879. __decorate([
  39880. BABYLON.serialize()
  39881. /**
  39882. * Allows scaling the angle of the light for shadow generation only.
  39883. */
  39884. ], SpotLight.prototype, "shadowAngleScale", null);
  39885. __decorate([
  39886. BABYLON.serialize()
  39887. ], SpotLight.prototype, "exponent", void 0);
  39888. return SpotLight;
  39889. }(BABYLON.ShadowLight));
  39890. BABYLON.SpotLight = SpotLight;
  39891. })(BABYLON || (BABYLON = {}));
  39892. //# sourceMappingURL=babylon.spotLight.js.map
  39893. var BABYLON;
  39894. (function (BABYLON) {
  39895. var AnimationRange = /** @class */ (function () {
  39896. function AnimationRange(name, from, to) {
  39897. this.name = name;
  39898. this.from = from;
  39899. this.to = to;
  39900. }
  39901. AnimationRange.prototype.clone = function () {
  39902. return new AnimationRange(this.name, this.from, this.to);
  39903. };
  39904. return AnimationRange;
  39905. }());
  39906. BABYLON.AnimationRange = AnimationRange;
  39907. /**
  39908. * Composed of a frame, and an action function
  39909. */
  39910. var AnimationEvent = /** @class */ (function () {
  39911. function AnimationEvent(frame, action, onlyOnce) {
  39912. this.frame = frame;
  39913. this.action = action;
  39914. this.onlyOnce = onlyOnce;
  39915. this.isDone = false;
  39916. }
  39917. return AnimationEvent;
  39918. }());
  39919. BABYLON.AnimationEvent = AnimationEvent;
  39920. var PathCursor = /** @class */ (function () {
  39921. function PathCursor(path) {
  39922. this.path = path;
  39923. this._onchange = new Array();
  39924. this.value = 0;
  39925. this.animations = new Array();
  39926. }
  39927. PathCursor.prototype.getPoint = function () {
  39928. var point = this.path.getPointAtLengthPosition(this.value);
  39929. return new BABYLON.Vector3(point.x, 0, point.y);
  39930. };
  39931. PathCursor.prototype.moveAhead = function (step) {
  39932. if (step === void 0) { step = 0.002; }
  39933. this.move(step);
  39934. return this;
  39935. };
  39936. PathCursor.prototype.moveBack = function (step) {
  39937. if (step === void 0) { step = 0.002; }
  39938. this.move(-step);
  39939. return this;
  39940. };
  39941. PathCursor.prototype.move = function (step) {
  39942. if (Math.abs(step) > 1) {
  39943. throw "step size should be less than 1.";
  39944. }
  39945. this.value += step;
  39946. this.ensureLimits();
  39947. this.raiseOnChange();
  39948. return this;
  39949. };
  39950. PathCursor.prototype.ensureLimits = function () {
  39951. while (this.value > 1) {
  39952. this.value -= 1;
  39953. }
  39954. while (this.value < 0) {
  39955. this.value += 1;
  39956. }
  39957. return this;
  39958. };
  39959. // used by animation engine
  39960. PathCursor.prototype.raiseOnChange = function () {
  39961. var _this = this;
  39962. this._onchange.forEach(function (f) { return f(_this); });
  39963. return this;
  39964. };
  39965. PathCursor.prototype.onchange = function (f) {
  39966. this._onchange.push(f);
  39967. return this;
  39968. };
  39969. return PathCursor;
  39970. }());
  39971. BABYLON.PathCursor = PathCursor;
  39972. var Animation = /** @class */ (function () {
  39973. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  39974. this.name = name;
  39975. this.targetProperty = targetProperty;
  39976. this.framePerSecond = framePerSecond;
  39977. this.dataType = dataType;
  39978. this.loopMode = loopMode;
  39979. this.enableBlending = enableBlending;
  39980. this._runtimeAnimations = new Array();
  39981. // The set of event that will be linked to this animation
  39982. this._events = new Array();
  39983. this.blendingSpeed = 0.01;
  39984. this._ranges = {};
  39985. this.targetPropertyPath = targetProperty.split(".");
  39986. this.dataType = dataType;
  39987. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  39988. }
  39989. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  39990. var dataType = undefined;
  39991. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  39992. dataType = Animation.ANIMATIONTYPE_FLOAT;
  39993. }
  39994. else if (from instanceof BABYLON.Quaternion) {
  39995. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  39996. }
  39997. else if (from instanceof BABYLON.Vector3) {
  39998. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  39999. }
  40000. else if (from instanceof BABYLON.Vector2) {
  40001. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40002. }
  40003. else if (from instanceof BABYLON.Color3) {
  40004. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40005. }
  40006. else if (from instanceof BABYLON.Size) {
  40007. dataType = Animation.ANIMATIONTYPE_SIZE;
  40008. }
  40009. if (dataType == undefined) {
  40010. return null;
  40011. }
  40012. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40013. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40014. animation.setKeys(keys);
  40015. if (easingFunction !== undefined) {
  40016. animation.setEasingFunction(easingFunction);
  40017. }
  40018. return animation;
  40019. };
  40020. /**
  40021. * Sets up an animation.
  40022. * @param property the property to animate
  40023. * @param animationType the animation type to apply
  40024. * @param easingFunction the easing function used in the animation
  40025. * @returns The created animation
  40026. */
  40027. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40028. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40029. animation.setEasingFunction(easingFunction);
  40030. return animation;
  40031. };
  40032. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40033. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40034. if (!animation) {
  40035. return null;
  40036. }
  40037. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40038. };
  40039. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40040. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40041. if (!animation) {
  40042. return null;
  40043. }
  40044. node.animations.push(animation);
  40045. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40046. };
  40047. /**
  40048. * Transition property of the Camera to the target Value.
  40049. * @param property The property to transition
  40050. * @param targetValue The target Value of the property
  40051. * @param host The object where the property to animate belongs
  40052. * @param scene Scene used to run the animation
  40053. * @param frameRate Framerate (in frame/s) to use
  40054. * @param transition The transition type we want to use
  40055. * @param duration The duration of the animation, in milliseconds
  40056. * @param onAnimationEnd Call back trigger at the end of the animation.
  40057. */
  40058. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40059. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40060. if (duration <= 0) {
  40061. host[property] = targetValue;
  40062. if (onAnimationEnd) {
  40063. onAnimationEnd();
  40064. }
  40065. return null;
  40066. }
  40067. var endFrame = frameRate * (duration / 1000);
  40068. transition.setKeys([{
  40069. frame: 0,
  40070. value: host[property].clone ? host[property].clone() : host[property]
  40071. },
  40072. {
  40073. frame: endFrame,
  40074. value: targetValue
  40075. }]);
  40076. if (!host.animations) {
  40077. host.animations = [];
  40078. }
  40079. host.animations.push(transition);
  40080. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40081. animation.onAnimationEnd = onAnimationEnd;
  40082. return animation;
  40083. };
  40084. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40085. /**
  40086. * Return the array of runtime animations currently using this animation
  40087. */
  40088. get: function () {
  40089. return this._runtimeAnimations;
  40090. },
  40091. enumerable: true,
  40092. configurable: true
  40093. });
  40094. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40095. get: function () {
  40096. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40097. var runtimeAnimation = _a[_i];
  40098. if (!runtimeAnimation.isStopped) {
  40099. return true;
  40100. }
  40101. }
  40102. return false;
  40103. },
  40104. enumerable: true,
  40105. configurable: true
  40106. });
  40107. // Methods
  40108. /**
  40109. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40110. */
  40111. Animation.prototype.toString = function (fullDetails) {
  40112. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40113. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40114. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40115. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40116. if (fullDetails) {
  40117. ret += ", Ranges: {";
  40118. var first = true;
  40119. for (var name in this._ranges) {
  40120. if (first) {
  40121. ret += ", ";
  40122. first = false;
  40123. }
  40124. ret += name;
  40125. }
  40126. ret += "}";
  40127. }
  40128. return ret;
  40129. };
  40130. /**
  40131. * Add an event to this animation.
  40132. */
  40133. Animation.prototype.addEvent = function (event) {
  40134. this._events.push(event);
  40135. };
  40136. /**
  40137. * Remove all events found at the given frame
  40138. * @param frame
  40139. */
  40140. Animation.prototype.removeEvents = function (frame) {
  40141. for (var index = 0; index < this._events.length; index++) {
  40142. if (this._events[index].frame === frame) {
  40143. this._events.splice(index, 1);
  40144. index--;
  40145. }
  40146. }
  40147. };
  40148. Animation.prototype.getEvents = function () {
  40149. return this._events;
  40150. };
  40151. Animation.prototype.createRange = function (name, from, to) {
  40152. // check name not already in use; could happen for bones after serialized
  40153. if (!this._ranges[name]) {
  40154. this._ranges[name] = new AnimationRange(name, from, to);
  40155. }
  40156. };
  40157. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40158. if (deleteFrames === void 0) { deleteFrames = true; }
  40159. var range = this._ranges[name];
  40160. if (!range) {
  40161. return;
  40162. }
  40163. if (deleteFrames) {
  40164. var from = range.from;
  40165. var to = range.to;
  40166. // this loop MUST go high to low for multiple splices to work
  40167. for (var key = this._keys.length - 1; key >= 0; key--) {
  40168. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40169. this._keys.splice(key, 1);
  40170. }
  40171. }
  40172. }
  40173. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40174. };
  40175. Animation.prototype.getRange = function (name) {
  40176. return this._ranges[name];
  40177. };
  40178. Animation.prototype.getKeys = function () {
  40179. return this._keys;
  40180. };
  40181. Animation.prototype.getHighestFrame = function () {
  40182. var ret = 0;
  40183. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40184. if (ret < this._keys[key].frame) {
  40185. ret = this._keys[key].frame;
  40186. }
  40187. }
  40188. return ret;
  40189. };
  40190. Animation.prototype.getEasingFunction = function () {
  40191. return this._easingFunction;
  40192. };
  40193. Animation.prototype.setEasingFunction = function (easingFunction) {
  40194. this._easingFunction = easingFunction;
  40195. };
  40196. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40197. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40198. };
  40199. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40200. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40201. };
  40202. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40203. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40204. };
  40205. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40206. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40207. };
  40208. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40209. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40210. };
  40211. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40212. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40213. };
  40214. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40215. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40216. };
  40217. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40218. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40219. };
  40220. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40221. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40222. };
  40223. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40224. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40225. };
  40226. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40227. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40228. };
  40229. Animation.prototype.clone = function () {
  40230. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40231. clone.enableBlending = this.enableBlending;
  40232. clone.blendingSpeed = this.blendingSpeed;
  40233. if (this._keys) {
  40234. clone.setKeys(this._keys);
  40235. }
  40236. if (this._ranges) {
  40237. clone._ranges = {};
  40238. for (var name in this._ranges) {
  40239. var range = this._ranges[name];
  40240. if (!range) {
  40241. continue;
  40242. }
  40243. clone._ranges[name] = range.clone();
  40244. }
  40245. }
  40246. return clone;
  40247. };
  40248. Animation.prototype.setKeys = function (values) {
  40249. this._keys = values.slice(0);
  40250. };
  40251. Animation.prototype.serialize = function () {
  40252. var serializationObject = {};
  40253. serializationObject.name = this.name;
  40254. serializationObject.property = this.targetProperty;
  40255. serializationObject.framePerSecond = this.framePerSecond;
  40256. serializationObject.dataType = this.dataType;
  40257. serializationObject.loopBehavior = this.loopMode;
  40258. serializationObject.enableBlending = this.enableBlending;
  40259. serializationObject.blendingSpeed = this.blendingSpeed;
  40260. var dataType = this.dataType;
  40261. serializationObject.keys = [];
  40262. var keys = this.getKeys();
  40263. for (var index = 0; index < keys.length; index++) {
  40264. var animationKey = keys[index];
  40265. var key = {};
  40266. key.frame = animationKey.frame;
  40267. switch (dataType) {
  40268. case Animation.ANIMATIONTYPE_FLOAT:
  40269. key.values = [animationKey.value];
  40270. break;
  40271. case Animation.ANIMATIONTYPE_QUATERNION:
  40272. case Animation.ANIMATIONTYPE_MATRIX:
  40273. case Animation.ANIMATIONTYPE_VECTOR3:
  40274. case Animation.ANIMATIONTYPE_COLOR3:
  40275. key.values = animationKey.value.asArray();
  40276. break;
  40277. }
  40278. serializationObject.keys.push(key);
  40279. }
  40280. serializationObject.ranges = [];
  40281. for (var name in this._ranges) {
  40282. var source = this._ranges[name];
  40283. if (!source) {
  40284. continue;
  40285. }
  40286. var range = {};
  40287. range.name = name;
  40288. range.from = source.from;
  40289. range.to = source.to;
  40290. serializationObject.ranges.push(range);
  40291. }
  40292. return serializationObject;
  40293. };
  40294. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40295. get: function () {
  40296. return Animation._ANIMATIONTYPE_FLOAT;
  40297. },
  40298. enumerable: true,
  40299. configurable: true
  40300. });
  40301. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40302. get: function () {
  40303. return Animation._ANIMATIONTYPE_VECTOR3;
  40304. },
  40305. enumerable: true,
  40306. configurable: true
  40307. });
  40308. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40309. get: function () {
  40310. return Animation._ANIMATIONTYPE_VECTOR2;
  40311. },
  40312. enumerable: true,
  40313. configurable: true
  40314. });
  40315. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40316. get: function () {
  40317. return Animation._ANIMATIONTYPE_SIZE;
  40318. },
  40319. enumerable: true,
  40320. configurable: true
  40321. });
  40322. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40323. get: function () {
  40324. return Animation._ANIMATIONTYPE_QUATERNION;
  40325. },
  40326. enumerable: true,
  40327. configurable: true
  40328. });
  40329. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40330. get: function () {
  40331. return Animation._ANIMATIONTYPE_MATRIX;
  40332. },
  40333. enumerable: true,
  40334. configurable: true
  40335. });
  40336. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40337. get: function () {
  40338. return Animation._ANIMATIONTYPE_COLOR3;
  40339. },
  40340. enumerable: true,
  40341. configurable: true
  40342. });
  40343. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40344. get: function () {
  40345. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40346. },
  40347. enumerable: true,
  40348. configurable: true
  40349. });
  40350. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40351. get: function () {
  40352. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40353. },
  40354. enumerable: true,
  40355. configurable: true
  40356. });
  40357. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40358. get: function () {
  40359. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40360. },
  40361. enumerable: true,
  40362. configurable: true
  40363. });
  40364. Animation.Parse = function (parsedAnimation) {
  40365. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40366. var dataType = parsedAnimation.dataType;
  40367. var keys = [];
  40368. var data;
  40369. var index;
  40370. if (parsedAnimation.enableBlending) {
  40371. animation.enableBlending = parsedAnimation.enableBlending;
  40372. }
  40373. if (parsedAnimation.blendingSpeed) {
  40374. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40375. }
  40376. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40377. var key = parsedAnimation.keys[index];
  40378. var inTangent;
  40379. var outTangent;
  40380. switch (dataType) {
  40381. case Animation.ANIMATIONTYPE_FLOAT:
  40382. data = key.values[0];
  40383. if (key.values.length >= 1) {
  40384. inTangent = key.values[1];
  40385. }
  40386. if (key.values.length >= 2) {
  40387. outTangent = key.values[2];
  40388. }
  40389. break;
  40390. case Animation.ANIMATIONTYPE_QUATERNION:
  40391. data = BABYLON.Quaternion.FromArray(key.values);
  40392. if (key.values.length >= 8) {
  40393. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40394. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40395. inTangent = _inTangent;
  40396. }
  40397. }
  40398. if (key.values.length >= 12) {
  40399. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40400. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40401. outTangent = _outTangent;
  40402. }
  40403. }
  40404. break;
  40405. case Animation.ANIMATIONTYPE_MATRIX:
  40406. data = BABYLON.Matrix.FromArray(key.values);
  40407. break;
  40408. case Animation.ANIMATIONTYPE_COLOR3:
  40409. data = BABYLON.Color3.FromArray(key.values);
  40410. break;
  40411. case Animation.ANIMATIONTYPE_VECTOR3:
  40412. default:
  40413. data = BABYLON.Vector3.FromArray(key.values);
  40414. break;
  40415. }
  40416. var keyData = {};
  40417. keyData.frame = key.frame;
  40418. keyData.value = data;
  40419. if (inTangent != undefined) {
  40420. keyData.inTangent = inTangent;
  40421. }
  40422. if (outTangent != undefined) {
  40423. keyData.outTangent = outTangent;
  40424. }
  40425. keys.push(keyData);
  40426. }
  40427. animation.setKeys(keys);
  40428. if (parsedAnimation.ranges) {
  40429. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40430. data = parsedAnimation.ranges[index];
  40431. animation.createRange(data.name, data.from, data.to);
  40432. }
  40433. }
  40434. return animation;
  40435. };
  40436. Animation.AppendSerializedAnimations = function (source, destination) {
  40437. if (source.animations) {
  40438. destination.animations = [];
  40439. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40440. var animation = source.animations[animationIndex];
  40441. destination.animations.push(animation.serialize());
  40442. }
  40443. }
  40444. };
  40445. Animation.AllowMatricesInterpolation = false;
  40446. // Statics
  40447. Animation._ANIMATIONTYPE_FLOAT = 0;
  40448. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40449. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40450. Animation._ANIMATIONTYPE_MATRIX = 3;
  40451. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40452. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40453. Animation._ANIMATIONTYPE_SIZE = 6;
  40454. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40455. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40456. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40457. return Animation;
  40458. }());
  40459. BABYLON.Animation = Animation;
  40460. })(BABYLON || (BABYLON = {}));
  40461. //# sourceMappingURL=babylon.animation.js.map
  40462. var BABYLON;
  40463. (function (BABYLON) {
  40464. var RuntimeAnimation = /** @class */ (function () {
  40465. function RuntimeAnimation(target, animation) {
  40466. this._offsetsCache = {};
  40467. this._highLimitsCache = {};
  40468. this._stopped = false;
  40469. this._blendingFactor = 0;
  40470. this._ratioOffset = 0;
  40471. this._animation = animation;
  40472. this._target = target;
  40473. animation._runtimeAnimations.push(this);
  40474. }
  40475. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40476. get: function () {
  40477. return this._animation;
  40478. },
  40479. enumerable: true,
  40480. configurable: true
  40481. });
  40482. RuntimeAnimation.prototype.reset = function () {
  40483. this._offsetsCache = {};
  40484. this._highLimitsCache = {};
  40485. this.currentFrame = 0;
  40486. this._blendingFactor = 0;
  40487. this._originalBlendValue = null;
  40488. };
  40489. RuntimeAnimation.prototype.isStopped = function () {
  40490. return this._stopped;
  40491. };
  40492. RuntimeAnimation.prototype.dispose = function () {
  40493. var index = this._animation.runtimeAnimations.indexOf(this);
  40494. if (index > -1) {
  40495. this._animation.runtimeAnimations.splice(index, 1);
  40496. }
  40497. };
  40498. RuntimeAnimation.prototype._getKeyValue = function (value) {
  40499. if (typeof value === "function") {
  40500. return value();
  40501. }
  40502. return value;
  40503. };
  40504. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  40505. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  40506. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  40507. }
  40508. this.currentFrame = currentFrame;
  40509. var keys = this._animation.getKeys();
  40510. // Try to get a hash to find the right key
  40511. 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));
  40512. if (keys[startKeyIndex].frame >= currentFrame) {
  40513. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  40514. startKeyIndex--;
  40515. }
  40516. }
  40517. for (var key = startKeyIndex; key < keys.length; key++) {
  40518. var endKey = keys[key + 1];
  40519. if (endKey.frame >= currentFrame) {
  40520. var startKey = keys[key];
  40521. var startValue = this._getKeyValue(startKey.value);
  40522. var endValue = this._getKeyValue(endKey.value);
  40523. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  40524. var frameDelta = endKey.frame - startKey.frame;
  40525. // gradient : percent of currentFrame between the frame inf and the frame sup
  40526. var gradient = (currentFrame - startKey.frame) / frameDelta;
  40527. // check for easingFunction and correction of gradient
  40528. var easingFunction = this._animation.getEasingFunction();
  40529. if (easingFunction != null) {
  40530. gradient = easingFunction.ease(gradient);
  40531. }
  40532. switch (this._animation.dataType) {
  40533. // Float
  40534. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40535. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  40536. switch (loopMode) {
  40537. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40538. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40539. return floatValue;
  40540. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40541. return offsetValue * repeatCount + floatValue;
  40542. }
  40543. break;
  40544. // Quaternion
  40545. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40546. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  40547. switch (loopMode) {
  40548. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40549. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40550. return quatValue;
  40551. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40552. return quatValue.add(offsetValue.scale(repeatCount));
  40553. }
  40554. return quatValue;
  40555. // Vector3
  40556. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40557. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  40558. switch (loopMode) {
  40559. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40560. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40561. return vec3Value;
  40562. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40563. return vec3Value.add(offsetValue.scale(repeatCount));
  40564. }
  40565. // Vector2
  40566. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40567. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  40568. switch (loopMode) {
  40569. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40570. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40571. return vec2Value;
  40572. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40573. return vec2Value.add(offsetValue.scale(repeatCount));
  40574. }
  40575. // Size
  40576. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40577. switch (loopMode) {
  40578. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40579. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40580. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  40581. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40582. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40583. }
  40584. // Color3
  40585. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40586. switch (loopMode) {
  40587. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40588. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40589. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  40590. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40591. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40592. }
  40593. // Matrix
  40594. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  40595. switch (loopMode) {
  40596. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40597. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40598. if (BABYLON.Animation.AllowMatricesInterpolation) {
  40599. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  40600. }
  40601. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40602. return startValue;
  40603. }
  40604. default:
  40605. break;
  40606. }
  40607. break;
  40608. }
  40609. }
  40610. return this._getKeyValue(keys[keys.length - 1].value);
  40611. };
  40612. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  40613. if (blend === void 0) { blend = false; }
  40614. // Set value
  40615. var path;
  40616. var destination;
  40617. var targetPropertyPath = this._animation.targetPropertyPath;
  40618. if (targetPropertyPath.length > 1) {
  40619. var property = this._target[targetPropertyPath[0]];
  40620. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  40621. property = property[targetPropertyPath[index]];
  40622. }
  40623. path = targetPropertyPath[targetPropertyPath.length - 1];
  40624. destination = property;
  40625. }
  40626. else {
  40627. path = targetPropertyPath[0];
  40628. destination = this._target;
  40629. }
  40630. // Blending
  40631. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  40632. if (!this._originalBlendValue) {
  40633. if (destination[path].clone) {
  40634. this._originalBlendValue = destination[path].clone();
  40635. }
  40636. else {
  40637. this._originalBlendValue = destination[path];
  40638. }
  40639. }
  40640. if (this._originalBlendValue.prototype) {
  40641. if (this._originalBlendValue.prototype.Lerp) {
  40642. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  40643. }
  40644. else {
  40645. destination[path] = currentValue;
  40646. }
  40647. }
  40648. else if (this._originalBlendValue.m) {
  40649. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  40650. }
  40651. else {
  40652. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  40653. }
  40654. this._blendingFactor += this._animation.blendingSpeed;
  40655. }
  40656. else {
  40657. destination[path] = currentValue;
  40658. }
  40659. if (this._target.markAsDirty) {
  40660. this._target.markAsDirty(this._animation.targetProperty);
  40661. }
  40662. };
  40663. RuntimeAnimation.prototype.goToFrame = function (frame) {
  40664. var keys = this._animation.getKeys();
  40665. if (frame < keys[0].frame) {
  40666. frame = keys[0].frame;
  40667. }
  40668. else if (frame > keys[keys.length - 1].frame) {
  40669. frame = keys[keys.length - 1].frame;
  40670. }
  40671. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  40672. this.setValue(currentValue);
  40673. };
  40674. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  40675. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  40676. this._ratioOffset = this._previousRatio - newRatio;
  40677. };
  40678. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  40679. if (blend === void 0) { blend = false; }
  40680. var targetPropertyPath = this._animation.targetPropertyPath;
  40681. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  40682. this._stopped = true;
  40683. return false;
  40684. }
  40685. var returnValue = true;
  40686. var keys = this._animation.getKeys();
  40687. // Adding a start key at frame 0 if missing
  40688. if (keys[0].frame !== 0) {
  40689. var newKey = { frame: 0, value: keys[0].value };
  40690. keys.splice(0, 0, newKey);
  40691. }
  40692. // Check limits
  40693. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  40694. from = keys[0].frame;
  40695. }
  40696. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  40697. to = keys[keys.length - 1].frame;
  40698. }
  40699. //to and from cannot be the same key
  40700. if (from === to) {
  40701. if (from > keys[0].frame) {
  40702. from--;
  40703. }
  40704. else if (to < keys[keys.length - 1].frame) {
  40705. to++;
  40706. }
  40707. }
  40708. // Compute ratio
  40709. var range = to - from;
  40710. var offsetValue;
  40711. // ratio represents the frame delta between from and to
  40712. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40713. var highLimitValue = 0;
  40714. this._previousDelay = delay;
  40715. this._previousRatio = ratio;
  40716. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40717. returnValue = false;
  40718. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40719. }
  40720. else {
  40721. // Get max value if required
  40722. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40723. var keyOffset = to.toString() + from.toString();
  40724. if (!this._offsetsCache[keyOffset]) {
  40725. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40726. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40727. switch (this._animation.dataType) {
  40728. // Float
  40729. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40730. this._offsetsCache[keyOffset] = toValue - fromValue;
  40731. break;
  40732. // Quaternion
  40733. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40734. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40735. break;
  40736. // Vector3
  40737. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40738. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40739. // Vector2
  40740. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40741. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40742. // Size
  40743. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40744. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40745. // Color3
  40746. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40747. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40748. default:
  40749. break;
  40750. }
  40751. this._highLimitsCache[keyOffset] = toValue;
  40752. }
  40753. highLimitValue = this._highLimitsCache[keyOffset];
  40754. offsetValue = this._offsetsCache[keyOffset];
  40755. }
  40756. }
  40757. if (offsetValue === undefined) {
  40758. switch (this._animation.dataType) {
  40759. // Float
  40760. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40761. offsetValue = 0;
  40762. break;
  40763. // Quaternion
  40764. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40765. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40766. break;
  40767. // Vector3
  40768. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40769. offsetValue = BABYLON.Vector3.Zero();
  40770. break;
  40771. // Vector2
  40772. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40773. offsetValue = BABYLON.Vector2.Zero();
  40774. break;
  40775. // Size
  40776. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40777. offsetValue = BABYLON.Size.Zero();
  40778. break;
  40779. // Color3
  40780. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40781. offsetValue = BABYLON.Color3.Black();
  40782. }
  40783. }
  40784. // Compute value
  40785. var repeatCount = (ratio / range) >> 0;
  40786. var currentFrame = returnValue ? from + ratio % range : to;
  40787. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40788. // Set value
  40789. this.setValue(currentValue);
  40790. // Check events
  40791. var events = this._animation.getEvents();
  40792. for (var index = 0; index < events.length; index++) {
  40793. // Make sure current frame has passed event frame and that event frame is within the current range
  40794. // Also, handle both forward and reverse animations
  40795. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40796. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40797. var event = events[index];
  40798. if (!event.isDone) {
  40799. // If event should be done only once, remove it.
  40800. if (event.onlyOnce) {
  40801. events.splice(index, 1);
  40802. index--;
  40803. }
  40804. event.isDone = true;
  40805. event.action();
  40806. } // Don't do anything if the event has already be done.
  40807. }
  40808. else if (events[index].isDone && !events[index].onlyOnce) {
  40809. // reset event, the animation is looping
  40810. events[index].isDone = false;
  40811. }
  40812. }
  40813. if (!returnValue) {
  40814. this._stopped = true;
  40815. }
  40816. return returnValue;
  40817. };
  40818. return RuntimeAnimation;
  40819. }());
  40820. BABYLON.RuntimeAnimation = RuntimeAnimation;
  40821. })(BABYLON || (BABYLON = {}));
  40822. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  40823. var BABYLON;
  40824. (function (BABYLON) {
  40825. var Animatable = /** @class */ (function () {
  40826. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  40827. if (fromFrame === void 0) { fromFrame = 0; }
  40828. if (toFrame === void 0) { toFrame = 100; }
  40829. if (loopAnimation === void 0) { loopAnimation = false; }
  40830. if (speedRatio === void 0) { speedRatio = 1.0; }
  40831. this.target = target;
  40832. this.fromFrame = fromFrame;
  40833. this.toFrame = toFrame;
  40834. this.loopAnimation = loopAnimation;
  40835. this.onAnimationEnd = onAnimationEnd;
  40836. this._localDelayOffset = null;
  40837. this._pausedDelay = null;
  40838. this._runtimeAnimations = new Array();
  40839. this._paused = false;
  40840. this._speedRatio = 1;
  40841. this.animationStarted = false;
  40842. if (animations) {
  40843. this.appendAnimations(target, animations);
  40844. }
  40845. this._speedRatio = speedRatio;
  40846. this._scene = scene;
  40847. scene._activeAnimatables.push(this);
  40848. }
  40849. Object.defineProperty(Animatable.prototype, "speedRatio", {
  40850. get: function () {
  40851. return this._speedRatio;
  40852. },
  40853. set: function (value) {
  40854. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  40855. var animation = this._runtimeAnimations[index];
  40856. animation._prepareForSpeedRatioChange(value);
  40857. }
  40858. this._speedRatio = value;
  40859. },
  40860. enumerable: true,
  40861. configurable: true
  40862. });
  40863. // Methods
  40864. Animatable.prototype.getAnimations = function () {
  40865. return this._runtimeAnimations;
  40866. };
  40867. Animatable.prototype.appendAnimations = function (target, animations) {
  40868. for (var index = 0; index < animations.length; index++) {
  40869. var animation = animations[index];
  40870. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  40871. }
  40872. };
  40873. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  40874. var runtimeAnimations = this._runtimeAnimations;
  40875. for (var index = 0; index < runtimeAnimations.length; index++) {
  40876. if (runtimeAnimations[index].animation.targetProperty === property) {
  40877. return runtimeAnimations[index].animation;
  40878. }
  40879. }
  40880. return null;
  40881. };
  40882. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  40883. var runtimeAnimations = this._runtimeAnimations;
  40884. for (var index = 0; index < runtimeAnimations.length; index++) {
  40885. if (runtimeAnimations[index].animation.targetProperty === property) {
  40886. return runtimeAnimations[index];
  40887. }
  40888. }
  40889. return null;
  40890. };
  40891. Animatable.prototype.reset = function () {
  40892. var runtimeAnimations = this._runtimeAnimations;
  40893. for (var index = 0; index < runtimeAnimations.length; index++) {
  40894. runtimeAnimations[index].reset();
  40895. }
  40896. this._localDelayOffset = null;
  40897. this._pausedDelay = null;
  40898. };
  40899. Animatable.prototype.enableBlending = function (blendingSpeed) {
  40900. var runtimeAnimations = this._runtimeAnimations;
  40901. for (var index = 0; index < runtimeAnimations.length; index++) {
  40902. runtimeAnimations[index].animation.enableBlending = true;
  40903. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  40904. }
  40905. };
  40906. Animatable.prototype.disableBlending = function () {
  40907. var runtimeAnimations = this._runtimeAnimations;
  40908. for (var index = 0; index < runtimeAnimations.length; index++) {
  40909. runtimeAnimations[index].animation.enableBlending = false;
  40910. }
  40911. };
  40912. Animatable.prototype.goToFrame = function (frame) {
  40913. var runtimeAnimations = this._runtimeAnimations;
  40914. if (runtimeAnimations[0]) {
  40915. var fps = runtimeAnimations[0].animation.framePerSecond;
  40916. var currentFrame = runtimeAnimations[0].currentFrame;
  40917. var adjustTime = frame - currentFrame;
  40918. var delay = adjustTime * 1000 / fps;
  40919. if (this._localDelayOffset === null) {
  40920. this._localDelayOffset = 0;
  40921. }
  40922. this._localDelayOffset -= delay;
  40923. }
  40924. for (var index = 0; index < runtimeAnimations.length; index++) {
  40925. runtimeAnimations[index].goToFrame(frame);
  40926. }
  40927. };
  40928. Animatable.prototype.pause = function () {
  40929. if (this._paused) {
  40930. return;
  40931. }
  40932. this._paused = true;
  40933. };
  40934. Animatable.prototype.restart = function () {
  40935. this._paused = false;
  40936. };
  40937. Animatable.prototype.stop = function (animationName) {
  40938. if (animationName) {
  40939. var idx = this._scene._activeAnimatables.indexOf(this);
  40940. if (idx > -1) {
  40941. var runtimeAnimations = this._runtimeAnimations;
  40942. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  40943. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  40944. continue;
  40945. }
  40946. runtimeAnimations[index].dispose();
  40947. runtimeAnimations.splice(index, 1);
  40948. }
  40949. if (runtimeAnimations.length == 0) {
  40950. this._scene._activeAnimatables.splice(idx, 1);
  40951. if (this.onAnimationEnd) {
  40952. this.onAnimationEnd();
  40953. }
  40954. }
  40955. }
  40956. }
  40957. else {
  40958. var index = this._scene._activeAnimatables.indexOf(this);
  40959. if (index > -1) {
  40960. this._scene._activeAnimatables.splice(index, 1);
  40961. var runtimeAnimations = this._runtimeAnimations;
  40962. for (var index = 0; index < runtimeAnimations.length; index++) {
  40963. runtimeAnimations[index].dispose();
  40964. }
  40965. if (this.onAnimationEnd) {
  40966. this.onAnimationEnd();
  40967. }
  40968. }
  40969. }
  40970. };
  40971. Animatable.prototype._animate = function (delay) {
  40972. if (this._paused) {
  40973. this.animationStarted = false;
  40974. if (this._pausedDelay === null) {
  40975. this._pausedDelay = delay;
  40976. }
  40977. return true;
  40978. }
  40979. if (this._localDelayOffset === null) {
  40980. this._localDelayOffset = delay;
  40981. }
  40982. else if (this._pausedDelay !== null) {
  40983. this._localDelayOffset += delay - this._pausedDelay;
  40984. this._pausedDelay = null;
  40985. }
  40986. // Animating
  40987. var running = false;
  40988. var runtimeAnimations = this._runtimeAnimations;
  40989. var index;
  40990. for (index = 0; index < runtimeAnimations.length; index++) {
  40991. var animation = runtimeAnimations[index];
  40992. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  40993. running = running || isRunning;
  40994. }
  40995. this.animationStarted = running;
  40996. if (!running) {
  40997. // Remove from active animatables
  40998. index = this._scene._activeAnimatables.indexOf(this);
  40999. this._scene._activeAnimatables.splice(index, 1);
  41000. // Dispose all runtime animations
  41001. for (index = 0; index < runtimeAnimations.length; index++) {
  41002. runtimeAnimations[index].dispose();
  41003. }
  41004. }
  41005. if (!running && this.onAnimationEnd) {
  41006. this.onAnimationEnd();
  41007. this.onAnimationEnd = null;
  41008. }
  41009. return running;
  41010. };
  41011. return Animatable;
  41012. }());
  41013. BABYLON.Animatable = Animatable;
  41014. })(BABYLON || (BABYLON = {}));
  41015. //# sourceMappingURL=babylon.animatable.js.map
  41016. var BABYLON;
  41017. (function (BABYLON) {
  41018. var EasingFunction = /** @class */ (function () {
  41019. function EasingFunction() {
  41020. // Properties
  41021. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41022. }
  41023. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41024. get: function () {
  41025. return EasingFunction._EASINGMODE_EASEIN;
  41026. },
  41027. enumerable: true,
  41028. configurable: true
  41029. });
  41030. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41031. get: function () {
  41032. return EasingFunction._EASINGMODE_EASEOUT;
  41033. },
  41034. enumerable: true,
  41035. configurable: true
  41036. });
  41037. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41038. get: function () {
  41039. return EasingFunction._EASINGMODE_EASEINOUT;
  41040. },
  41041. enumerable: true,
  41042. configurable: true
  41043. });
  41044. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41045. var n = Math.min(Math.max(easingMode, 0), 2);
  41046. this._easingMode = n;
  41047. };
  41048. EasingFunction.prototype.getEasingMode = function () {
  41049. return this._easingMode;
  41050. };
  41051. EasingFunction.prototype.easeInCore = function (gradient) {
  41052. throw new Error('You must implement this method');
  41053. };
  41054. EasingFunction.prototype.ease = function (gradient) {
  41055. switch (this._easingMode) {
  41056. case EasingFunction.EASINGMODE_EASEIN:
  41057. return this.easeInCore(gradient);
  41058. case EasingFunction.EASINGMODE_EASEOUT:
  41059. return (1 - this.easeInCore(1 - gradient));
  41060. }
  41061. if (gradient >= 0.5) {
  41062. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41063. }
  41064. return (this.easeInCore(gradient * 2) * 0.5);
  41065. };
  41066. //Statics
  41067. EasingFunction._EASINGMODE_EASEIN = 0;
  41068. EasingFunction._EASINGMODE_EASEOUT = 1;
  41069. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41070. return EasingFunction;
  41071. }());
  41072. BABYLON.EasingFunction = EasingFunction;
  41073. var CircleEase = /** @class */ (function (_super) {
  41074. __extends(CircleEase, _super);
  41075. function CircleEase() {
  41076. return _super !== null && _super.apply(this, arguments) || this;
  41077. }
  41078. CircleEase.prototype.easeInCore = function (gradient) {
  41079. gradient = Math.max(0, Math.min(1, gradient));
  41080. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41081. };
  41082. return CircleEase;
  41083. }(EasingFunction));
  41084. BABYLON.CircleEase = CircleEase;
  41085. var BackEase = /** @class */ (function (_super) {
  41086. __extends(BackEase, _super);
  41087. function BackEase(amplitude) {
  41088. if (amplitude === void 0) { amplitude = 1; }
  41089. var _this = _super.call(this) || this;
  41090. _this.amplitude = amplitude;
  41091. return _this;
  41092. }
  41093. BackEase.prototype.easeInCore = function (gradient) {
  41094. var num = Math.max(0, this.amplitude);
  41095. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41096. };
  41097. return BackEase;
  41098. }(EasingFunction));
  41099. BABYLON.BackEase = BackEase;
  41100. var BounceEase = /** @class */ (function (_super) {
  41101. __extends(BounceEase, _super);
  41102. function BounceEase(bounces, bounciness) {
  41103. if (bounces === void 0) { bounces = 3; }
  41104. if (bounciness === void 0) { bounciness = 2; }
  41105. var _this = _super.call(this) || this;
  41106. _this.bounces = bounces;
  41107. _this.bounciness = bounciness;
  41108. return _this;
  41109. }
  41110. BounceEase.prototype.easeInCore = function (gradient) {
  41111. var y = Math.max(0.0, this.bounces);
  41112. var bounciness = this.bounciness;
  41113. if (bounciness <= 1.0) {
  41114. bounciness = 1.001;
  41115. }
  41116. var num9 = Math.pow(bounciness, y);
  41117. var num5 = 1.0 - bounciness;
  41118. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41119. var num15 = gradient * num4;
  41120. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41121. var num3 = Math.floor(num65);
  41122. var num13 = num3 + 1.0;
  41123. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41124. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41125. var num7 = (num8 + num12) * 0.5;
  41126. var num6 = gradient - num7;
  41127. var num2 = num7 - num8;
  41128. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41129. };
  41130. return BounceEase;
  41131. }(EasingFunction));
  41132. BABYLON.BounceEase = BounceEase;
  41133. var CubicEase = /** @class */ (function (_super) {
  41134. __extends(CubicEase, _super);
  41135. function CubicEase() {
  41136. return _super !== null && _super.apply(this, arguments) || this;
  41137. }
  41138. CubicEase.prototype.easeInCore = function (gradient) {
  41139. return (gradient * gradient * gradient);
  41140. };
  41141. return CubicEase;
  41142. }(EasingFunction));
  41143. BABYLON.CubicEase = CubicEase;
  41144. var ElasticEase = /** @class */ (function (_super) {
  41145. __extends(ElasticEase, _super);
  41146. function ElasticEase(oscillations, springiness) {
  41147. if (oscillations === void 0) { oscillations = 3; }
  41148. if (springiness === void 0) { springiness = 3; }
  41149. var _this = _super.call(this) || this;
  41150. _this.oscillations = oscillations;
  41151. _this.springiness = springiness;
  41152. return _this;
  41153. }
  41154. ElasticEase.prototype.easeInCore = function (gradient) {
  41155. var num2;
  41156. var num3 = Math.max(0.0, this.oscillations);
  41157. var num = Math.max(0.0, this.springiness);
  41158. if (num == 0) {
  41159. num2 = gradient;
  41160. }
  41161. else {
  41162. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41163. }
  41164. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41165. };
  41166. return ElasticEase;
  41167. }(EasingFunction));
  41168. BABYLON.ElasticEase = ElasticEase;
  41169. var ExponentialEase = /** @class */ (function (_super) {
  41170. __extends(ExponentialEase, _super);
  41171. function ExponentialEase(exponent) {
  41172. if (exponent === void 0) { exponent = 2; }
  41173. var _this = _super.call(this) || this;
  41174. _this.exponent = exponent;
  41175. return _this;
  41176. }
  41177. ExponentialEase.prototype.easeInCore = function (gradient) {
  41178. if (this.exponent <= 0) {
  41179. return gradient;
  41180. }
  41181. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41182. };
  41183. return ExponentialEase;
  41184. }(EasingFunction));
  41185. BABYLON.ExponentialEase = ExponentialEase;
  41186. var PowerEase = /** @class */ (function (_super) {
  41187. __extends(PowerEase, _super);
  41188. function PowerEase(power) {
  41189. if (power === void 0) { power = 2; }
  41190. var _this = _super.call(this) || this;
  41191. _this.power = power;
  41192. return _this;
  41193. }
  41194. PowerEase.prototype.easeInCore = function (gradient) {
  41195. var y = Math.max(0.0, this.power);
  41196. return Math.pow(gradient, y);
  41197. };
  41198. return PowerEase;
  41199. }(EasingFunction));
  41200. BABYLON.PowerEase = PowerEase;
  41201. var QuadraticEase = /** @class */ (function (_super) {
  41202. __extends(QuadraticEase, _super);
  41203. function QuadraticEase() {
  41204. return _super !== null && _super.apply(this, arguments) || this;
  41205. }
  41206. QuadraticEase.prototype.easeInCore = function (gradient) {
  41207. return (gradient * gradient);
  41208. };
  41209. return QuadraticEase;
  41210. }(EasingFunction));
  41211. BABYLON.QuadraticEase = QuadraticEase;
  41212. var QuarticEase = /** @class */ (function (_super) {
  41213. __extends(QuarticEase, _super);
  41214. function QuarticEase() {
  41215. return _super !== null && _super.apply(this, arguments) || this;
  41216. }
  41217. QuarticEase.prototype.easeInCore = function (gradient) {
  41218. return (gradient * gradient * gradient * gradient);
  41219. };
  41220. return QuarticEase;
  41221. }(EasingFunction));
  41222. BABYLON.QuarticEase = QuarticEase;
  41223. var QuinticEase = /** @class */ (function (_super) {
  41224. __extends(QuinticEase, _super);
  41225. function QuinticEase() {
  41226. return _super !== null && _super.apply(this, arguments) || this;
  41227. }
  41228. QuinticEase.prototype.easeInCore = function (gradient) {
  41229. return (gradient * gradient * gradient * gradient * gradient);
  41230. };
  41231. return QuinticEase;
  41232. }(EasingFunction));
  41233. BABYLON.QuinticEase = QuinticEase;
  41234. var SineEase = /** @class */ (function (_super) {
  41235. __extends(SineEase, _super);
  41236. function SineEase() {
  41237. return _super !== null && _super.apply(this, arguments) || this;
  41238. }
  41239. SineEase.prototype.easeInCore = function (gradient) {
  41240. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41241. };
  41242. return SineEase;
  41243. }(EasingFunction));
  41244. BABYLON.SineEase = SineEase;
  41245. var BezierCurveEase = /** @class */ (function (_super) {
  41246. __extends(BezierCurveEase, _super);
  41247. function BezierCurveEase(x1, y1, x2, y2) {
  41248. if (x1 === void 0) { x1 = 0; }
  41249. if (y1 === void 0) { y1 = 0; }
  41250. if (x2 === void 0) { x2 = 1; }
  41251. if (y2 === void 0) { y2 = 1; }
  41252. var _this = _super.call(this) || this;
  41253. _this.x1 = x1;
  41254. _this.y1 = y1;
  41255. _this.x2 = x2;
  41256. _this.y2 = y2;
  41257. return _this;
  41258. }
  41259. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41260. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41261. };
  41262. return BezierCurveEase;
  41263. }(EasingFunction));
  41264. BABYLON.BezierCurveEase = BezierCurveEase;
  41265. })(BABYLON || (BABYLON = {}));
  41266. //# sourceMappingURL=babylon.easing.js.map
  41267. var BABYLON;
  41268. (function (BABYLON) {
  41269. var Condition = /** @class */ (function () {
  41270. function Condition(actionManager) {
  41271. this._actionManager = actionManager;
  41272. }
  41273. Condition.prototype.isValid = function () {
  41274. return true;
  41275. };
  41276. Condition.prototype._getProperty = function (propertyPath) {
  41277. return this._actionManager._getProperty(propertyPath);
  41278. };
  41279. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41280. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41281. };
  41282. Condition.prototype.serialize = function () {
  41283. };
  41284. Condition.prototype._serialize = function (serializedCondition) {
  41285. return {
  41286. type: 2,
  41287. children: [],
  41288. name: serializedCondition.name,
  41289. properties: serializedCondition.properties
  41290. };
  41291. };
  41292. return Condition;
  41293. }());
  41294. BABYLON.Condition = Condition;
  41295. var ValueCondition = /** @class */ (function (_super) {
  41296. __extends(ValueCondition, _super);
  41297. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41298. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41299. var _this = _super.call(this, actionManager) || this;
  41300. _this.propertyPath = propertyPath;
  41301. _this.value = value;
  41302. _this.operator = operator;
  41303. _this._target = target;
  41304. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41305. _this._property = _this._getProperty(_this.propertyPath);
  41306. return _this;
  41307. }
  41308. Object.defineProperty(ValueCondition, "IsEqual", {
  41309. get: function () {
  41310. return ValueCondition._IsEqual;
  41311. },
  41312. enumerable: true,
  41313. configurable: true
  41314. });
  41315. Object.defineProperty(ValueCondition, "IsDifferent", {
  41316. get: function () {
  41317. return ValueCondition._IsDifferent;
  41318. },
  41319. enumerable: true,
  41320. configurable: true
  41321. });
  41322. Object.defineProperty(ValueCondition, "IsGreater", {
  41323. get: function () {
  41324. return ValueCondition._IsGreater;
  41325. },
  41326. enumerable: true,
  41327. configurable: true
  41328. });
  41329. Object.defineProperty(ValueCondition, "IsLesser", {
  41330. get: function () {
  41331. return ValueCondition._IsLesser;
  41332. },
  41333. enumerable: true,
  41334. configurable: true
  41335. });
  41336. // Methods
  41337. ValueCondition.prototype.isValid = function () {
  41338. switch (this.operator) {
  41339. case ValueCondition.IsGreater:
  41340. return this._effectiveTarget[this._property] > this.value;
  41341. case ValueCondition.IsLesser:
  41342. return this._effectiveTarget[this._property] < this.value;
  41343. case ValueCondition.IsEqual:
  41344. case ValueCondition.IsDifferent:
  41345. var check;
  41346. if (this.value.equals) {
  41347. check = this.value.equals(this._effectiveTarget[this._property]);
  41348. }
  41349. else {
  41350. check = this.value === this._effectiveTarget[this._property];
  41351. }
  41352. return this.operator === ValueCondition.IsEqual ? check : !check;
  41353. }
  41354. return false;
  41355. };
  41356. ValueCondition.prototype.serialize = function () {
  41357. return this._serialize({
  41358. name: "ValueCondition",
  41359. properties: [
  41360. BABYLON.Action._GetTargetProperty(this._target),
  41361. { name: "propertyPath", value: this.propertyPath },
  41362. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41363. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41364. ]
  41365. });
  41366. };
  41367. ValueCondition.GetOperatorName = function (operator) {
  41368. switch (operator) {
  41369. case ValueCondition._IsEqual: return "IsEqual";
  41370. case ValueCondition._IsDifferent: return "IsDifferent";
  41371. case ValueCondition._IsGreater: return "IsGreater";
  41372. case ValueCondition._IsLesser: return "IsLesser";
  41373. default: return "";
  41374. }
  41375. };
  41376. // Statics
  41377. ValueCondition._IsEqual = 0;
  41378. ValueCondition._IsDifferent = 1;
  41379. ValueCondition._IsGreater = 2;
  41380. ValueCondition._IsLesser = 3;
  41381. return ValueCondition;
  41382. }(Condition));
  41383. BABYLON.ValueCondition = ValueCondition;
  41384. var PredicateCondition = /** @class */ (function (_super) {
  41385. __extends(PredicateCondition, _super);
  41386. function PredicateCondition(actionManager, predicate) {
  41387. var _this = _super.call(this, actionManager) || this;
  41388. _this.predicate = predicate;
  41389. return _this;
  41390. }
  41391. PredicateCondition.prototype.isValid = function () {
  41392. return this.predicate();
  41393. };
  41394. return PredicateCondition;
  41395. }(Condition));
  41396. BABYLON.PredicateCondition = PredicateCondition;
  41397. var StateCondition = /** @class */ (function (_super) {
  41398. __extends(StateCondition, _super);
  41399. function StateCondition(actionManager, target, value) {
  41400. var _this = _super.call(this, actionManager) || this;
  41401. _this.value = value;
  41402. _this._target = target;
  41403. return _this;
  41404. }
  41405. // Methods
  41406. StateCondition.prototype.isValid = function () {
  41407. return this._target.state === this.value;
  41408. };
  41409. StateCondition.prototype.serialize = function () {
  41410. return this._serialize({
  41411. name: "StateCondition",
  41412. properties: [
  41413. BABYLON.Action._GetTargetProperty(this._target),
  41414. { name: "value", value: this.value }
  41415. ]
  41416. });
  41417. };
  41418. return StateCondition;
  41419. }(Condition));
  41420. BABYLON.StateCondition = StateCondition;
  41421. })(BABYLON || (BABYLON = {}));
  41422. //# sourceMappingURL=babylon.condition.js.map
  41423. var BABYLON;
  41424. (function (BABYLON) {
  41425. var Action = /** @class */ (function () {
  41426. function Action(triggerOptions, condition) {
  41427. this.triggerOptions = triggerOptions;
  41428. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41429. if (triggerOptions.parameter) {
  41430. this.trigger = triggerOptions.trigger;
  41431. this._triggerParameter = triggerOptions.parameter;
  41432. }
  41433. else {
  41434. this.trigger = triggerOptions;
  41435. }
  41436. this._nextActiveAction = this;
  41437. this._condition = condition;
  41438. }
  41439. // Methods
  41440. Action.prototype._prepare = function () {
  41441. };
  41442. Action.prototype.getTriggerParameter = function () {
  41443. return this._triggerParameter;
  41444. };
  41445. Action.prototype._executeCurrent = function (evt) {
  41446. if (this._nextActiveAction._condition) {
  41447. var condition = this._nextActiveAction._condition;
  41448. var currentRenderId = this._actionManager.getScene().getRenderId();
  41449. // We cache the current evaluation for the current frame
  41450. if (condition._evaluationId === currentRenderId) {
  41451. if (!condition._currentResult) {
  41452. return;
  41453. }
  41454. }
  41455. else {
  41456. condition._evaluationId = currentRenderId;
  41457. if (!condition.isValid()) {
  41458. condition._currentResult = false;
  41459. return;
  41460. }
  41461. condition._currentResult = true;
  41462. }
  41463. }
  41464. this.onBeforeExecuteObservable.notifyObservers(this);
  41465. this._nextActiveAction.execute(evt);
  41466. this.skipToNextActiveAction();
  41467. };
  41468. Action.prototype.execute = function (evt) {
  41469. };
  41470. Action.prototype.skipToNextActiveAction = function () {
  41471. if (this._nextActiveAction._child) {
  41472. if (!this._nextActiveAction._child._actionManager) {
  41473. this._nextActiveAction._child._actionManager = this._actionManager;
  41474. }
  41475. this._nextActiveAction = this._nextActiveAction._child;
  41476. }
  41477. else {
  41478. this._nextActiveAction = this;
  41479. }
  41480. };
  41481. Action.prototype.then = function (action) {
  41482. this._child = action;
  41483. action._actionManager = this._actionManager;
  41484. action._prepare();
  41485. return action;
  41486. };
  41487. Action.prototype._getProperty = function (propertyPath) {
  41488. return this._actionManager._getProperty(propertyPath);
  41489. };
  41490. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41491. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41492. };
  41493. Action.prototype.serialize = function (parent) {
  41494. };
  41495. // Called by BABYLON.Action objects in serialize(...). Internal use
  41496. Action.prototype._serialize = function (serializedAction, parent) {
  41497. var serializationObject = {
  41498. type: 1,
  41499. children: [],
  41500. name: serializedAction.name,
  41501. properties: serializedAction.properties || []
  41502. };
  41503. // Serialize child
  41504. if (this._child) {
  41505. this._child.serialize(serializationObject);
  41506. }
  41507. // Check if "this" has a condition
  41508. if (this._condition) {
  41509. var serializedCondition = this._condition.serialize();
  41510. serializedCondition.children.push(serializationObject);
  41511. if (parent) {
  41512. parent.children.push(serializedCondition);
  41513. }
  41514. return serializedCondition;
  41515. }
  41516. if (parent) {
  41517. parent.children.push(serializationObject);
  41518. }
  41519. return serializationObject;
  41520. };
  41521. Action._SerializeValueAsString = function (value) {
  41522. if (typeof value === "number") {
  41523. return value.toString();
  41524. }
  41525. if (typeof value === "boolean") {
  41526. return value ? "true" : "false";
  41527. }
  41528. if (value instanceof BABYLON.Vector2) {
  41529. return value.x + ", " + value.y;
  41530. }
  41531. if (value instanceof BABYLON.Vector3) {
  41532. return value.x + ", " + value.y + ", " + value.z;
  41533. }
  41534. if (value instanceof BABYLON.Color3) {
  41535. return value.r + ", " + value.g + ", " + value.b;
  41536. }
  41537. if (value instanceof BABYLON.Color4) {
  41538. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41539. }
  41540. return value; // string
  41541. };
  41542. Action._GetTargetProperty = function (target) {
  41543. return {
  41544. name: "target",
  41545. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41546. : target instanceof BABYLON.Light ? "LightProperties"
  41547. : target instanceof BABYLON.Camera ? "CameraProperties"
  41548. : "SceneProperties",
  41549. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41550. };
  41551. };
  41552. return Action;
  41553. }());
  41554. BABYLON.Action = Action;
  41555. })(BABYLON || (BABYLON = {}));
  41556. //# sourceMappingURL=babylon.action.js.map
  41557. var BABYLON;
  41558. (function (BABYLON) {
  41559. /**
  41560. * ActionEvent is the event beint sent when an action is triggered.
  41561. */
  41562. var ActionEvent = /** @class */ (function () {
  41563. /**
  41564. * @param source The mesh or sprite that triggered the action.
  41565. * @param pointerX The X mouse cursor position at the time of the event
  41566. * @param pointerY The Y mouse cursor position at the time of the event
  41567. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41568. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41569. */
  41570. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41571. this.source = source;
  41572. this.pointerX = pointerX;
  41573. this.pointerY = pointerY;
  41574. this.meshUnderPointer = meshUnderPointer;
  41575. this.sourceEvent = sourceEvent;
  41576. this.additionalData = additionalData;
  41577. }
  41578. /**
  41579. * Helper function to auto-create an ActionEvent from a source mesh.
  41580. * @param source The source mesh that triggered the event
  41581. * @param evt {Event} The original (browser) event
  41582. */
  41583. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41584. var scene = source.getScene();
  41585. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41586. };
  41587. /**
  41588. * Helper function to auto-create an ActionEvent from a source mesh.
  41589. * @param source The source sprite that triggered the event
  41590. * @param scene Scene associated with the sprite
  41591. * @param evt {Event} The original (browser) event
  41592. */
  41593. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41594. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41595. };
  41596. /**
  41597. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41598. * @param scene the scene where the event occurred
  41599. * @param evt {Event} The original (browser) event
  41600. */
  41601. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41602. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41603. };
  41604. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41605. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41606. };
  41607. return ActionEvent;
  41608. }());
  41609. BABYLON.ActionEvent = ActionEvent;
  41610. /**
  41611. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41612. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41613. */
  41614. var ActionManager = /** @class */ (function () {
  41615. function ActionManager(scene) {
  41616. // Members
  41617. this.actions = new Array();
  41618. this.hoverCursor = '';
  41619. this._scene = scene;
  41620. scene._actionManagers.push(this);
  41621. }
  41622. Object.defineProperty(ActionManager, "NothingTrigger", {
  41623. get: function () {
  41624. return ActionManager._NothingTrigger;
  41625. },
  41626. enumerable: true,
  41627. configurable: true
  41628. });
  41629. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41630. get: function () {
  41631. return ActionManager._OnPickTrigger;
  41632. },
  41633. enumerable: true,
  41634. configurable: true
  41635. });
  41636. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41637. get: function () {
  41638. return ActionManager._OnLeftPickTrigger;
  41639. },
  41640. enumerable: true,
  41641. configurable: true
  41642. });
  41643. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41644. get: function () {
  41645. return ActionManager._OnRightPickTrigger;
  41646. },
  41647. enumerable: true,
  41648. configurable: true
  41649. });
  41650. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41651. get: function () {
  41652. return ActionManager._OnCenterPickTrigger;
  41653. },
  41654. enumerable: true,
  41655. configurable: true
  41656. });
  41657. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41658. get: function () {
  41659. return ActionManager._OnPickDownTrigger;
  41660. },
  41661. enumerable: true,
  41662. configurable: true
  41663. });
  41664. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41665. get: function () {
  41666. return ActionManager._OnDoublePickTrigger;
  41667. },
  41668. enumerable: true,
  41669. configurable: true
  41670. });
  41671. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41672. get: function () {
  41673. return ActionManager._OnPickUpTrigger;
  41674. },
  41675. enumerable: true,
  41676. configurable: true
  41677. });
  41678. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41679. /// This trigger will only be raised if you also declared a OnPickDown
  41680. get: function () {
  41681. return ActionManager._OnPickOutTrigger;
  41682. },
  41683. enumerable: true,
  41684. configurable: true
  41685. });
  41686. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41687. get: function () {
  41688. return ActionManager._OnLongPressTrigger;
  41689. },
  41690. enumerable: true,
  41691. configurable: true
  41692. });
  41693. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41694. get: function () {
  41695. return ActionManager._OnPointerOverTrigger;
  41696. },
  41697. enumerable: true,
  41698. configurable: true
  41699. });
  41700. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41701. get: function () {
  41702. return ActionManager._OnPointerOutTrigger;
  41703. },
  41704. enumerable: true,
  41705. configurable: true
  41706. });
  41707. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41708. get: function () {
  41709. return ActionManager._OnEveryFrameTrigger;
  41710. },
  41711. enumerable: true,
  41712. configurable: true
  41713. });
  41714. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41715. get: function () {
  41716. return ActionManager._OnIntersectionEnterTrigger;
  41717. },
  41718. enumerable: true,
  41719. configurable: true
  41720. });
  41721. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41722. get: function () {
  41723. return ActionManager._OnIntersectionExitTrigger;
  41724. },
  41725. enumerable: true,
  41726. configurable: true
  41727. });
  41728. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41729. get: function () {
  41730. return ActionManager._OnKeyDownTrigger;
  41731. },
  41732. enumerable: true,
  41733. configurable: true
  41734. });
  41735. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41736. get: function () {
  41737. return ActionManager._OnKeyUpTrigger;
  41738. },
  41739. enumerable: true,
  41740. configurable: true
  41741. });
  41742. // Methods
  41743. ActionManager.prototype.dispose = function () {
  41744. var index = this._scene._actionManagers.indexOf(this);
  41745. for (var i = 0; i < this.actions.length; i++) {
  41746. var action = this.actions[i];
  41747. ActionManager.Triggers[action.trigger]--;
  41748. if (ActionManager.Triggers[action.trigger] === 0) {
  41749. delete ActionManager.Triggers[action.trigger];
  41750. }
  41751. }
  41752. if (index > -1) {
  41753. this._scene._actionManagers.splice(index, 1);
  41754. }
  41755. };
  41756. ActionManager.prototype.getScene = function () {
  41757. return this._scene;
  41758. };
  41759. /**
  41760. * Does this action manager handles actions of any of the given triggers
  41761. * @param {number[]} triggers - the triggers to be tested
  41762. * @return {boolean} whether one (or more) of the triggers is handeled
  41763. */
  41764. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41765. for (var index = 0; index < this.actions.length; index++) {
  41766. var action = this.actions[index];
  41767. if (triggers.indexOf(action.trigger) > -1) {
  41768. return true;
  41769. }
  41770. }
  41771. return false;
  41772. };
  41773. /**
  41774. * Does this action manager handles actions of a given trigger
  41775. * @param {number} trigger - the trigger to be tested
  41776. * @return {boolean} whether the trigger is handeled
  41777. */
  41778. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41779. for (var index = 0; index < this.actions.length; index++) {
  41780. var action = this.actions[index];
  41781. if (action.trigger === trigger) {
  41782. return true;
  41783. }
  41784. }
  41785. return false;
  41786. };
  41787. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41788. /**
  41789. * Does this action manager has pointer triggers
  41790. * @return {boolean} whether or not it has pointer triggers
  41791. */
  41792. get: function () {
  41793. for (var index = 0; index < this.actions.length; index++) {
  41794. var action = this.actions[index];
  41795. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41796. return true;
  41797. }
  41798. }
  41799. return false;
  41800. },
  41801. enumerable: true,
  41802. configurable: true
  41803. });
  41804. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41805. /**
  41806. * Does this action manager has pick triggers
  41807. * @return {boolean} whether or not it has pick triggers
  41808. */
  41809. get: function () {
  41810. for (var index = 0; index < this.actions.length; index++) {
  41811. var action = this.actions[index];
  41812. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41813. return true;
  41814. }
  41815. }
  41816. return false;
  41817. },
  41818. enumerable: true,
  41819. configurable: true
  41820. });
  41821. Object.defineProperty(ActionManager, "HasTriggers", {
  41822. /**
  41823. * Does exist one action manager with at least one trigger
  41824. * @return {boolean} whether or not it exists one action manager with one trigger
  41825. **/
  41826. get: function () {
  41827. for (var t in ActionManager.Triggers) {
  41828. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41829. return true;
  41830. }
  41831. }
  41832. return false;
  41833. },
  41834. enumerable: true,
  41835. configurable: true
  41836. });
  41837. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41838. /**
  41839. * Does exist one action manager with at least one pick trigger
  41840. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41841. **/
  41842. get: function () {
  41843. for (var t in ActionManager.Triggers) {
  41844. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41845. var t_int = parseInt(t);
  41846. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41847. return true;
  41848. }
  41849. }
  41850. }
  41851. return false;
  41852. },
  41853. enumerable: true,
  41854. configurable: true
  41855. });
  41856. /**
  41857. * Does exist one action manager that handles actions of a given trigger
  41858. * @param {number} trigger - the trigger to be tested
  41859. * @return {boolean} whether the trigger is handeled by at least one action manager
  41860. **/
  41861. ActionManager.HasSpecificTrigger = function (trigger) {
  41862. for (var t in ActionManager.Triggers) {
  41863. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41864. var t_int = parseInt(t);
  41865. if (t_int === trigger) {
  41866. return true;
  41867. }
  41868. }
  41869. }
  41870. return false;
  41871. };
  41872. /**
  41873. * Registers an action to this action manager
  41874. * @param {BABYLON.Action} action - the action to be registered
  41875. * @return {BABYLON.Action} the action amended (prepared) after registration
  41876. */
  41877. ActionManager.prototype.registerAction = function (action) {
  41878. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41879. if (this.getScene().actionManager !== this) {
  41880. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41881. return null;
  41882. }
  41883. }
  41884. this.actions.push(action);
  41885. if (ActionManager.Triggers[action.trigger]) {
  41886. ActionManager.Triggers[action.trigger]++;
  41887. }
  41888. else {
  41889. ActionManager.Triggers[action.trigger] = 1;
  41890. }
  41891. action._actionManager = this;
  41892. action._prepare();
  41893. return action;
  41894. };
  41895. /**
  41896. * Process a specific trigger
  41897. * @param {number} trigger - the trigger to process
  41898. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41899. */
  41900. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41901. for (var index = 0; index < this.actions.length; index++) {
  41902. var action = this.actions[index];
  41903. if (action.trigger === trigger) {
  41904. if (evt) {
  41905. if (trigger === ActionManager.OnKeyUpTrigger
  41906. || trigger === ActionManager.OnKeyDownTrigger) {
  41907. var parameter = action.getTriggerParameter();
  41908. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41909. if (!parameter.toLowerCase) {
  41910. continue;
  41911. }
  41912. var lowerCase = parameter.toLowerCase();
  41913. if (lowerCase !== evt.sourceEvent.key) {
  41914. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41915. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41916. if (actualkey !== lowerCase) {
  41917. continue;
  41918. }
  41919. }
  41920. }
  41921. }
  41922. }
  41923. action._executeCurrent(evt);
  41924. }
  41925. }
  41926. };
  41927. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41928. var properties = propertyPath.split(".");
  41929. for (var index = 0; index < properties.length - 1; index++) {
  41930. target = target[properties[index]];
  41931. }
  41932. return target;
  41933. };
  41934. ActionManager.prototype._getProperty = function (propertyPath) {
  41935. var properties = propertyPath.split(".");
  41936. return properties[properties.length - 1];
  41937. };
  41938. ActionManager.prototype.serialize = function (name) {
  41939. var root = {
  41940. children: new Array(),
  41941. name: name,
  41942. type: 3,
  41943. properties: new Array() // Empty for root but required
  41944. };
  41945. for (var i = 0; i < this.actions.length; i++) {
  41946. var triggerObject = {
  41947. type: 0,
  41948. children: new Array(),
  41949. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41950. properties: new Array()
  41951. };
  41952. var triggerOptions = this.actions[i].triggerOptions;
  41953. if (triggerOptions && typeof triggerOptions !== "number") {
  41954. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41955. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  41956. }
  41957. else {
  41958. var parameter = {};
  41959. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  41960. if (triggerOptions.parameter.mesh) {
  41961. parameter._meshId = triggerOptions.parameter.mesh.id;
  41962. }
  41963. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  41964. }
  41965. }
  41966. // Serialize child action, recursively
  41967. this.actions[i].serialize(triggerObject);
  41968. // Add serialized trigger
  41969. root.children.push(triggerObject);
  41970. }
  41971. return root;
  41972. };
  41973. ActionManager.Parse = function (parsedActions, object, scene) {
  41974. var actionManager = new BABYLON.ActionManager(scene);
  41975. if (object === null)
  41976. scene.actionManager = actionManager;
  41977. else
  41978. object.actionManager = actionManager;
  41979. // instanciate a new object
  41980. var instanciate = function (name, params) {
  41981. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  41982. newInstance.constructor.apply(newInstance, params);
  41983. return newInstance;
  41984. };
  41985. var parseParameter = function (name, value, target, propertyPath) {
  41986. if (propertyPath === null) {
  41987. // String, boolean or float
  41988. var floatValue = parseFloat(value);
  41989. if (value === "true" || value === "false")
  41990. return value === "true";
  41991. else
  41992. return isNaN(floatValue) ? value : floatValue;
  41993. }
  41994. var effectiveTarget = propertyPath.split(".");
  41995. var values = value.split(",");
  41996. // Get effective Target
  41997. for (var i = 0; i < effectiveTarget.length; i++) {
  41998. target = target[effectiveTarget[i]];
  41999. }
  42000. // Return appropriate value with its type
  42001. if (typeof (target) === "boolean")
  42002. return values[0] === "true";
  42003. if (typeof (target) === "string")
  42004. return values[0];
  42005. // Parameters with multiple values such as Vector3 etc.
  42006. var split = new Array();
  42007. for (var i = 0; i < values.length; i++)
  42008. split.push(parseFloat(values[i]));
  42009. if (target instanceof BABYLON.Vector3)
  42010. return BABYLON.Vector3.FromArray(split);
  42011. if (target instanceof BABYLON.Vector4)
  42012. return BABYLON.Vector4.FromArray(split);
  42013. if (target instanceof BABYLON.Color3)
  42014. return BABYLON.Color3.FromArray(split);
  42015. if (target instanceof BABYLON.Color4)
  42016. return BABYLON.Color4.FromArray(split);
  42017. return parseFloat(values[0]);
  42018. };
  42019. // traverse graph per trigger
  42020. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42021. if (combineArray === void 0) { combineArray = null; }
  42022. if (parsedAction.detached)
  42023. return;
  42024. var parameters = new Array();
  42025. var target = null;
  42026. var propertyPath = null;
  42027. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42028. // Parameters
  42029. if (parsedAction.type === 2)
  42030. parameters.push(actionManager);
  42031. else
  42032. parameters.push(trigger);
  42033. if (combine) {
  42034. var actions = new Array();
  42035. for (var j = 0; j < parsedAction.combine.length; j++) {
  42036. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42037. }
  42038. parameters.push(actions);
  42039. }
  42040. else {
  42041. for (var i = 0; i < parsedAction.properties.length; i++) {
  42042. var value = parsedAction.properties[i].value;
  42043. var name = parsedAction.properties[i].name;
  42044. var targetType = parsedAction.properties[i].targetType;
  42045. if (name === "target")
  42046. if (targetType !== null && targetType === "SceneProperties")
  42047. value = target = scene;
  42048. else
  42049. value = target = scene.getNodeByName(value);
  42050. else if (name === "parent")
  42051. value = scene.getNodeByName(value);
  42052. else if (name === "sound")
  42053. value = scene.getSoundByName(value);
  42054. else if (name !== "propertyPath") {
  42055. if (parsedAction.type === 2 && name === "operator")
  42056. value = BABYLON.ValueCondition[value];
  42057. else
  42058. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42059. }
  42060. else {
  42061. propertyPath = value;
  42062. }
  42063. parameters.push(value);
  42064. }
  42065. }
  42066. if (combineArray === null) {
  42067. parameters.push(condition);
  42068. }
  42069. else {
  42070. parameters.push(null);
  42071. }
  42072. // If interpolate value action
  42073. if (parsedAction.name === "InterpolateValueAction") {
  42074. var param = parameters[parameters.length - 2];
  42075. parameters[parameters.length - 1] = param;
  42076. parameters[parameters.length - 2] = condition;
  42077. }
  42078. // Action or condition(s) and not CombineAction
  42079. var newAction = instanciate(parsedAction.name, parameters);
  42080. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42081. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42082. if (action)
  42083. action.then(nothing);
  42084. else
  42085. actionManager.registerAction(nothing);
  42086. action = nothing;
  42087. }
  42088. if (combineArray === null) {
  42089. if (newAction instanceof BABYLON.Condition) {
  42090. condition = newAction;
  42091. newAction = action;
  42092. }
  42093. else {
  42094. condition = null;
  42095. if (action)
  42096. action.then(newAction);
  42097. else
  42098. actionManager.registerAction(newAction);
  42099. }
  42100. }
  42101. else {
  42102. combineArray.push(newAction);
  42103. }
  42104. for (var i = 0; i < parsedAction.children.length; i++)
  42105. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42106. };
  42107. // triggers
  42108. for (var i = 0; i < parsedActions.children.length; i++) {
  42109. var triggerParams;
  42110. var trigger = parsedActions.children[i];
  42111. if (trigger.properties.length > 0) {
  42112. var param = trigger.properties[0].value;
  42113. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42114. if (value._meshId) {
  42115. value.mesh = scene.getMeshByID(value._meshId);
  42116. }
  42117. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42118. }
  42119. else
  42120. triggerParams = ActionManager[trigger.name];
  42121. for (var j = 0; j < trigger.children.length; j++) {
  42122. if (!trigger.detached)
  42123. traverse(trigger.children[j], triggerParams, null, null);
  42124. }
  42125. }
  42126. };
  42127. ActionManager.GetTriggerName = function (trigger) {
  42128. switch (trigger) {
  42129. case 0: return "NothingTrigger";
  42130. case 1: return "OnPickTrigger";
  42131. case 2: return "OnLeftPickTrigger";
  42132. case 3: return "OnRightPickTrigger";
  42133. case 4: return "OnCenterPickTrigger";
  42134. case 5: return "OnPickDownTrigger";
  42135. case 6: return "OnPickUpTrigger";
  42136. case 7: return "OnLongPressTrigger";
  42137. case 8: return "OnPointerOverTrigger";
  42138. case 9: return "OnPointerOutTrigger";
  42139. case 10: return "OnEveryFrameTrigger";
  42140. case 11: return "OnIntersectionEnterTrigger";
  42141. case 12: return "OnIntersectionExitTrigger";
  42142. case 13: return "OnKeyDownTrigger";
  42143. case 14: return "OnKeyUpTrigger";
  42144. case 15: return "OnPickOutTrigger";
  42145. default: return "";
  42146. }
  42147. };
  42148. // Statics
  42149. ActionManager._NothingTrigger = 0;
  42150. ActionManager._OnPickTrigger = 1;
  42151. ActionManager._OnLeftPickTrigger = 2;
  42152. ActionManager._OnRightPickTrigger = 3;
  42153. ActionManager._OnCenterPickTrigger = 4;
  42154. ActionManager._OnPickDownTrigger = 5;
  42155. ActionManager._OnDoublePickTrigger = 6;
  42156. ActionManager._OnPickUpTrigger = 7;
  42157. ActionManager._OnLongPressTrigger = 8;
  42158. ActionManager._OnPointerOverTrigger = 9;
  42159. ActionManager._OnPointerOutTrigger = 10;
  42160. ActionManager._OnEveryFrameTrigger = 11;
  42161. ActionManager._OnIntersectionEnterTrigger = 12;
  42162. ActionManager._OnIntersectionExitTrigger = 13;
  42163. ActionManager._OnKeyDownTrigger = 14;
  42164. ActionManager._OnKeyUpTrigger = 15;
  42165. ActionManager._OnPickOutTrigger = 16;
  42166. ActionManager.Triggers = {};
  42167. return ActionManager;
  42168. }());
  42169. BABYLON.ActionManager = ActionManager;
  42170. })(BABYLON || (BABYLON = {}));
  42171. //# sourceMappingURL=babylon.actionManager.js.map
  42172. var BABYLON;
  42173. (function (BABYLON) {
  42174. var InterpolateValueAction = /** @class */ (function (_super) {
  42175. __extends(InterpolateValueAction, _super);
  42176. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42177. if (duration === void 0) { duration = 1000; }
  42178. var _this = _super.call(this, triggerOptions, condition) || this;
  42179. _this.propertyPath = propertyPath;
  42180. _this.value = value;
  42181. _this.duration = duration;
  42182. _this.stopOtherAnimations = stopOtherAnimations;
  42183. _this.onInterpolationDone = onInterpolationDone;
  42184. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42185. _this._target = _this._effectiveTarget = target;
  42186. return _this;
  42187. }
  42188. InterpolateValueAction.prototype._prepare = function () {
  42189. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42190. this._property = this._getProperty(this.propertyPath);
  42191. };
  42192. InterpolateValueAction.prototype.execute = function () {
  42193. var _this = this;
  42194. var scene = this._actionManager.getScene();
  42195. var keys = [
  42196. {
  42197. frame: 0,
  42198. value: this._effectiveTarget[this._property]
  42199. }, {
  42200. frame: 100,
  42201. value: this.value
  42202. }
  42203. ];
  42204. var dataType;
  42205. if (typeof this.value === "number") {
  42206. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42207. }
  42208. else if (this.value instanceof BABYLON.Color3) {
  42209. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42210. }
  42211. else if (this.value instanceof BABYLON.Vector3) {
  42212. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42213. }
  42214. else if (this.value instanceof BABYLON.Matrix) {
  42215. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42216. }
  42217. else if (this.value instanceof BABYLON.Quaternion) {
  42218. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42219. }
  42220. else {
  42221. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42222. return;
  42223. }
  42224. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42225. animation.setKeys(keys);
  42226. if (this.stopOtherAnimations) {
  42227. scene.stopAnimation(this._effectiveTarget);
  42228. }
  42229. var wrapper = function () {
  42230. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42231. if (_this.onInterpolationDone) {
  42232. _this.onInterpolationDone();
  42233. }
  42234. };
  42235. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42236. };
  42237. InterpolateValueAction.prototype.serialize = function (parent) {
  42238. return _super.prototype._serialize.call(this, {
  42239. name: "InterpolateValueAction",
  42240. properties: [
  42241. BABYLON.Action._GetTargetProperty(this._target),
  42242. { name: "propertyPath", value: this.propertyPath },
  42243. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42244. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42245. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42246. ]
  42247. }, parent);
  42248. };
  42249. return InterpolateValueAction;
  42250. }(BABYLON.Action));
  42251. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42252. })(BABYLON || (BABYLON = {}));
  42253. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42254. var BABYLON;
  42255. (function (BABYLON) {
  42256. var SwitchBooleanAction = /** @class */ (function (_super) {
  42257. __extends(SwitchBooleanAction, _super);
  42258. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42259. var _this = _super.call(this, triggerOptions, condition) || this;
  42260. _this.propertyPath = propertyPath;
  42261. _this._target = _this._effectiveTarget = target;
  42262. return _this;
  42263. }
  42264. SwitchBooleanAction.prototype._prepare = function () {
  42265. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42266. this._property = this._getProperty(this.propertyPath);
  42267. };
  42268. SwitchBooleanAction.prototype.execute = function () {
  42269. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42270. };
  42271. SwitchBooleanAction.prototype.serialize = function (parent) {
  42272. return _super.prototype._serialize.call(this, {
  42273. name: "SwitchBooleanAction",
  42274. properties: [
  42275. BABYLON.Action._GetTargetProperty(this._target),
  42276. { name: "propertyPath", value: this.propertyPath }
  42277. ]
  42278. }, parent);
  42279. };
  42280. return SwitchBooleanAction;
  42281. }(BABYLON.Action));
  42282. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42283. var SetStateAction = /** @class */ (function (_super) {
  42284. __extends(SetStateAction, _super);
  42285. function SetStateAction(triggerOptions, target, value, condition) {
  42286. var _this = _super.call(this, triggerOptions, condition) || this;
  42287. _this.value = value;
  42288. _this._target = target;
  42289. return _this;
  42290. }
  42291. SetStateAction.prototype.execute = function () {
  42292. this._target.state = this.value;
  42293. };
  42294. SetStateAction.prototype.serialize = function (parent) {
  42295. return _super.prototype._serialize.call(this, {
  42296. name: "SetStateAction",
  42297. properties: [
  42298. BABYLON.Action._GetTargetProperty(this._target),
  42299. { name: "value", value: this.value }
  42300. ]
  42301. }, parent);
  42302. };
  42303. return SetStateAction;
  42304. }(BABYLON.Action));
  42305. BABYLON.SetStateAction = SetStateAction;
  42306. var SetValueAction = /** @class */ (function (_super) {
  42307. __extends(SetValueAction, _super);
  42308. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42309. var _this = _super.call(this, triggerOptions, condition) || this;
  42310. _this.propertyPath = propertyPath;
  42311. _this.value = value;
  42312. _this._target = _this._effectiveTarget = target;
  42313. return _this;
  42314. }
  42315. SetValueAction.prototype._prepare = function () {
  42316. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42317. this._property = this._getProperty(this.propertyPath);
  42318. };
  42319. SetValueAction.prototype.execute = function () {
  42320. this._effectiveTarget[this._property] = this.value;
  42321. if (this._target.markAsDirty) {
  42322. this._target.markAsDirty(this._property);
  42323. }
  42324. };
  42325. SetValueAction.prototype.serialize = function (parent) {
  42326. return _super.prototype._serialize.call(this, {
  42327. name: "SetValueAction",
  42328. properties: [
  42329. BABYLON.Action._GetTargetProperty(this._target),
  42330. { name: "propertyPath", value: this.propertyPath },
  42331. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42332. ]
  42333. }, parent);
  42334. };
  42335. return SetValueAction;
  42336. }(BABYLON.Action));
  42337. BABYLON.SetValueAction = SetValueAction;
  42338. var IncrementValueAction = /** @class */ (function (_super) {
  42339. __extends(IncrementValueAction, _super);
  42340. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42341. var _this = _super.call(this, triggerOptions, condition) || this;
  42342. _this.propertyPath = propertyPath;
  42343. _this.value = value;
  42344. _this._target = _this._effectiveTarget = target;
  42345. return _this;
  42346. }
  42347. IncrementValueAction.prototype._prepare = function () {
  42348. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42349. this._property = this._getProperty(this.propertyPath);
  42350. if (typeof this._effectiveTarget[this._property] !== "number") {
  42351. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42352. }
  42353. };
  42354. IncrementValueAction.prototype.execute = function () {
  42355. this._effectiveTarget[this._property] += this.value;
  42356. if (this._target.markAsDirty) {
  42357. this._target.markAsDirty(this._property);
  42358. }
  42359. };
  42360. IncrementValueAction.prototype.serialize = function (parent) {
  42361. return _super.prototype._serialize.call(this, {
  42362. name: "IncrementValueAction",
  42363. properties: [
  42364. BABYLON.Action._GetTargetProperty(this._target),
  42365. { name: "propertyPath", value: this.propertyPath },
  42366. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42367. ]
  42368. }, parent);
  42369. };
  42370. return IncrementValueAction;
  42371. }(BABYLON.Action));
  42372. BABYLON.IncrementValueAction = IncrementValueAction;
  42373. var PlayAnimationAction = /** @class */ (function (_super) {
  42374. __extends(PlayAnimationAction, _super);
  42375. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42376. var _this = _super.call(this, triggerOptions, condition) || this;
  42377. _this.from = from;
  42378. _this.to = to;
  42379. _this.loop = loop;
  42380. _this._target = target;
  42381. return _this;
  42382. }
  42383. PlayAnimationAction.prototype._prepare = function () {
  42384. };
  42385. PlayAnimationAction.prototype.execute = function () {
  42386. var scene = this._actionManager.getScene();
  42387. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42388. };
  42389. PlayAnimationAction.prototype.serialize = function (parent) {
  42390. return _super.prototype._serialize.call(this, {
  42391. name: "PlayAnimationAction",
  42392. properties: [
  42393. BABYLON.Action._GetTargetProperty(this._target),
  42394. { name: "from", value: String(this.from) },
  42395. { name: "to", value: String(this.to) },
  42396. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42397. ]
  42398. }, parent);
  42399. };
  42400. return PlayAnimationAction;
  42401. }(BABYLON.Action));
  42402. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42403. var StopAnimationAction = /** @class */ (function (_super) {
  42404. __extends(StopAnimationAction, _super);
  42405. function StopAnimationAction(triggerOptions, target, condition) {
  42406. var _this = _super.call(this, triggerOptions, condition) || this;
  42407. _this._target = target;
  42408. return _this;
  42409. }
  42410. StopAnimationAction.prototype._prepare = function () {
  42411. };
  42412. StopAnimationAction.prototype.execute = function () {
  42413. var scene = this._actionManager.getScene();
  42414. scene.stopAnimation(this._target);
  42415. };
  42416. StopAnimationAction.prototype.serialize = function (parent) {
  42417. return _super.prototype._serialize.call(this, {
  42418. name: "StopAnimationAction",
  42419. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42420. }, parent);
  42421. };
  42422. return StopAnimationAction;
  42423. }(BABYLON.Action));
  42424. BABYLON.StopAnimationAction = StopAnimationAction;
  42425. var DoNothingAction = /** @class */ (function (_super) {
  42426. __extends(DoNothingAction, _super);
  42427. function DoNothingAction(triggerOptions, condition) {
  42428. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42429. return _super.call(this, triggerOptions, condition) || this;
  42430. }
  42431. DoNothingAction.prototype.execute = function () {
  42432. };
  42433. DoNothingAction.prototype.serialize = function (parent) {
  42434. return _super.prototype._serialize.call(this, {
  42435. name: "DoNothingAction",
  42436. properties: []
  42437. }, parent);
  42438. };
  42439. return DoNothingAction;
  42440. }(BABYLON.Action));
  42441. BABYLON.DoNothingAction = DoNothingAction;
  42442. var CombineAction = /** @class */ (function (_super) {
  42443. __extends(CombineAction, _super);
  42444. function CombineAction(triggerOptions, children, condition) {
  42445. var _this = _super.call(this, triggerOptions, condition) || this;
  42446. _this.children = children;
  42447. return _this;
  42448. }
  42449. CombineAction.prototype._prepare = function () {
  42450. for (var index = 0; index < this.children.length; index++) {
  42451. this.children[index]._actionManager = this._actionManager;
  42452. this.children[index]._prepare();
  42453. }
  42454. };
  42455. CombineAction.prototype.execute = function (evt) {
  42456. for (var index = 0; index < this.children.length; index++) {
  42457. this.children[index].execute(evt);
  42458. }
  42459. };
  42460. CombineAction.prototype.serialize = function (parent) {
  42461. var serializationObject = _super.prototype._serialize.call(this, {
  42462. name: "CombineAction",
  42463. properties: [],
  42464. combine: []
  42465. }, parent);
  42466. for (var i = 0; i < this.children.length; i++) {
  42467. serializationObject.combine.push(this.children[i].serialize(null));
  42468. }
  42469. return serializationObject;
  42470. };
  42471. return CombineAction;
  42472. }(BABYLON.Action));
  42473. BABYLON.CombineAction = CombineAction;
  42474. var ExecuteCodeAction = /** @class */ (function (_super) {
  42475. __extends(ExecuteCodeAction, _super);
  42476. function ExecuteCodeAction(triggerOptions, func, condition) {
  42477. var _this = _super.call(this, triggerOptions, condition) || this;
  42478. _this.func = func;
  42479. return _this;
  42480. }
  42481. ExecuteCodeAction.prototype.execute = function (evt) {
  42482. this.func(evt);
  42483. };
  42484. return ExecuteCodeAction;
  42485. }(BABYLON.Action));
  42486. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42487. var SetParentAction = /** @class */ (function (_super) {
  42488. __extends(SetParentAction, _super);
  42489. function SetParentAction(triggerOptions, target, parent, condition) {
  42490. var _this = _super.call(this, triggerOptions, condition) || this;
  42491. _this._target = target;
  42492. _this._parent = parent;
  42493. return _this;
  42494. }
  42495. SetParentAction.prototype._prepare = function () {
  42496. };
  42497. SetParentAction.prototype.execute = function () {
  42498. if (this._target.parent === this._parent) {
  42499. return;
  42500. }
  42501. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42502. invertParentWorldMatrix.invert();
  42503. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42504. this._target.parent = this._parent;
  42505. };
  42506. SetParentAction.prototype.serialize = function (parent) {
  42507. return _super.prototype._serialize.call(this, {
  42508. name: "SetParentAction",
  42509. properties: [
  42510. BABYLON.Action._GetTargetProperty(this._target),
  42511. BABYLON.Action._GetTargetProperty(this._parent),
  42512. ]
  42513. }, parent);
  42514. };
  42515. return SetParentAction;
  42516. }(BABYLON.Action));
  42517. BABYLON.SetParentAction = SetParentAction;
  42518. var PlaySoundAction = /** @class */ (function (_super) {
  42519. __extends(PlaySoundAction, _super);
  42520. function PlaySoundAction(triggerOptions, sound, condition) {
  42521. var _this = _super.call(this, triggerOptions, condition) || this;
  42522. _this._sound = sound;
  42523. return _this;
  42524. }
  42525. PlaySoundAction.prototype._prepare = function () {
  42526. };
  42527. PlaySoundAction.prototype.execute = function () {
  42528. if (this._sound !== undefined)
  42529. this._sound.play();
  42530. };
  42531. PlaySoundAction.prototype.serialize = function (parent) {
  42532. return _super.prototype._serialize.call(this, {
  42533. name: "PlaySoundAction",
  42534. properties: [{ name: "sound", value: this._sound.name }]
  42535. }, parent);
  42536. };
  42537. return PlaySoundAction;
  42538. }(BABYLON.Action));
  42539. BABYLON.PlaySoundAction = PlaySoundAction;
  42540. var StopSoundAction = /** @class */ (function (_super) {
  42541. __extends(StopSoundAction, _super);
  42542. function StopSoundAction(triggerOptions, sound, condition) {
  42543. var _this = _super.call(this, triggerOptions, condition) || this;
  42544. _this._sound = sound;
  42545. return _this;
  42546. }
  42547. StopSoundAction.prototype._prepare = function () {
  42548. };
  42549. StopSoundAction.prototype.execute = function () {
  42550. if (this._sound !== undefined)
  42551. this._sound.stop();
  42552. };
  42553. StopSoundAction.prototype.serialize = function (parent) {
  42554. return _super.prototype._serialize.call(this, {
  42555. name: "StopSoundAction",
  42556. properties: [{ name: "sound", value: this._sound.name }]
  42557. }, parent);
  42558. };
  42559. return StopSoundAction;
  42560. }(BABYLON.Action));
  42561. BABYLON.StopSoundAction = StopSoundAction;
  42562. })(BABYLON || (BABYLON = {}));
  42563. //# sourceMappingURL=babylon.directActions.js.map
  42564. var BABYLON;
  42565. (function (BABYLON) {
  42566. var SpriteManager = /** @class */ (function () {
  42567. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  42568. if (epsilon === void 0) { epsilon = 0.01; }
  42569. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42570. this.name = name;
  42571. this.sprites = new Array();
  42572. this.renderingGroupId = 0;
  42573. this.layerMask = 0x0FFFFFFF;
  42574. this.fogEnabled = true;
  42575. this.isPickable = false;
  42576. /**
  42577. * An event triggered when the manager is disposed.
  42578. * @type {BABYLON.Observable}
  42579. */
  42580. this.onDisposeObservable = new BABYLON.Observable();
  42581. this._vertexBuffers = {};
  42582. this._capacity = capacity;
  42583. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  42584. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42585. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42586. if (cellSize.width && cellSize.height) {
  42587. this.cellWidth = cellSize.width;
  42588. this.cellHeight = cellSize.height;
  42589. }
  42590. else if (cellSize !== undefined) {
  42591. this.cellWidth = cellSize;
  42592. this.cellHeight = cellSize;
  42593. }
  42594. else {
  42595. return;
  42596. }
  42597. this._epsilon = epsilon;
  42598. this._scene = scene;
  42599. this._scene.spriteManagers.push(this);
  42600. var indices = [];
  42601. var index = 0;
  42602. for (var count = 0; count < capacity; count++) {
  42603. indices.push(index);
  42604. indices.push(index + 1);
  42605. indices.push(index + 2);
  42606. indices.push(index);
  42607. indices.push(index + 2);
  42608. indices.push(index + 3);
  42609. index += 4;
  42610. }
  42611. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  42612. // VBO
  42613. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  42614. this._vertexData = new Float32Array(capacity * 16 * 4);
  42615. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  42616. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  42617. var options = this._buffer.createVertexBuffer("options", 4, 4);
  42618. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  42619. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  42620. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42621. this._vertexBuffers["options"] = options;
  42622. this._vertexBuffers["cellInfo"] = cellInfo;
  42623. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42624. // Effects
  42625. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  42626. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  42627. }
  42628. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  42629. set: function (callback) {
  42630. if (this._onDisposeObserver) {
  42631. this.onDisposeObservable.remove(this._onDisposeObserver);
  42632. }
  42633. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42634. },
  42635. enumerable: true,
  42636. configurable: true
  42637. });
  42638. Object.defineProperty(SpriteManager.prototype, "texture", {
  42639. get: function () {
  42640. return this._spriteTexture;
  42641. },
  42642. set: function (value) {
  42643. this._spriteTexture = value;
  42644. },
  42645. enumerable: true,
  42646. configurable: true
  42647. });
  42648. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  42649. var arrayOffset = index * 16;
  42650. if (offsetX === 0)
  42651. offsetX = this._epsilon;
  42652. else if (offsetX === 1)
  42653. offsetX = 1 - this._epsilon;
  42654. if (offsetY === 0)
  42655. offsetY = this._epsilon;
  42656. else if (offsetY === 1)
  42657. offsetY = 1 - this._epsilon;
  42658. this._vertexData[arrayOffset] = sprite.position.x;
  42659. this._vertexData[arrayOffset + 1] = sprite.position.y;
  42660. this._vertexData[arrayOffset + 2] = sprite.position.z;
  42661. this._vertexData[arrayOffset + 3] = sprite.angle;
  42662. this._vertexData[arrayOffset + 4] = sprite.width;
  42663. this._vertexData[arrayOffset + 5] = sprite.height;
  42664. this._vertexData[arrayOffset + 6] = offsetX;
  42665. this._vertexData[arrayOffset + 7] = offsetY;
  42666. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  42667. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  42668. var offset = (sprite.cellIndex / rowSize) >> 0;
  42669. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  42670. this._vertexData[arrayOffset + 11] = offset;
  42671. // Color
  42672. this._vertexData[arrayOffset + 12] = sprite.color.r;
  42673. this._vertexData[arrayOffset + 13] = sprite.color.g;
  42674. this._vertexData[arrayOffset + 14] = sprite.color.b;
  42675. this._vertexData[arrayOffset + 15] = sprite.color.a;
  42676. };
  42677. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  42678. var count = Math.min(this._capacity, this.sprites.length);
  42679. var min = BABYLON.Vector3.Zero();
  42680. var max = BABYLON.Vector3.Zero();
  42681. var distance = Number.MAX_VALUE;
  42682. var currentSprite = null;
  42683. var cameraSpacePosition = BABYLON.Vector3.Zero();
  42684. var cameraView = camera.getViewMatrix();
  42685. for (var index = 0; index < count; index++) {
  42686. var sprite = this.sprites[index];
  42687. if (!sprite) {
  42688. continue;
  42689. }
  42690. if (predicate) {
  42691. if (!predicate(sprite)) {
  42692. continue;
  42693. }
  42694. }
  42695. else if (!sprite.isPickable) {
  42696. continue;
  42697. }
  42698. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  42699. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  42700. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  42701. if (ray.intersectsBoxMinMax(min, max)) {
  42702. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  42703. if (distance > currentDistance) {
  42704. distance = currentDistance;
  42705. currentSprite = sprite;
  42706. if (fastCheck) {
  42707. break;
  42708. }
  42709. }
  42710. }
  42711. }
  42712. if (currentSprite) {
  42713. var result = new BABYLON.PickingInfo();
  42714. result.hit = true;
  42715. result.pickedSprite = currentSprite;
  42716. result.distance = distance;
  42717. return result;
  42718. }
  42719. return null;
  42720. };
  42721. SpriteManager.prototype.render = function () {
  42722. // Check
  42723. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42724. return;
  42725. var engine = this._scene.getEngine();
  42726. var baseSize = this._spriteTexture.getBaseSize();
  42727. // Sprites
  42728. var deltaTime = engine.getDeltaTime();
  42729. var max = Math.min(this._capacity, this.sprites.length);
  42730. var rowSize = baseSize.width / this.cellWidth;
  42731. var offset = 0;
  42732. for (var index = 0; index < max; index++) {
  42733. var sprite = this.sprites[index];
  42734. if (!sprite) {
  42735. continue;
  42736. }
  42737. sprite._animate(deltaTime);
  42738. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42739. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42740. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42741. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42742. }
  42743. this._buffer.update(this._vertexData);
  42744. // Render
  42745. var effect = this._effectBase;
  42746. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42747. effect = this._effectFog;
  42748. }
  42749. engine.enableEffect(effect);
  42750. var viewMatrix = this._scene.getViewMatrix();
  42751. effect.setTexture("diffuseSampler", this._spriteTexture);
  42752. effect.setMatrix("view", viewMatrix);
  42753. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42754. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42755. // Fog
  42756. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42757. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42758. effect.setColor3("vFogColor", this._scene.fogColor);
  42759. }
  42760. // VBOs
  42761. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42762. // Draw order
  42763. engine.setDepthFunctionToLessOrEqual();
  42764. effect.setBool("alphaTest", true);
  42765. engine.setColorWrite(false);
  42766. engine.draw(true, 0, max * 6);
  42767. engine.setColorWrite(true);
  42768. effect.setBool("alphaTest", false);
  42769. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42770. engine.draw(true, 0, max * 6);
  42771. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42772. };
  42773. SpriteManager.prototype.dispose = function () {
  42774. if (this._buffer) {
  42775. this._buffer.dispose();
  42776. this._buffer = null;
  42777. }
  42778. if (this._indexBuffer) {
  42779. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42780. this._indexBuffer = null;
  42781. }
  42782. if (this._spriteTexture) {
  42783. this._spriteTexture.dispose();
  42784. this._spriteTexture = null;
  42785. }
  42786. // Remove from scene
  42787. var index = this._scene.spriteManagers.indexOf(this);
  42788. this._scene.spriteManagers.splice(index, 1);
  42789. // Callback
  42790. this.onDisposeObservable.notifyObservers(this);
  42791. this.onDisposeObservable.clear();
  42792. };
  42793. return SpriteManager;
  42794. }());
  42795. BABYLON.SpriteManager = SpriteManager;
  42796. })(BABYLON || (BABYLON = {}));
  42797. //# sourceMappingURL=babylon.spriteManager.js.map
  42798. var BABYLON;
  42799. (function (BABYLON) {
  42800. var Sprite = /** @class */ (function () {
  42801. function Sprite(name, manager) {
  42802. this.name = name;
  42803. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42804. this.width = 1.0;
  42805. this.height = 1.0;
  42806. this.angle = 0;
  42807. this.cellIndex = 0;
  42808. this.invertU = 0;
  42809. this.invertV = 0;
  42810. this.animations = new Array();
  42811. this.isPickable = false;
  42812. this._animationStarted = false;
  42813. this._loopAnimation = false;
  42814. this._fromIndex = 0;
  42815. this._toIndex = 0;
  42816. this._delay = 0;
  42817. this._direction = 1;
  42818. this._time = 0;
  42819. this._manager = manager;
  42820. this._manager.sprites.push(this);
  42821. this.position = BABYLON.Vector3.Zero();
  42822. }
  42823. Object.defineProperty(Sprite.prototype, "size", {
  42824. get: function () {
  42825. return this.width;
  42826. },
  42827. set: function (value) {
  42828. this.width = value;
  42829. this.height = value;
  42830. },
  42831. enumerable: true,
  42832. configurable: true
  42833. });
  42834. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  42835. this._fromIndex = from;
  42836. this._toIndex = to;
  42837. this._loopAnimation = loop;
  42838. this._delay = delay;
  42839. this._animationStarted = true;
  42840. this._direction = from < to ? 1 : -1;
  42841. this.cellIndex = from;
  42842. this._time = 0;
  42843. this._onAnimationEnd = onAnimationEnd;
  42844. };
  42845. Sprite.prototype.stopAnimation = function () {
  42846. this._animationStarted = false;
  42847. };
  42848. Sprite.prototype._animate = function (deltaTime) {
  42849. if (!this._animationStarted)
  42850. return;
  42851. this._time += deltaTime;
  42852. if (this._time > this._delay) {
  42853. this._time = this._time % this._delay;
  42854. this.cellIndex += this._direction;
  42855. if (this.cellIndex > this._toIndex) {
  42856. if (this._loopAnimation) {
  42857. this.cellIndex = this._fromIndex;
  42858. }
  42859. else {
  42860. this.cellIndex = this._toIndex;
  42861. this._animationStarted = false;
  42862. if (this._onAnimationEnd) {
  42863. this._onAnimationEnd();
  42864. }
  42865. if (this.disposeWhenFinishedAnimating) {
  42866. this.dispose();
  42867. }
  42868. }
  42869. }
  42870. }
  42871. };
  42872. Sprite.prototype.dispose = function () {
  42873. for (var i = 0; i < this._manager.sprites.length; i++) {
  42874. if (this._manager.sprites[i] == this) {
  42875. this._manager.sprites.splice(i, 1);
  42876. }
  42877. }
  42878. };
  42879. return Sprite;
  42880. }());
  42881. BABYLON.Sprite = Sprite;
  42882. })(BABYLON || (BABYLON = {}));
  42883. //# sourceMappingURL=babylon.sprite.js.map
  42884. var BABYLON;
  42885. (function (BABYLON) {
  42886. var IntersectionInfo = /** @class */ (function () {
  42887. function IntersectionInfo(bu, bv, distance) {
  42888. this.bu = bu;
  42889. this.bv = bv;
  42890. this.distance = distance;
  42891. this.faceId = 0;
  42892. this.subMeshId = 0;
  42893. }
  42894. return IntersectionInfo;
  42895. }());
  42896. BABYLON.IntersectionInfo = IntersectionInfo;
  42897. var PickingInfo = /** @class */ (function () {
  42898. function PickingInfo() {
  42899. this.hit = false;
  42900. this.distance = 0;
  42901. this.pickedPoint = null;
  42902. this.pickedMesh = null;
  42903. this.bu = 0;
  42904. this.bv = 0;
  42905. this.faceId = -1;
  42906. this.subMeshId = 0;
  42907. this.pickedSprite = null;
  42908. }
  42909. // Methods
  42910. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  42911. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  42912. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  42913. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42914. return null;
  42915. }
  42916. var indices = this.pickedMesh.getIndices();
  42917. if (!indices) {
  42918. return null;
  42919. }
  42920. var result;
  42921. if (useVerticesNormals) {
  42922. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42923. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  42924. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  42925. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  42926. normal0 = normal0.scale(this.bu);
  42927. normal1 = normal1.scale(this.bv);
  42928. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  42929. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  42930. }
  42931. else {
  42932. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42933. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  42934. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  42935. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  42936. var p1p2 = vertex1.subtract(vertex2);
  42937. var p3p2 = vertex3.subtract(vertex2);
  42938. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  42939. }
  42940. if (useWorldCoordinates) {
  42941. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  42942. }
  42943. return BABYLON.Vector3.Normalize(result);
  42944. };
  42945. PickingInfo.prototype.getTextureCoordinates = function () {
  42946. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42947. return null;
  42948. }
  42949. var indices = this.pickedMesh.getIndices();
  42950. if (!indices) {
  42951. return null;
  42952. }
  42953. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42954. if (!uvs) {
  42955. return null;
  42956. }
  42957. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  42958. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  42959. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  42960. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  42961. uv1 = uv1.scale(this.bu);
  42962. uv2 = uv2.scale(this.bv);
  42963. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  42964. };
  42965. return PickingInfo;
  42966. }());
  42967. BABYLON.PickingInfo = PickingInfo;
  42968. })(BABYLON || (BABYLON = {}));
  42969. //# sourceMappingURL=babylon.pickingInfo.js.map
  42970. var BABYLON;
  42971. (function (BABYLON) {
  42972. var Ray = /** @class */ (function () {
  42973. function Ray(origin, direction, length) {
  42974. if (length === void 0) { length = Number.MAX_VALUE; }
  42975. this.origin = origin;
  42976. this.direction = direction;
  42977. this.length = length;
  42978. }
  42979. // Methods
  42980. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  42981. var d = 0.0;
  42982. var maxValue = Number.MAX_VALUE;
  42983. var inv;
  42984. var min;
  42985. var max;
  42986. var temp;
  42987. if (Math.abs(this.direction.x) < 0.0000001) {
  42988. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  42989. return false;
  42990. }
  42991. }
  42992. else {
  42993. inv = 1.0 / this.direction.x;
  42994. min = (minimum.x - this.origin.x) * inv;
  42995. max = (maximum.x - this.origin.x) * inv;
  42996. if (max === -Infinity) {
  42997. max = Infinity;
  42998. }
  42999. if (min > max) {
  43000. temp = min;
  43001. min = max;
  43002. max = temp;
  43003. }
  43004. d = Math.max(min, d);
  43005. maxValue = Math.min(max, maxValue);
  43006. if (d > maxValue) {
  43007. return false;
  43008. }
  43009. }
  43010. if (Math.abs(this.direction.y) < 0.0000001) {
  43011. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43012. return false;
  43013. }
  43014. }
  43015. else {
  43016. inv = 1.0 / this.direction.y;
  43017. min = (minimum.y - this.origin.y) * inv;
  43018. max = (maximum.y - this.origin.y) * inv;
  43019. if (max === -Infinity) {
  43020. max = Infinity;
  43021. }
  43022. if (min > max) {
  43023. temp = min;
  43024. min = max;
  43025. max = temp;
  43026. }
  43027. d = Math.max(min, d);
  43028. maxValue = Math.min(max, maxValue);
  43029. if (d > maxValue) {
  43030. return false;
  43031. }
  43032. }
  43033. if (Math.abs(this.direction.z) < 0.0000001) {
  43034. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43035. return false;
  43036. }
  43037. }
  43038. else {
  43039. inv = 1.0 / this.direction.z;
  43040. min = (minimum.z - this.origin.z) * inv;
  43041. max = (maximum.z - this.origin.z) * inv;
  43042. if (max === -Infinity) {
  43043. max = Infinity;
  43044. }
  43045. if (min > max) {
  43046. temp = min;
  43047. min = max;
  43048. max = temp;
  43049. }
  43050. d = Math.max(min, d);
  43051. maxValue = Math.min(max, maxValue);
  43052. if (d > maxValue) {
  43053. return false;
  43054. }
  43055. }
  43056. return true;
  43057. };
  43058. Ray.prototype.intersectsBox = function (box) {
  43059. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43060. };
  43061. Ray.prototype.intersectsSphere = function (sphere) {
  43062. var x = sphere.center.x - this.origin.x;
  43063. var y = sphere.center.y - this.origin.y;
  43064. var z = sphere.center.z - this.origin.z;
  43065. var pyth = (x * x) + (y * y) + (z * z);
  43066. var rr = sphere.radius * sphere.radius;
  43067. if (pyth <= rr) {
  43068. return true;
  43069. }
  43070. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43071. if (dot < 0.0) {
  43072. return false;
  43073. }
  43074. var temp = pyth - (dot * dot);
  43075. return temp <= rr;
  43076. };
  43077. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43078. if (!this._edge1) {
  43079. this._edge1 = BABYLON.Vector3.Zero();
  43080. this._edge2 = BABYLON.Vector3.Zero();
  43081. this._pvec = BABYLON.Vector3.Zero();
  43082. this._tvec = BABYLON.Vector3.Zero();
  43083. this._qvec = BABYLON.Vector3.Zero();
  43084. }
  43085. vertex1.subtractToRef(vertex0, this._edge1);
  43086. vertex2.subtractToRef(vertex0, this._edge2);
  43087. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43088. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43089. if (det === 0) {
  43090. return null;
  43091. }
  43092. var invdet = 1 / det;
  43093. this.origin.subtractToRef(vertex0, this._tvec);
  43094. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43095. if (bu < 0 || bu > 1.0) {
  43096. return null;
  43097. }
  43098. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43099. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43100. if (bv < 0 || bu + bv > 1.0) {
  43101. return null;
  43102. }
  43103. //check if the distance is longer than the predefined length.
  43104. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43105. if (distance > this.length) {
  43106. return null;
  43107. }
  43108. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43109. };
  43110. Ray.prototype.intersectsPlane = function (plane) {
  43111. var distance;
  43112. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43113. if (Math.abs(result1) < 9.99999997475243E-07) {
  43114. return null;
  43115. }
  43116. else {
  43117. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43118. distance = (-plane.d - result2) / result1;
  43119. if (distance < 0.0) {
  43120. if (distance < -9.99999997475243E-07) {
  43121. return null;
  43122. }
  43123. else {
  43124. return 0;
  43125. }
  43126. }
  43127. return distance;
  43128. }
  43129. };
  43130. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43131. var tm = BABYLON.Tmp.Matrix[0];
  43132. mesh.getWorldMatrix().invertToRef(tm);
  43133. if (this._tmpRay) {
  43134. Ray.TransformToRef(this, tm, this._tmpRay);
  43135. }
  43136. else {
  43137. this._tmpRay = Ray.Transform(this, tm);
  43138. }
  43139. return mesh.intersects(this._tmpRay, fastCheck);
  43140. };
  43141. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43142. if (results) {
  43143. results.length = 0;
  43144. }
  43145. else {
  43146. results = [];
  43147. }
  43148. for (var i = 0; i < meshes.length; i++) {
  43149. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43150. if (pickInfo.hit) {
  43151. results.push(pickInfo);
  43152. }
  43153. }
  43154. results.sort(this._comparePickingInfo);
  43155. return results;
  43156. };
  43157. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43158. if (pickingInfoA.distance < pickingInfoB.distance) {
  43159. return -1;
  43160. }
  43161. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43162. return 1;
  43163. }
  43164. else {
  43165. return 0;
  43166. }
  43167. };
  43168. /**
  43169. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43170. * @param sega the first point of the segment to test the intersection against
  43171. * @param segb the second point of the segment to test the intersection against
  43172. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43173. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43174. */
  43175. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43176. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43177. var u = segb.subtract(sega);
  43178. var v = rsegb.subtract(this.origin);
  43179. var w = sega.subtract(this.origin);
  43180. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43181. var b = BABYLON.Vector3.Dot(u, v);
  43182. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43183. var d = BABYLON.Vector3.Dot(u, w);
  43184. var e = BABYLON.Vector3.Dot(v, w);
  43185. var D = a * c - b * b; // always >= 0
  43186. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43187. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43188. // compute the line parameters of the two closest points
  43189. if (D < Ray.smallnum) {
  43190. sN = 0.0; // force using point P0 on segment S1
  43191. sD = 1.0; // to prevent possible division by 0.0 later
  43192. tN = e;
  43193. tD = c;
  43194. }
  43195. else {
  43196. sN = (b * e - c * d);
  43197. tN = (a * e - b * d);
  43198. if (sN < 0.0) {
  43199. sN = 0.0;
  43200. tN = e;
  43201. tD = c;
  43202. }
  43203. else if (sN > sD) {
  43204. sN = sD;
  43205. tN = e + b;
  43206. tD = c;
  43207. }
  43208. }
  43209. if (tN < 0.0) {
  43210. tN = 0.0;
  43211. // recompute sc for this edge
  43212. if (-d < 0.0) {
  43213. sN = 0.0;
  43214. }
  43215. else if (-d > a)
  43216. sN = sD;
  43217. else {
  43218. sN = -d;
  43219. sD = a;
  43220. }
  43221. }
  43222. else if (tN > tD) {
  43223. tN = tD;
  43224. // recompute sc for this edge
  43225. if ((-d + b) < 0.0) {
  43226. sN = 0;
  43227. }
  43228. else if ((-d + b) > a) {
  43229. sN = sD;
  43230. }
  43231. else {
  43232. sN = (-d + b);
  43233. sD = a;
  43234. }
  43235. }
  43236. // finally do the division to get sc and tc
  43237. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43238. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43239. // get the difference of the two closest points
  43240. var qtc = v.multiplyByFloats(tc, tc, tc);
  43241. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43242. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43243. if (isIntersected) {
  43244. return qtc.length();
  43245. }
  43246. return -1;
  43247. };
  43248. // Statics
  43249. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43250. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  43251. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  43252. var direction = end.subtract(start);
  43253. direction.normalize();
  43254. return new Ray(start, direction);
  43255. };
  43256. /**
  43257. * 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
  43258. * transformed to the given world matrix.
  43259. * @param origin The origin point
  43260. * @param end The end point
  43261. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43262. */
  43263. Ray.CreateNewFromTo = function (origin, end, world) {
  43264. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43265. var direction = end.subtract(origin);
  43266. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43267. direction.normalize();
  43268. return Ray.Transform(new Ray(origin, direction, length), world);
  43269. };
  43270. Ray.Transform = function (ray, matrix) {
  43271. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43272. Ray.TransformToRef(ray, matrix, result);
  43273. return result;
  43274. };
  43275. Ray.TransformToRef = function (ray, matrix, result) {
  43276. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43277. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43278. result.length = ray.length;
  43279. var dir = result.direction;
  43280. var len = dir.length();
  43281. if (!(len === 0 || len === 1)) {
  43282. var num = 1.0 / len;
  43283. dir.x *= num;
  43284. dir.y *= num;
  43285. dir.z *= num;
  43286. result.length *= len;
  43287. }
  43288. };
  43289. Ray.smallnum = 0.00000001;
  43290. Ray.rayl = 10e8;
  43291. return Ray;
  43292. }());
  43293. BABYLON.Ray = Ray;
  43294. })(BABYLON || (BABYLON = {}));
  43295. //# sourceMappingURL=babylon.ray.js.map
  43296. var BABYLON;
  43297. (function (BABYLON) {
  43298. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43299. if (boxMin.x > sphereCenter.x + sphereRadius)
  43300. return false;
  43301. if (sphereCenter.x - sphereRadius > boxMax.x)
  43302. return false;
  43303. if (boxMin.y > sphereCenter.y + sphereRadius)
  43304. return false;
  43305. if (sphereCenter.y - sphereRadius > boxMax.y)
  43306. return false;
  43307. if (boxMin.z > sphereCenter.z + sphereRadius)
  43308. return false;
  43309. if (sphereCenter.z - sphereRadius > boxMax.z)
  43310. return false;
  43311. return true;
  43312. };
  43313. var getLowestRoot = (function () {
  43314. var result = { root: 0, found: false };
  43315. return function (a, b, c, maxR) {
  43316. result.root = 0;
  43317. result.found = false;
  43318. var determinant = b * b - 4.0 * a * c;
  43319. if (determinant < 0)
  43320. return result;
  43321. var sqrtD = Math.sqrt(determinant);
  43322. var r1 = (-b - sqrtD) / (2.0 * a);
  43323. var r2 = (-b + sqrtD) / (2.0 * a);
  43324. if (r1 > r2) {
  43325. var temp = r2;
  43326. r2 = r1;
  43327. r1 = temp;
  43328. }
  43329. if (r1 > 0 && r1 < maxR) {
  43330. result.root = r1;
  43331. result.found = true;
  43332. return result;
  43333. }
  43334. if (r2 > 0 && r2 < maxR) {
  43335. result.root = r2;
  43336. result.found = true;
  43337. return result;
  43338. }
  43339. return result;
  43340. };
  43341. })();
  43342. var Collider = /** @class */ (function () {
  43343. function Collider() {
  43344. this.radius = BABYLON.Vector3.One();
  43345. this.retry = 0;
  43346. this.basePointWorld = BABYLON.Vector3.Zero();
  43347. this.velocityWorld = BABYLON.Vector3.Zero();
  43348. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43349. this._collisionPoint = BABYLON.Vector3.Zero();
  43350. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43351. this._tempVector = BABYLON.Vector3.Zero();
  43352. this._tempVector2 = BABYLON.Vector3.Zero();
  43353. this._tempVector3 = BABYLON.Vector3.Zero();
  43354. this._tempVector4 = BABYLON.Vector3.Zero();
  43355. this._edge = BABYLON.Vector3.Zero();
  43356. this._baseToVertex = BABYLON.Vector3.Zero();
  43357. this._destinationPoint = BABYLON.Vector3.Zero();
  43358. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43359. this._displacementVector = BABYLON.Vector3.Zero();
  43360. this._collisionMask = -1;
  43361. }
  43362. Object.defineProperty(Collider.prototype, "collisionMask", {
  43363. get: function () {
  43364. return this._collisionMask;
  43365. },
  43366. set: function (mask) {
  43367. this._collisionMask = !isNaN(mask) ? mask : -1;
  43368. },
  43369. enumerable: true,
  43370. configurable: true
  43371. });
  43372. // Methods
  43373. Collider.prototype._initialize = function (source, dir, e) {
  43374. this.velocity = dir;
  43375. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43376. this.basePoint = source;
  43377. source.multiplyToRef(this.radius, this.basePointWorld);
  43378. dir.multiplyToRef(this.radius, this.velocityWorld);
  43379. this.velocityWorldLength = this.velocityWorld.length();
  43380. this.epsilon = e;
  43381. this.collisionFound = false;
  43382. };
  43383. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43384. pa.subtractToRef(point, this._tempVector);
  43385. pb.subtractToRef(point, this._tempVector2);
  43386. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43387. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43388. if (d < 0)
  43389. return false;
  43390. pc.subtractToRef(point, this._tempVector3);
  43391. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43392. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43393. if (d < 0)
  43394. return false;
  43395. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43396. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43397. return d >= 0;
  43398. };
  43399. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43400. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43401. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43402. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43403. return false;
  43404. }
  43405. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43406. return false;
  43407. return true;
  43408. };
  43409. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43410. var t0;
  43411. var embeddedInPlane = false;
  43412. //defensive programming, actually not needed.
  43413. if (!trianglePlaneArray) {
  43414. trianglePlaneArray = [];
  43415. }
  43416. if (!trianglePlaneArray[faceIndex]) {
  43417. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43418. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43419. }
  43420. var trianglePlane = trianglePlaneArray[faceIndex];
  43421. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43422. return;
  43423. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43424. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43425. if (normalDotVelocity == 0) {
  43426. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43427. return;
  43428. embeddedInPlane = true;
  43429. t0 = 0;
  43430. }
  43431. else {
  43432. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43433. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43434. if (t0 > t1) {
  43435. var temp = t1;
  43436. t1 = t0;
  43437. t0 = temp;
  43438. }
  43439. if (t0 > 1.0 || t1 < 0.0)
  43440. return;
  43441. if (t0 < 0)
  43442. t0 = 0;
  43443. if (t0 > 1.0)
  43444. t0 = 1.0;
  43445. }
  43446. this._collisionPoint.copyFromFloats(0, 0, 0);
  43447. var found = false;
  43448. var t = 1.0;
  43449. if (!embeddedInPlane) {
  43450. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43451. this.velocity.scaleToRef(t0, this._tempVector);
  43452. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43453. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43454. found = true;
  43455. t = t0;
  43456. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43457. }
  43458. }
  43459. if (!found) {
  43460. var velocitySquaredLength = this.velocity.lengthSquared();
  43461. var a = velocitySquaredLength;
  43462. this.basePoint.subtractToRef(p1, this._tempVector);
  43463. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43464. var c = this._tempVector.lengthSquared() - 1.0;
  43465. var lowestRoot = getLowestRoot(a, b, c, t);
  43466. if (lowestRoot.found) {
  43467. t = lowestRoot.root;
  43468. found = true;
  43469. this._collisionPoint.copyFrom(p1);
  43470. }
  43471. this.basePoint.subtractToRef(p2, this._tempVector);
  43472. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43473. c = this._tempVector.lengthSquared() - 1.0;
  43474. lowestRoot = getLowestRoot(a, b, c, t);
  43475. if (lowestRoot.found) {
  43476. t = lowestRoot.root;
  43477. found = true;
  43478. this._collisionPoint.copyFrom(p2);
  43479. }
  43480. this.basePoint.subtractToRef(p3, this._tempVector);
  43481. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43482. c = this._tempVector.lengthSquared() - 1.0;
  43483. lowestRoot = getLowestRoot(a, b, c, t);
  43484. if (lowestRoot.found) {
  43485. t = lowestRoot.root;
  43486. found = true;
  43487. this._collisionPoint.copyFrom(p3);
  43488. }
  43489. p2.subtractToRef(p1, this._edge);
  43490. p1.subtractToRef(this.basePoint, this._baseToVertex);
  43491. var edgeSquaredLength = this._edge.lengthSquared();
  43492. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43493. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43494. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43495. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43496. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43497. lowestRoot = getLowestRoot(a, b, c, t);
  43498. if (lowestRoot.found) {
  43499. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43500. if (f >= 0.0 && f <= 1.0) {
  43501. t = lowestRoot.root;
  43502. found = true;
  43503. this._edge.scaleInPlace(f);
  43504. p1.addToRef(this._edge, this._collisionPoint);
  43505. }
  43506. }
  43507. p3.subtractToRef(p2, this._edge);
  43508. p2.subtractToRef(this.basePoint, this._baseToVertex);
  43509. edgeSquaredLength = this._edge.lengthSquared();
  43510. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43511. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43512. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43513. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43514. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43515. lowestRoot = getLowestRoot(a, b, c, t);
  43516. if (lowestRoot.found) {
  43517. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43518. if (f >= 0.0 && f <= 1.0) {
  43519. t = lowestRoot.root;
  43520. found = true;
  43521. this._edge.scaleInPlace(f);
  43522. p2.addToRef(this._edge, this._collisionPoint);
  43523. }
  43524. }
  43525. p1.subtractToRef(p3, this._edge);
  43526. p3.subtractToRef(this.basePoint, this._baseToVertex);
  43527. edgeSquaredLength = this._edge.lengthSquared();
  43528. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43529. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43530. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43531. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43532. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43533. lowestRoot = getLowestRoot(a, b, c, t);
  43534. if (lowestRoot.found) {
  43535. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43536. if (f >= 0.0 && f <= 1.0) {
  43537. t = lowestRoot.root;
  43538. found = true;
  43539. this._edge.scaleInPlace(f);
  43540. p3.addToRef(this._edge, this._collisionPoint);
  43541. }
  43542. }
  43543. }
  43544. if (found) {
  43545. var distToCollision = t * this.velocity.length();
  43546. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  43547. if (!this.intersectionPoint) {
  43548. this.intersectionPoint = this._collisionPoint.clone();
  43549. }
  43550. else {
  43551. this.intersectionPoint.copyFrom(this._collisionPoint);
  43552. }
  43553. this.nearestDistance = distToCollision;
  43554. this.collisionFound = true;
  43555. }
  43556. }
  43557. };
  43558. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  43559. for (var i = indexStart; i < indexEnd; i += 3) {
  43560. var p1 = pts[indices[i] - decal];
  43561. var p2 = pts[indices[i + 1] - decal];
  43562. var p3 = pts[indices[i + 2] - decal];
  43563. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  43564. }
  43565. };
  43566. Collider.prototype._getResponse = function (pos, vel) {
  43567. pos.addToRef(vel, this._destinationPoint);
  43568. vel.scaleInPlace((this.nearestDistance / vel.length()));
  43569. this.basePoint.addToRef(vel, pos);
  43570. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  43571. this._slidePlaneNormal.normalize();
  43572. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  43573. pos.addInPlace(this._displacementVector);
  43574. this.intersectionPoint.addInPlace(this._displacementVector);
  43575. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  43576. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  43577. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  43578. };
  43579. return Collider;
  43580. }());
  43581. BABYLON.Collider = Collider;
  43582. })(BABYLON || (BABYLON = {}));
  43583. //# sourceMappingURL=babylon.collider.js.map
  43584. var BABYLON;
  43585. (function (BABYLON) {
  43586. //WebWorker code will be inserted to this variable.
  43587. BABYLON.CollisionWorker = "";
  43588. var WorkerTaskType;
  43589. (function (WorkerTaskType) {
  43590. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  43591. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  43592. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  43593. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  43594. var WorkerReplyType;
  43595. (function (WorkerReplyType) {
  43596. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  43597. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  43598. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  43599. var CollisionCoordinatorWorker = /** @class */ (function () {
  43600. function CollisionCoordinatorWorker() {
  43601. var _this = this;
  43602. this._scaledPosition = BABYLON.Vector3.Zero();
  43603. this._scaledVelocity = BABYLON.Vector3.Zero();
  43604. this.onMeshUpdated = function (mesh) {
  43605. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  43606. };
  43607. this.onGeometryUpdated = function (geometry) {
  43608. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  43609. };
  43610. this._afterRender = function () {
  43611. if (!_this._init)
  43612. return;
  43613. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  43614. return;
  43615. }
  43616. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  43617. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  43618. if (_this._runningUpdated > 4) {
  43619. return;
  43620. }
  43621. ++_this._runningUpdated;
  43622. var payload = {
  43623. updatedMeshes: _this._addUpdateMeshesList,
  43624. updatedGeometries: _this._addUpdateGeometriesList,
  43625. removedGeometries: _this._toRemoveGeometryArray,
  43626. removedMeshes: _this._toRemoveMeshesArray
  43627. };
  43628. var message = {
  43629. payload: payload,
  43630. taskType: WorkerTaskType.UPDATE
  43631. };
  43632. var serializable = [];
  43633. for (var id in payload.updatedGeometries) {
  43634. if (payload.updatedGeometries.hasOwnProperty(id)) {
  43635. //prepare transferables
  43636. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  43637. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  43638. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  43639. }
  43640. }
  43641. _this._worker.postMessage(message, serializable);
  43642. _this._addUpdateMeshesList = {};
  43643. _this._addUpdateGeometriesList = {};
  43644. _this._toRemoveGeometryArray = [];
  43645. _this._toRemoveMeshesArray = [];
  43646. };
  43647. this._onMessageFromWorker = function (e) {
  43648. var returnData = e.data;
  43649. if (returnData.error != WorkerReplyType.SUCCESS) {
  43650. //TODO what errors can be returned from the worker?
  43651. BABYLON.Tools.Warn("error returned from worker!");
  43652. return;
  43653. }
  43654. switch (returnData.taskType) {
  43655. case WorkerTaskType.INIT:
  43656. _this._init = true;
  43657. //Update the worked with ALL of the scene's current state
  43658. _this._scene.meshes.forEach(function (mesh) {
  43659. _this.onMeshAdded(mesh);
  43660. });
  43661. _this._scene.getGeometries().forEach(function (geometry) {
  43662. _this.onGeometryAdded(geometry);
  43663. });
  43664. break;
  43665. case WorkerTaskType.UPDATE:
  43666. _this._runningUpdated--;
  43667. break;
  43668. case WorkerTaskType.COLLIDE:
  43669. _this._runningCollisionTask = false;
  43670. var returnPayload = returnData.payload;
  43671. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  43672. return;
  43673. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  43674. if (callback) {
  43675. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  43676. if (mesh) {
  43677. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  43678. }
  43679. }
  43680. //cleanup
  43681. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  43682. break;
  43683. }
  43684. };
  43685. this._collisionsCallbackArray = [];
  43686. this._init = false;
  43687. this._runningUpdated = 0;
  43688. this._runningCollisionTask = false;
  43689. this._addUpdateMeshesList = {};
  43690. this._addUpdateGeometriesList = {};
  43691. this._toRemoveGeometryArray = [];
  43692. this._toRemoveMeshesArray = [];
  43693. }
  43694. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43695. if (!this._init)
  43696. return;
  43697. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  43698. return;
  43699. position.divideToRef(collider.radius, this._scaledPosition);
  43700. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43701. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  43702. var payload = {
  43703. collider: {
  43704. position: this._scaledPosition.asArray(),
  43705. velocity: this._scaledVelocity.asArray(),
  43706. radius: collider.radius.asArray()
  43707. },
  43708. collisionId: collisionIndex,
  43709. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43710. maximumRetry: maximumRetry
  43711. };
  43712. var message = {
  43713. payload: payload,
  43714. taskType: WorkerTaskType.COLLIDE
  43715. };
  43716. this._worker.postMessage(message);
  43717. };
  43718. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43719. this._scene = scene;
  43720. this._scene.registerAfterRender(this._afterRender);
  43721. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43722. this._worker = new Worker(workerUrl);
  43723. this._worker.onmessage = this._onMessageFromWorker;
  43724. var message = {
  43725. payload: {},
  43726. taskType: WorkerTaskType.INIT
  43727. };
  43728. this._worker.postMessage(message);
  43729. };
  43730. CollisionCoordinatorWorker.prototype.destroy = function () {
  43731. this._scene.unregisterAfterRender(this._afterRender);
  43732. this._worker.terminate();
  43733. };
  43734. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43735. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43736. this.onMeshUpdated(mesh);
  43737. };
  43738. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43739. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43740. };
  43741. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43742. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43743. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43744. this.onGeometryUpdated(geometry);
  43745. };
  43746. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43747. this._toRemoveGeometryArray.push(geometry.id);
  43748. };
  43749. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43750. var submeshes = [];
  43751. if (mesh.subMeshes) {
  43752. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43753. var boundingInfo = sm.getBoundingInfo();
  43754. return {
  43755. position: idx,
  43756. verticesStart: sm.verticesStart,
  43757. verticesCount: sm.verticesCount,
  43758. indexStart: sm.indexStart,
  43759. indexCount: sm.indexCount,
  43760. hasMaterial: !!sm.getMaterial(),
  43761. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43762. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43763. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43764. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  43765. };
  43766. });
  43767. }
  43768. var geometryId = null;
  43769. if (mesh instanceof BABYLON.Mesh) {
  43770. var geometry = mesh.geometry;
  43771. geometryId = geometry ? geometry.id : null;
  43772. }
  43773. else if (mesh instanceof BABYLON.InstancedMesh) {
  43774. var geometry = mesh.sourceMesh.geometry;
  43775. geometryId = geometry ? geometry.id : null;
  43776. }
  43777. var boundingInfo = mesh.getBoundingInfo();
  43778. return {
  43779. uniqueId: mesh.uniqueId,
  43780. id: mesh.id,
  43781. name: mesh.name,
  43782. geometryId: geometryId,
  43783. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43784. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43785. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43786. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  43787. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43788. subMeshes: submeshes,
  43789. checkCollisions: mesh.checkCollisions
  43790. };
  43791. };
  43792. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43793. return {
  43794. id: geometry.id,
  43795. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43796. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43797. indices: new Uint32Array(geometry.getIndices() || []),
  43798. };
  43799. };
  43800. return CollisionCoordinatorWorker;
  43801. }());
  43802. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43803. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43804. function CollisionCoordinatorLegacy() {
  43805. this._scaledPosition = BABYLON.Vector3.Zero();
  43806. this._scaledVelocity = BABYLON.Vector3.Zero();
  43807. this._finalPosition = BABYLON.Vector3.Zero();
  43808. }
  43809. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43810. position.divideToRef(collider.radius, this._scaledPosition);
  43811. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43812. collider.collidedMesh = null;
  43813. collider.retry = 0;
  43814. collider.initialVelocity = this._scaledVelocity;
  43815. collider.initialPosition = this._scaledPosition;
  43816. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  43817. this._finalPosition.multiplyInPlace(collider.radius);
  43818. //run the callback
  43819. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  43820. };
  43821. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  43822. this._scene = scene;
  43823. };
  43824. CollisionCoordinatorLegacy.prototype.destroy = function () {
  43825. //Legacy need no destruction method.
  43826. };
  43827. //No update in legacy mode
  43828. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  43829. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  43830. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  43831. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  43832. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  43833. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  43834. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  43835. if (excludedMesh === void 0) { excludedMesh = null; }
  43836. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  43837. if (collider.retry >= maximumRetry) {
  43838. finalPosition.copyFrom(position);
  43839. return;
  43840. }
  43841. // Check if this is a mesh else camera or -1
  43842. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  43843. collider._initialize(position, velocity, closeDistance);
  43844. // Check all meshes
  43845. for (var index = 0; index < this._scene.meshes.length; index++) {
  43846. var mesh = this._scene.meshes[index];
  43847. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  43848. mesh._checkCollision(collider);
  43849. }
  43850. }
  43851. if (!collider.collisionFound) {
  43852. position.addToRef(velocity, finalPosition);
  43853. return;
  43854. }
  43855. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  43856. collider._getResponse(position, velocity);
  43857. }
  43858. if (velocity.length() <= closeDistance) {
  43859. finalPosition.copyFrom(position);
  43860. return;
  43861. }
  43862. collider.retry++;
  43863. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  43864. };
  43865. return CollisionCoordinatorLegacy;
  43866. }());
  43867. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  43868. })(BABYLON || (BABYLON = {}));
  43869. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  43870. var BABYLON;
  43871. (function (BABYLON) {
  43872. var Particle = /** @class */ (function () {
  43873. function Particle(particleSystem) {
  43874. this.particleSystem = particleSystem;
  43875. this.position = BABYLON.Vector3.Zero();
  43876. this.direction = BABYLON.Vector3.Zero();
  43877. this.color = new BABYLON.Color4(0, 0, 0, 0);
  43878. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  43879. this.lifeTime = 1.0;
  43880. this.age = 0;
  43881. this.size = 0;
  43882. this.angle = 0;
  43883. this.angularSpeed = 0;
  43884. this._currentFrameCounter = 0;
  43885. this.cellIndex = 0;
  43886. if (!this.particleSystem.isAnimationSheetEnabled) {
  43887. return;
  43888. }
  43889. this.cellIndex = this.particleSystem.startSpriteCellID;
  43890. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  43891. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  43892. }
  43893. else {
  43894. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  43895. }
  43896. }
  43897. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  43898. // (ageOffset / scaledUpdateSpeed) / available cells
  43899. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  43900. this._currentFrameCounter += scaledUpdateSpeed;
  43901. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  43902. this._currentFrameCounter = 0;
  43903. this.cellIndex++;
  43904. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43905. this.cellIndex = this.particleSystem.endSpriteCellID;
  43906. }
  43907. }
  43908. };
  43909. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  43910. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  43911. this.cellIndex++;
  43912. this._currentFrameCounter = 0;
  43913. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43914. if (this.particleSystem.spriteCellLoop) {
  43915. this.cellIndex = this.particleSystem.startSpriteCellID;
  43916. }
  43917. else {
  43918. this.cellIndex = this.particleSystem.endSpriteCellID;
  43919. }
  43920. }
  43921. }
  43922. else {
  43923. this._currentFrameCounter++;
  43924. }
  43925. };
  43926. Particle.prototype.copyTo = function (other) {
  43927. other.position.copyFrom(this.position);
  43928. other.direction.copyFrom(this.direction);
  43929. other.color.copyFrom(this.color);
  43930. other.colorStep.copyFrom(this.colorStep);
  43931. other.lifeTime = this.lifeTime;
  43932. other.age = this.age;
  43933. other.size = this.size;
  43934. other.angle = this.angle;
  43935. other.angularSpeed = this.angularSpeed;
  43936. other.particleSystem = this.particleSystem;
  43937. other.cellIndex = this.cellIndex;
  43938. };
  43939. return Particle;
  43940. }());
  43941. BABYLON.Particle = Particle;
  43942. })(BABYLON || (BABYLON = {}));
  43943. //# sourceMappingURL=babylon.particle.js.map
  43944. var BABYLON;
  43945. (function (BABYLON) {
  43946. var randomNumber = function (min, max) {
  43947. if (min === max) {
  43948. return (min);
  43949. }
  43950. var random = Math.random();
  43951. return ((random * (max - min)) + min);
  43952. };
  43953. var ParticleSystem = /** @class */ (function () {
  43954. // end of sheet animation
  43955. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  43956. if (customEffect === void 0) { customEffect = null; }
  43957. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  43958. if (epsilon === void 0) { epsilon = 0.01; }
  43959. var _this = this;
  43960. this.name = name;
  43961. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  43962. // Members
  43963. this.animations = [];
  43964. this.renderingGroupId = 0;
  43965. this.emitter = null;
  43966. this.emitRate = 10;
  43967. this.manualEmitCount = -1;
  43968. this.updateSpeed = 0.01;
  43969. this.targetStopDuration = 0;
  43970. this.disposeOnStop = false;
  43971. this.minEmitPower = 1;
  43972. this.maxEmitPower = 1;
  43973. this.minLifeTime = 1;
  43974. this.maxLifeTime = 1;
  43975. this.minSize = 1;
  43976. this.maxSize = 1;
  43977. this.minAngularSpeed = 0;
  43978. this.maxAngularSpeed = 0;
  43979. this.layerMask = 0x0FFFFFFF;
  43980. this.customShader = null;
  43981. this.preventAutoStart = false;
  43982. /**
  43983. * An event triggered when the system is disposed.
  43984. * @type {BABYLON.Observable}
  43985. */
  43986. this.onDisposeObservable = new BABYLON.Observable();
  43987. this.onAnimationEnd = null;
  43988. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  43989. this.forceDepthWrite = false;
  43990. this.gravity = BABYLON.Vector3.Zero();
  43991. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  43992. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  43993. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  43994. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43995. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43996. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43997. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  43998. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43999. this.particles = new Array();
  44000. this._stockParticles = new Array();
  44001. this._newPartsExcess = 0;
  44002. this._vertexBuffers = {};
  44003. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44004. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44005. this._scaledDirection = BABYLON.Vector3.Zero();
  44006. this._scaledGravity = BABYLON.Vector3.Zero();
  44007. this._currentRenderId = -1;
  44008. this._started = false;
  44009. this._stopped = false;
  44010. this._actualFrame = 0;
  44011. // sheet animation
  44012. this.startSpriteCellID = 0;
  44013. this.endSpriteCellID = 0;
  44014. this.spriteCellLoop = true;
  44015. this.spriteCellChangeSpeed = 0;
  44016. this.spriteCellWidth = 0;
  44017. this.spriteCellHeight = 0;
  44018. this._vertexBufferSize = 11;
  44019. this.appendParticleVertexes = null;
  44020. this.id = name;
  44021. this._capacity = capacity;
  44022. this._epsilon = epsilon;
  44023. if (_isAnimationSheetEnabled) {
  44024. this._vertexBufferSize = 12;
  44025. }
  44026. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44027. this._customEffect = customEffect;
  44028. scene.particleSystems.push(this);
  44029. this._createIndexBuffer();
  44030. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44031. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44032. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44033. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44034. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44035. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44036. if (this._isAnimationSheetEnabled) {
  44037. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44038. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44039. }
  44040. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44041. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44042. this._vertexBuffers["options"] = options;
  44043. // Default behaviors
  44044. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44045. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44046. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44047. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44048. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44049. };
  44050. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44051. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44052. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44053. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44054. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44055. };
  44056. this.updateFunction = function (particles) {
  44057. for (var index = 0; index < particles.length; index++) {
  44058. var particle = particles[index];
  44059. particle.age += _this._scaledUpdateSpeed;
  44060. if (particle.age >= particle.lifeTime) {
  44061. _this.recycleParticle(particle);
  44062. index--;
  44063. continue;
  44064. }
  44065. else {
  44066. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44067. particle.color.addInPlace(_this._scaledColorStep);
  44068. if (particle.color.a < 0)
  44069. particle.color.a = 0;
  44070. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44071. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44072. particle.position.addInPlace(_this._scaledDirection);
  44073. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44074. particle.direction.addInPlace(_this._scaledGravity);
  44075. if (_this._isAnimationSheetEnabled) {
  44076. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44077. }
  44078. }
  44079. }
  44080. };
  44081. }
  44082. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44083. set: function (callback) {
  44084. if (this._onDisposeObserver) {
  44085. this.onDisposeObservable.remove(this._onDisposeObserver);
  44086. }
  44087. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44088. },
  44089. enumerable: true,
  44090. configurable: true
  44091. });
  44092. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44093. get: function () {
  44094. return this._isAnimationSheetEnabled;
  44095. },
  44096. enumerable: true,
  44097. configurable: true
  44098. });
  44099. ParticleSystem.prototype._createIndexBuffer = function () {
  44100. var indices = [];
  44101. var index = 0;
  44102. for (var count = 0; count < this._capacity; count++) {
  44103. indices.push(index);
  44104. indices.push(index + 1);
  44105. indices.push(index + 2);
  44106. indices.push(index);
  44107. indices.push(index + 2);
  44108. indices.push(index + 3);
  44109. index += 4;
  44110. }
  44111. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44112. };
  44113. ParticleSystem.prototype.recycleParticle = function (particle) {
  44114. var lastParticle = this.particles.pop();
  44115. if (lastParticle !== particle) {
  44116. lastParticle.copyTo(particle);
  44117. this._stockParticles.push(lastParticle);
  44118. }
  44119. };
  44120. ParticleSystem.prototype.getCapacity = function () {
  44121. return this._capacity;
  44122. };
  44123. ParticleSystem.prototype.isAlive = function () {
  44124. return this._alive;
  44125. };
  44126. ParticleSystem.prototype.isStarted = function () {
  44127. return this._started;
  44128. };
  44129. ParticleSystem.prototype.start = function () {
  44130. this._started = true;
  44131. this._stopped = false;
  44132. this._actualFrame = 0;
  44133. };
  44134. ParticleSystem.prototype.stop = function () {
  44135. this._stopped = true;
  44136. };
  44137. // animation sheet
  44138. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44139. var offset = index * this._vertexBufferSize;
  44140. this._vertexData[offset] = particle.position.x;
  44141. this._vertexData[offset + 1] = particle.position.y;
  44142. this._vertexData[offset + 2] = particle.position.z;
  44143. this._vertexData[offset + 3] = particle.color.r;
  44144. this._vertexData[offset + 4] = particle.color.g;
  44145. this._vertexData[offset + 5] = particle.color.b;
  44146. this._vertexData[offset + 6] = particle.color.a;
  44147. this._vertexData[offset + 7] = particle.angle;
  44148. this._vertexData[offset + 8] = particle.size;
  44149. this._vertexData[offset + 9] = offsetX;
  44150. this._vertexData[offset + 10] = offsetY;
  44151. };
  44152. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44153. if (offsetX === 0)
  44154. offsetX = this._epsilon;
  44155. else if (offsetX === 1)
  44156. offsetX = 1 - this._epsilon;
  44157. if (offsetY === 0)
  44158. offsetY = this._epsilon;
  44159. else if (offsetY === 1)
  44160. offsetY = 1 - this._epsilon;
  44161. var offset = index * this._vertexBufferSize;
  44162. this._vertexData[offset] = particle.position.x;
  44163. this._vertexData[offset + 1] = particle.position.y;
  44164. this._vertexData[offset + 2] = particle.position.z;
  44165. this._vertexData[offset + 3] = particle.color.r;
  44166. this._vertexData[offset + 4] = particle.color.g;
  44167. this._vertexData[offset + 5] = particle.color.b;
  44168. this._vertexData[offset + 6] = particle.color.a;
  44169. this._vertexData[offset + 7] = particle.angle;
  44170. this._vertexData[offset + 8] = particle.size;
  44171. this._vertexData[offset + 9] = offsetX;
  44172. this._vertexData[offset + 10] = offsetY;
  44173. this._vertexData[offset + 11] = particle.cellIndex;
  44174. };
  44175. ParticleSystem.prototype._update = function (newParticles) {
  44176. // Update current
  44177. this._alive = this.particles.length > 0;
  44178. this.updateFunction(this.particles);
  44179. // Add new ones
  44180. var worldMatrix;
  44181. if (this.emitter.position) {
  44182. var emitterMesh = this.emitter;
  44183. worldMatrix = emitterMesh.getWorldMatrix();
  44184. }
  44185. else {
  44186. var emitterPosition = this.emitter;
  44187. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44188. }
  44189. var particle;
  44190. for (var index = 0; index < newParticles; index++) {
  44191. if (this.particles.length === this._capacity) {
  44192. break;
  44193. }
  44194. if (this._stockParticles.length !== 0) {
  44195. particle = this._stockParticles.pop();
  44196. particle.age = 0;
  44197. particle.cellIndex = this.startSpriteCellID;
  44198. }
  44199. else {
  44200. particle = new BABYLON.Particle(this);
  44201. }
  44202. this.particles.push(particle);
  44203. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44204. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44205. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44206. particle.size = randomNumber(this.minSize, this.maxSize);
  44207. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44208. this.startPositionFunction(worldMatrix, particle.position, particle);
  44209. var step = randomNumber(0, 1.0);
  44210. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44211. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44212. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44213. }
  44214. };
  44215. ParticleSystem.prototype._getEffect = function () {
  44216. if (this._customEffect) {
  44217. return this._customEffect;
  44218. }
  44219. ;
  44220. var defines = [];
  44221. if (this._scene.clipPlane) {
  44222. defines.push("#define CLIPPLANE");
  44223. }
  44224. if (this._isAnimationSheetEnabled) {
  44225. defines.push("#define ANIMATESHEET");
  44226. }
  44227. // Effect
  44228. var join = defines.join("\n");
  44229. if (this._cachedDefines !== join) {
  44230. this._cachedDefines = join;
  44231. var attributesNamesOrOptions;
  44232. var effectCreationOption;
  44233. if (this._isAnimationSheetEnabled) {
  44234. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44235. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44236. }
  44237. else {
  44238. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44239. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44240. }
  44241. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44242. }
  44243. return this._effect;
  44244. };
  44245. ParticleSystem.prototype.animate = function () {
  44246. if (!this._started)
  44247. return;
  44248. var effect = this._getEffect();
  44249. // Check
  44250. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44251. return;
  44252. if (this._currentRenderId === this._scene.getRenderId()) {
  44253. return;
  44254. }
  44255. this._currentRenderId = this._scene.getRenderId();
  44256. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44257. // determine the number of particles we need to create
  44258. var newParticles;
  44259. if (this.manualEmitCount > -1) {
  44260. newParticles = this.manualEmitCount;
  44261. this._newPartsExcess = 0;
  44262. this.manualEmitCount = 0;
  44263. }
  44264. else {
  44265. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44266. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44267. }
  44268. if (this._newPartsExcess > 1.0) {
  44269. newParticles += this._newPartsExcess >> 0;
  44270. this._newPartsExcess -= this._newPartsExcess >> 0;
  44271. }
  44272. this._alive = false;
  44273. if (!this._stopped) {
  44274. this._actualFrame += this._scaledUpdateSpeed;
  44275. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44276. this.stop();
  44277. }
  44278. else {
  44279. newParticles = 0;
  44280. }
  44281. this._update(newParticles);
  44282. // Stopped?
  44283. if (this._stopped) {
  44284. if (!this._alive) {
  44285. this._started = false;
  44286. if (this.onAnimationEnd) {
  44287. this.onAnimationEnd();
  44288. }
  44289. if (this.disposeOnStop) {
  44290. this._scene._toBeDisposed.push(this);
  44291. }
  44292. }
  44293. }
  44294. // Animation sheet
  44295. if (this._isAnimationSheetEnabled) {
  44296. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44297. }
  44298. else {
  44299. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44300. }
  44301. // Update VBO
  44302. var offset = 0;
  44303. for (var index = 0; index < this.particles.length; index++) {
  44304. var particle = this.particles[index];
  44305. this.appendParticleVertexes(offset, particle);
  44306. offset += 4;
  44307. }
  44308. if (this._vertexBuffer) {
  44309. this._vertexBuffer.update(this._vertexData);
  44310. }
  44311. };
  44312. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44313. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44314. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44315. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44316. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44317. };
  44318. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44319. this._appendParticleVertex(offset++, particle, 0, 0);
  44320. this._appendParticleVertex(offset++, particle, 1, 0);
  44321. this._appendParticleVertex(offset++, particle, 1, 1);
  44322. this._appendParticleVertex(offset++, particle, 0, 1);
  44323. };
  44324. ParticleSystem.prototype.rebuild = function () {
  44325. this._createIndexBuffer();
  44326. if (this._vertexBuffer) {
  44327. this._vertexBuffer._rebuild();
  44328. }
  44329. };
  44330. ParticleSystem.prototype.render = function () {
  44331. var effect = this._getEffect();
  44332. // Check
  44333. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44334. return 0;
  44335. var engine = this._scene.getEngine();
  44336. // Render
  44337. engine.enableEffect(effect);
  44338. engine.setState(false);
  44339. var viewMatrix = this._scene.getViewMatrix();
  44340. effect.setTexture("diffuseSampler", this.particleTexture);
  44341. effect.setMatrix("view", viewMatrix);
  44342. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44343. if (this._isAnimationSheetEnabled) {
  44344. var baseSize = this.particleTexture.getBaseSize();
  44345. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44346. }
  44347. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44348. if (this._scene.clipPlane) {
  44349. var clipPlane = this._scene.clipPlane;
  44350. var invView = viewMatrix.clone();
  44351. invView.invert();
  44352. effect.setMatrix("invView", invView);
  44353. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44354. }
  44355. // VBOs
  44356. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44357. // Draw order
  44358. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44359. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44360. }
  44361. else {
  44362. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44363. }
  44364. if (this.forceDepthWrite) {
  44365. engine.setDepthWrite(true);
  44366. }
  44367. engine.draw(true, 0, this.particles.length * 6);
  44368. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44369. return this.particles.length;
  44370. };
  44371. ParticleSystem.prototype.dispose = function () {
  44372. if (this._vertexBuffer) {
  44373. this._vertexBuffer.dispose();
  44374. this._vertexBuffer = null;
  44375. }
  44376. if (this._indexBuffer) {
  44377. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44378. this._indexBuffer = null;
  44379. }
  44380. if (this.particleTexture) {
  44381. this.particleTexture.dispose();
  44382. this.particleTexture = null;
  44383. }
  44384. // Remove from scene
  44385. var index = this._scene.particleSystems.indexOf(this);
  44386. if (index > -1) {
  44387. this._scene.particleSystems.splice(index, 1);
  44388. }
  44389. // Callback
  44390. this.onDisposeObservable.notifyObservers(this);
  44391. this.onDisposeObservable.clear();
  44392. };
  44393. // Clone
  44394. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44395. var custom = null;
  44396. var program = null;
  44397. if (this.customShader != null) {
  44398. program = this.customShader;
  44399. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44400. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44401. }
  44402. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44403. result.customShader = program;
  44404. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44405. if (newEmitter === undefined) {
  44406. newEmitter = this.emitter;
  44407. }
  44408. result.emitter = newEmitter;
  44409. if (this.particleTexture) {
  44410. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44411. }
  44412. if (!this.preventAutoStart) {
  44413. result.start();
  44414. }
  44415. return result;
  44416. };
  44417. ParticleSystem.prototype.serialize = function () {
  44418. var serializationObject = {};
  44419. serializationObject.name = this.name;
  44420. serializationObject.id = this.id;
  44421. // Emitter
  44422. if (this.emitter.position) {
  44423. var emitterMesh = this.emitter;
  44424. serializationObject.emitterId = emitterMesh.id;
  44425. }
  44426. else {
  44427. var emitterPosition = this.emitter;
  44428. serializationObject.emitter = emitterPosition.asArray();
  44429. }
  44430. serializationObject.capacity = this.getCapacity();
  44431. if (this.particleTexture) {
  44432. serializationObject.textureName = this.particleTexture.name;
  44433. }
  44434. // Animations
  44435. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44436. // Particle system
  44437. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44438. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44439. serializationObject.minSize = this.minSize;
  44440. serializationObject.maxSize = this.maxSize;
  44441. serializationObject.minEmitPower = this.minEmitPower;
  44442. serializationObject.maxEmitPower = this.maxEmitPower;
  44443. serializationObject.minLifeTime = this.minLifeTime;
  44444. serializationObject.maxLifeTime = this.maxLifeTime;
  44445. serializationObject.emitRate = this.emitRate;
  44446. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44447. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44448. serializationObject.gravity = this.gravity.asArray();
  44449. serializationObject.direction1 = this.direction1.asArray();
  44450. serializationObject.direction2 = this.direction2.asArray();
  44451. serializationObject.color1 = this.color1.asArray();
  44452. serializationObject.color2 = this.color2.asArray();
  44453. serializationObject.colorDead = this.colorDead.asArray();
  44454. serializationObject.updateSpeed = this.updateSpeed;
  44455. serializationObject.targetStopDuration = this.targetStopDuration;
  44456. serializationObject.textureMask = this.textureMask.asArray();
  44457. serializationObject.blendMode = this.blendMode;
  44458. serializationObject.customShader = this.customShader;
  44459. serializationObject.preventAutoStart = this.preventAutoStart;
  44460. return serializationObject;
  44461. };
  44462. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44463. var name = parsedParticleSystem.name;
  44464. var custom = null;
  44465. var program = null;
  44466. if (parsedParticleSystem.customShader) {
  44467. program = parsedParticleSystem.customShader;
  44468. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44469. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44470. }
  44471. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44472. particleSystem.customShader = program;
  44473. if (parsedParticleSystem.id) {
  44474. particleSystem.id = parsedParticleSystem.id;
  44475. }
  44476. // Auto start
  44477. if (parsedParticleSystem.preventAutoStart) {
  44478. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44479. }
  44480. // Texture
  44481. if (parsedParticleSystem.textureName) {
  44482. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  44483. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  44484. }
  44485. // Emitter
  44486. if (parsedParticleSystem.emitterId) {
  44487. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  44488. }
  44489. else {
  44490. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  44491. }
  44492. // Animations
  44493. if (parsedParticleSystem.animations) {
  44494. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  44495. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  44496. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44497. }
  44498. }
  44499. if (parsedParticleSystem.autoAnimate) {
  44500. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  44501. }
  44502. // Particle system
  44503. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  44504. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  44505. particleSystem.minSize = parsedParticleSystem.minSize;
  44506. particleSystem.maxSize = parsedParticleSystem.maxSize;
  44507. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  44508. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  44509. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  44510. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  44511. particleSystem.emitRate = parsedParticleSystem.emitRate;
  44512. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  44513. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  44514. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  44515. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  44516. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  44517. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  44518. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  44519. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  44520. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  44521. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  44522. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  44523. particleSystem.blendMode = parsedParticleSystem.blendMode;
  44524. if (!particleSystem.preventAutoStart) {
  44525. particleSystem.start();
  44526. }
  44527. return particleSystem;
  44528. };
  44529. // Statics
  44530. ParticleSystem.BLENDMODE_ONEONE = 0;
  44531. ParticleSystem.BLENDMODE_STANDARD = 1;
  44532. return ParticleSystem;
  44533. }());
  44534. BABYLON.ParticleSystem = ParticleSystem;
  44535. })(BABYLON || (BABYLON = {}));
  44536. //# sourceMappingURL=babylon.particleSystem.js.map
  44537. var BABYLON;
  44538. (function (BABYLON) {
  44539. var SolidParticle = /** @class */ (function () {
  44540. /**
  44541. * Creates a Solid Particle object.
  44542. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  44543. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  44544. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  44545. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  44546. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  44547. * `shapeId` (integer) is the model shape identifier in the SPS.
  44548. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  44549. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  44550. */
  44551. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  44552. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  44553. this.idx = 0; // particle global index
  44554. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  44555. this.position = BABYLON.Vector3.Zero(); // position
  44556. this.rotation = BABYLON.Vector3.Zero(); // rotation
  44557. this.scaling = BABYLON.Vector3.One(); // scaling
  44558. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  44559. this.velocity = BABYLON.Vector3.Zero(); // velocity
  44560. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  44561. this.alive = true; // alive
  44562. this.isVisible = true; // visibility
  44563. this._pos = 0; // index of this particle in the global "positions" array
  44564. this._ind = 0; // index of this particle in the global "indices" array
  44565. this.shapeId = 0; // model shape id
  44566. this.idxInShape = 0; // index of the particle in its shape id
  44567. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  44568. this.idx = particleIndex;
  44569. this._pos = positionIndex;
  44570. this._ind = indiceIndex;
  44571. this._model = model;
  44572. this.shapeId = shapeId;
  44573. this.idxInShape = idxInShape;
  44574. this._sps = sps;
  44575. if (modelBoundingInfo) {
  44576. this._modelBoundingInfo = modelBoundingInfo;
  44577. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  44578. }
  44579. }
  44580. Object.defineProperty(SolidParticle.prototype, "scale", {
  44581. /**
  44582. * legacy support, changed scale to scaling
  44583. */
  44584. get: function () {
  44585. return this.scaling;
  44586. },
  44587. set: function (scale) {
  44588. this.scaling = scale;
  44589. },
  44590. enumerable: true,
  44591. configurable: true
  44592. });
  44593. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  44594. /**
  44595. * legacy support, changed quaternion to rotationQuaternion
  44596. */
  44597. get: function () {
  44598. return this.rotationQuaternion;
  44599. },
  44600. set: function (q) {
  44601. this.rotationQuaternion = q;
  44602. },
  44603. enumerable: true,
  44604. configurable: true
  44605. });
  44606. /**
  44607. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  44608. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  44609. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  44610. */
  44611. SolidParticle.prototype.intersectsMesh = function (target) {
  44612. if (!this._boundingInfo || !target._boundingInfo) {
  44613. return false;
  44614. }
  44615. if (this._sps._bSphereOnly) {
  44616. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  44617. }
  44618. return this._boundingInfo.intersects(target._boundingInfo, false);
  44619. };
  44620. return SolidParticle;
  44621. }());
  44622. BABYLON.SolidParticle = SolidParticle;
  44623. var ModelShape = /** @class */ (function () {
  44624. /**
  44625. * 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.
  44626. * SPS internal tool, don't use it manually.
  44627. */
  44628. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  44629. this._indicesLength = 0; // length of the shape in the model indices array
  44630. this.shapeID = id;
  44631. this._shape = shape;
  44632. this._indicesLength = indicesLength;
  44633. this._shapeUV = shapeUV;
  44634. this._positionFunction = posFunction;
  44635. this._vertexFunction = vtxFunction;
  44636. }
  44637. return ModelShape;
  44638. }());
  44639. BABYLON.ModelShape = ModelShape;
  44640. var DepthSortedParticle = /** @class */ (function () {
  44641. function DepthSortedParticle() {
  44642. this.ind = 0; // index of the particle in the "indices" array
  44643. this.indicesLength = 0; // length of the particle shape in the "indices" array
  44644. this.sqDistance = 0.0; // squared distance from the particle to the camera
  44645. }
  44646. return DepthSortedParticle;
  44647. }());
  44648. BABYLON.DepthSortedParticle = DepthSortedParticle;
  44649. })(BABYLON || (BABYLON = {}));
  44650. //# sourceMappingURL=babylon.solidParticle.js.map
  44651. var BABYLON;
  44652. (function (BABYLON) {
  44653. /**
  44654. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  44655. */
  44656. var SolidParticleSystem = /** @class */ (function () {
  44657. /**
  44658. * Creates a SPS (Solid Particle System) object.
  44659. * `name` (String) is the SPS name, this will be the underlying mesh name.
  44660. * `scene` (Scene) is the scene in which the SPS is added.
  44661. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  44662. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  44663. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  44664. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  44665. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  44666. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  44667. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  44668. */
  44669. function SolidParticleSystem(name, scene, options) {
  44670. // public members
  44671. /**
  44672. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  44673. * Example : var p = SPS.particles[i];
  44674. */
  44675. this.particles = new Array();
  44676. /**
  44677. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  44678. */
  44679. this.nbParticles = 0;
  44680. /**
  44681. * If the particles must ever face the camera (default false). Useful for planar particles.
  44682. */
  44683. this.billboard = false;
  44684. /**
  44685. * Recompute normals when adding a shape
  44686. */
  44687. this.recomputeNormals = true;
  44688. /**
  44689. * This a counter ofr your own usage. It's not set by any SPS functions.
  44690. */
  44691. this.counter = 0;
  44692. /**
  44693. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  44694. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  44695. */
  44696. this.vars = {};
  44697. this._positions = new Array();
  44698. this._indices = new Array();
  44699. this._normals = new Array();
  44700. this._colors = new Array();
  44701. this._uvs = new Array();
  44702. this._index = 0; // indices index
  44703. this._updatable = true;
  44704. this._pickable = false;
  44705. this._isVisibilityBoxLocked = false;
  44706. this._alwaysVisible = false;
  44707. this._depthSort = false;
  44708. this._shapeCounter = 0;
  44709. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  44710. this._color = new BABYLON.Color4(0, 0, 0, 0);
  44711. this._computeParticleColor = true;
  44712. this._computeParticleTexture = true;
  44713. this._computeParticleRotation = true;
  44714. this._computeParticleVertex = false;
  44715. this._computeBoundingBox = false;
  44716. this._depthSortParticles = true;
  44717. this._cam_axisZ = BABYLON.Vector3.Zero();
  44718. this._cam_axisY = BABYLON.Vector3.Zero();
  44719. this._cam_axisX = BABYLON.Vector3.Zero();
  44720. this._axisZ = BABYLON.Axis.Z;
  44721. this._camDir = BABYLON.Vector3.Zero();
  44722. this._camInvertedPosition = BABYLON.Vector3.Zero();
  44723. this._rotMatrix = new BABYLON.Matrix();
  44724. this._invertMatrix = new BABYLON.Matrix();
  44725. this._rotated = BABYLON.Vector3.Zero();
  44726. this._quaternion = new BABYLON.Quaternion();
  44727. this._vertex = BABYLON.Vector3.Zero();
  44728. this._normal = BABYLON.Vector3.Zero();
  44729. this._yaw = 0.0;
  44730. this._pitch = 0.0;
  44731. this._roll = 0.0;
  44732. this._halfroll = 0.0;
  44733. this._halfpitch = 0.0;
  44734. this._halfyaw = 0.0;
  44735. this._sinRoll = 0.0;
  44736. this._cosRoll = 0.0;
  44737. this._sinPitch = 0.0;
  44738. this._cosPitch = 0.0;
  44739. this._sinYaw = 0.0;
  44740. this._cosYaw = 0.0;
  44741. this._mustUnrotateFixedNormals = false;
  44742. this._minimum = BABYLON.Tmp.Vector3[0];
  44743. this._maximum = BABYLON.Tmp.Vector3[1];
  44744. this._minBbox = BABYLON.Tmp.Vector3[4];
  44745. this._maxBbox = BABYLON.Tmp.Vector3[5];
  44746. this._particlesIntersect = false;
  44747. this._depthSortFunction = function (p1, p2) {
  44748. return (p2.sqDistance - p1.sqDistance);
  44749. };
  44750. this._needs32Bits = false;
  44751. this._bSphereOnly = false;
  44752. this._bSphereRadiusFactor = 1.0;
  44753. this.name = name;
  44754. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44755. this._camera = scene.activeCamera;
  44756. this._pickable = options ? options.isPickable : false;
  44757. this._depthSort = options ? options.enableDepthSort : false;
  44758. this._particlesIntersect = options ? options.particleIntersection : false;
  44759. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  44760. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  44761. if (options && options.updatable) {
  44762. this._updatable = options.updatable;
  44763. }
  44764. else {
  44765. this._updatable = true;
  44766. }
  44767. if (this._pickable) {
  44768. this.pickedParticles = [];
  44769. }
  44770. if (this._depthSort) {
  44771. this.depthSortedParticles = [];
  44772. }
  44773. }
  44774. /**
  44775. * Builds the SPS underlying mesh. Returns a standard Mesh.
  44776. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  44777. */
  44778. SolidParticleSystem.prototype.buildMesh = function () {
  44779. if (this.nbParticles === 0) {
  44780. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  44781. this.addShape(triangle, 1);
  44782. triangle.dispose();
  44783. }
  44784. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  44785. this._positions32 = new Float32Array(this._positions);
  44786. this._uvs32 = new Float32Array(this._uvs);
  44787. this._colors32 = new Float32Array(this._colors);
  44788. if (this.recomputeNormals) {
  44789. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  44790. }
  44791. this._normals32 = new Float32Array(this._normals);
  44792. this._fixedNormal32 = new Float32Array(this._normals);
  44793. if (this._mustUnrotateFixedNormals) {
  44794. this._unrotateFixedNormals();
  44795. }
  44796. var vertexData = new BABYLON.VertexData();
  44797. vertexData.indices = this._indices32;
  44798. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  44799. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  44800. if (this._uvs32) {
  44801. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  44802. ;
  44803. }
  44804. if (this._colors32) {
  44805. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  44806. }
  44807. var mesh = new BABYLON.Mesh(this.name, this._scene);
  44808. vertexData.applyToMesh(mesh, this._updatable);
  44809. this.mesh = mesh;
  44810. this.mesh.isPickable = this._pickable;
  44811. // free memory
  44812. if (!this._depthSort) {
  44813. this._indices = null;
  44814. }
  44815. this._positions = null;
  44816. this._normals = null;
  44817. this._uvs = null;
  44818. this._colors = null;
  44819. if (!this._updatable) {
  44820. this.particles.length = 0;
  44821. }
  44822. return mesh;
  44823. };
  44824. /**
  44825. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  44826. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  44827. * Thus the particles generated from `digest()` have their property `position` set yet.
  44828. * `mesh` ( Mesh ) is the mesh to be digested
  44829. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  44830. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  44831. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  44832. */
  44833. SolidParticleSystem.prototype.digest = function (mesh, options) {
  44834. var size = (options && options.facetNb) || 1;
  44835. var number = (options && options.number) || 0;
  44836. var delta = (options && options.delta) || 0;
  44837. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44838. var meshInd = mesh.getIndices();
  44839. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44840. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44841. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44842. var f = 0; // facet counter
  44843. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  44844. // compute size from number
  44845. if (number) {
  44846. number = (number > totalFacets) ? totalFacets : number;
  44847. size = Math.round(totalFacets / number);
  44848. delta = 0;
  44849. }
  44850. else {
  44851. size = (size > totalFacets) ? totalFacets : size;
  44852. }
  44853. var facetPos = []; // submesh positions
  44854. var facetInd = []; // submesh indices
  44855. var facetUV = []; // submesh UV
  44856. var facetCol = []; // submesh colors
  44857. var barycenter = BABYLON.Tmp.Vector3[0];
  44858. var sizeO = size;
  44859. while (f < totalFacets) {
  44860. size = sizeO + Math.floor((1 + delta) * Math.random());
  44861. if (f > totalFacets - size) {
  44862. size = totalFacets - f;
  44863. }
  44864. // reset temp arrays
  44865. facetPos.length = 0;
  44866. facetInd.length = 0;
  44867. facetUV.length = 0;
  44868. facetCol.length = 0;
  44869. // iterate over "size" facets
  44870. var fi = 0;
  44871. for (var j = f * 3; j < (f + size) * 3; j++) {
  44872. facetInd.push(fi);
  44873. var i = meshInd[j];
  44874. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  44875. if (meshUV) {
  44876. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  44877. }
  44878. if (meshCol) {
  44879. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  44880. }
  44881. fi++;
  44882. }
  44883. // create a model shape for each single particle
  44884. var idx = this.nbParticles;
  44885. var shape = this._posToShape(facetPos);
  44886. var shapeUV = this._uvsToShapeUV(facetUV);
  44887. // compute the barycenter of the shape
  44888. var v;
  44889. for (v = 0; v < shape.length; v++) {
  44890. barycenter.addInPlace(shape[v]);
  44891. }
  44892. barycenter.scaleInPlace(1 / shape.length);
  44893. // shift the shape from its barycenter to the origin
  44894. for (v = 0; v < shape.length; v++) {
  44895. shape[v].subtractInPlace(barycenter);
  44896. }
  44897. var bInfo;
  44898. if (this._particlesIntersect) {
  44899. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  44900. }
  44901. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  44902. // add the particle in the SPS
  44903. var currentPos = this._positions.length;
  44904. var currentInd = this._indices.length;
  44905. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  44906. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  44907. // initialize the particle position
  44908. this.particles[this.nbParticles].position.addInPlace(barycenter);
  44909. this._index += shape.length;
  44910. idx++;
  44911. this.nbParticles++;
  44912. this._shapeCounter++;
  44913. f += size;
  44914. }
  44915. return this;
  44916. };
  44917. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  44918. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  44919. var index = 0;
  44920. var idx = 0;
  44921. for (var p = 0; p < this.particles.length; p++) {
  44922. this._particle = this.particles[p];
  44923. this._shape = this._particle._model._shape;
  44924. if (this._particle.rotationQuaternion) {
  44925. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44926. }
  44927. else {
  44928. this._yaw = this._particle.rotation.y;
  44929. this._pitch = this._particle.rotation.x;
  44930. this._roll = this._particle.rotation.z;
  44931. this._quaternionRotationYPR();
  44932. }
  44933. this._quaternionToRotationMatrix();
  44934. this._rotMatrix.invertToRef(this._invertMatrix);
  44935. for (var pt = 0; pt < this._shape.length; pt++) {
  44936. idx = index + pt * 3;
  44937. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  44938. this._fixedNormal32[idx] = this._normal.x;
  44939. this._fixedNormal32[idx + 1] = this._normal.y;
  44940. this._fixedNormal32[idx + 2] = this._normal.z;
  44941. }
  44942. index = idx + 3;
  44943. }
  44944. };
  44945. //reset copy
  44946. SolidParticleSystem.prototype._resetCopy = function () {
  44947. this._copy.position.x = 0;
  44948. this._copy.position.y = 0;
  44949. this._copy.position.z = 0;
  44950. this._copy.rotation.x = 0;
  44951. this._copy.rotation.y = 0;
  44952. this._copy.rotation.z = 0;
  44953. this._copy.rotationQuaternion = null;
  44954. this._copy.scaling.x = 1.0;
  44955. this._copy.scaling.y = 1.0;
  44956. this._copy.scaling.z = 1.0;
  44957. this._copy.uvs.x = 0;
  44958. this._copy.uvs.y = 0;
  44959. this._copy.uvs.z = 1.0;
  44960. this._copy.uvs.w = 1.0;
  44961. this._copy.color = null;
  44962. };
  44963. // _meshBuilder : inserts the shape model in the global SPS mesh
  44964. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  44965. var i;
  44966. var u = 0;
  44967. var c = 0;
  44968. var n = 0;
  44969. this._resetCopy();
  44970. if (options && options.positionFunction) {
  44971. options.positionFunction(this._copy, idx, idxInShape);
  44972. this._mustUnrotateFixedNormals = true;
  44973. }
  44974. if (this._copy.rotationQuaternion) {
  44975. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44976. }
  44977. else {
  44978. this._yaw = this._copy.rotation.y;
  44979. this._pitch = this._copy.rotation.x;
  44980. this._roll = this._copy.rotation.z;
  44981. this._quaternionRotationYPR();
  44982. }
  44983. this._quaternionToRotationMatrix();
  44984. for (i = 0; i < shape.length; i++) {
  44985. this._vertex.x = shape[i].x;
  44986. this._vertex.y = shape[i].y;
  44987. this._vertex.z = shape[i].z;
  44988. if (options && options.vertexFunction) {
  44989. options.vertexFunction(this._copy, this._vertex, i);
  44990. }
  44991. this._vertex.x *= this._copy.scaling.x;
  44992. this._vertex.y *= this._copy.scaling.y;
  44993. this._vertex.z *= this._copy.scaling.z;
  44994. this._vertex.x += this._copy.pivot.x;
  44995. this._vertex.y += this._copy.pivot.y;
  44996. this._vertex.z += this._copy.pivot.z;
  44997. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44998. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  44999. if (meshUV) {
  45000. 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);
  45001. u += 2;
  45002. }
  45003. if (this._copy.color) {
  45004. this._color = this._copy.color;
  45005. }
  45006. else if (meshCol && meshCol[c] !== undefined) {
  45007. this._color.r = meshCol[c];
  45008. this._color.g = meshCol[c + 1];
  45009. this._color.b = meshCol[c + 2];
  45010. this._color.a = meshCol[c + 3];
  45011. }
  45012. else {
  45013. this._color.r = 1.0;
  45014. this._color.g = 1.0;
  45015. this._color.b = 1.0;
  45016. this._color.a = 1.0;
  45017. }
  45018. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45019. c += 4;
  45020. if (!this.recomputeNormals && meshNor) {
  45021. this._normal.x = meshNor[n];
  45022. this._normal.y = meshNor[n + 1];
  45023. this._normal.z = meshNor[n + 2];
  45024. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45025. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45026. n += 3;
  45027. }
  45028. }
  45029. for (i = 0; i < meshInd.length; i++) {
  45030. var current_ind = p + meshInd[i];
  45031. indices.push(current_ind);
  45032. if (current_ind > 65535) {
  45033. this._needs32Bits = true;
  45034. }
  45035. }
  45036. if (this._pickable) {
  45037. var nbfaces = meshInd.length / 3;
  45038. for (i = 0; i < nbfaces; i++) {
  45039. this.pickedParticles.push({ idx: idx, faceId: i });
  45040. }
  45041. }
  45042. if (this._depthSort) {
  45043. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45044. }
  45045. return this._copy;
  45046. };
  45047. // returns a shape array from positions array
  45048. SolidParticleSystem.prototype._posToShape = function (positions) {
  45049. var shape = [];
  45050. for (var i = 0; i < positions.length; i += 3) {
  45051. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45052. }
  45053. return shape;
  45054. };
  45055. // returns a shapeUV array from a Vector4 uvs
  45056. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45057. var shapeUV = [];
  45058. if (uvs) {
  45059. for (var i = 0; i < uvs.length; i++)
  45060. shapeUV.push(uvs[i]);
  45061. }
  45062. return shapeUV;
  45063. };
  45064. // adds a new particle object in the particles array
  45065. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45066. if (bInfo === void 0) { bInfo = null; }
  45067. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45068. this.particles.push(sp);
  45069. return sp;
  45070. };
  45071. /**
  45072. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45073. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45074. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45075. * `nb` (positive integer) the number of particles to be created from this model
  45076. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45077. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  45078. */
  45079. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  45080. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45081. var meshInd = mesh.getIndices();
  45082. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45083. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45084. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45085. var bbInfo;
  45086. if (this._particlesIntersect) {
  45087. bbInfo = mesh.getBoundingInfo();
  45088. }
  45089. var shape = this._posToShape(meshPos);
  45090. var shapeUV = this._uvsToShapeUV(meshUV);
  45091. var posfunc = options ? options.positionFunction : null;
  45092. var vtxfunc = options ? options.vertexFunction : null;
  45093. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45094. // particles
  45095. var sp;
  45096. var currentCopy;
  45097. var idx = this.nbParticles;
  45098. for (var i = 0; i < nb; i++) {
  45099. var currentPos = this._positions.length;
  45100. var currentInd = this._indices.length;
  45101. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45102. if (this._updatable) {
  45103. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45104. sp.position.copyFrom(currentCopy.position);
  45105. sp.rotation.copyFrom(currentCopy.rotation);
  45106. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45107. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45108. }
  45109. if (currentCopy.color && sp.color) {
  45110. sp.color.copyFrom(currentCopy.color);
  45111. }
  45112. sp.scaling.copyFrom(currentCopy.scaling);
  45113. sp.uvs.copyFrom(currentCopy.uvs);
  45114. }
  45115. this._index += shape.length;
  45116. idx++;
  45117. }
  45118. this.nbParticles += nb;
  45119. this._shapeCounter++;
  45120. return this._shapeCounter - 1;
  45121. };
  45122. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45123. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45124. this._resetCopy();
  45125. if (particle._model._positionFunction) {
  45126. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45127. }
  45128. if (this._copy.rotationQuaternion) {
  45129. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45130. }
  45131. else {
  45132. this._yaw = this._copy.rotation.y;
  45133. this._pitch = this._copy.rotation.x;
  45134. this._roll = this._copy.rotation.z;
  45135. this._quaternionRotationYPR();
  45136. }
  45137. this._quaternionToRotationMatrix();
  45138. this._shape = particle._model._shape;
  45139. for (var pt = 0; pt < this._shape.length; pt++) {
  45140. this._vertex.x = this._shape[pt].x;
  45141. this._vertex.y = this._shape[pt].y;
  45142. this._vertex.z = this._shape[pt].z;
  45143. if (particle._model._vertexFunction) {
  45144. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45145. }
  45146. this._vertex.x *= this._copy.scaling.x;
  45147. this._vertex.y *= this._copy.scaling.y;
  45148. this._vertex.z *= this._copy.scaling.z;
  45149. this._vertex.x += this._copy.pivot.x;
  45150. this._vertex.y += this._copy.pivot.y;
  45151. this._vertex.z += this._copy.pivot.z;
  45152. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45153. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45154. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45155. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45156. }
  45157. particle.position.x = 0.0;
  45158. particle.position.y = 0.0;
  45159. particle.position.z = 0.0;
  45160. particle.rotation.x = 0.0;
  45161. particle.rotation.y = 0.0;
  45162. particle.rotation.z = 0.0;
  45163. particle.rotationQuaternion = null;
  45164. particle.scaling.x = 1.0;
  45165. particle.scaling.y = 1.0;
  45166. particle.scaling.z = 1.0;
  45167. };
  45168. /**
  45169. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45170. * Returns the SPS.
  45171. */
  45172. SolidParticleSystem.prototype.rebuildMesh = function () {
  45173. for (var p = 0; p < this.particles.length; p++) {
  45174. this._rebuildParticle(this.particles[p]);
  45175. }
  45176. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45177. return this;
  45178. };
  45179. /**
  45180. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45181. * This method calls `updateParticle()` for each particle of the SPS.
  45182. * For an animated SPS, it is usually called within the render loop.
  45183. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45184. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45185. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45186. * Returns the SPS.
  45187. */
  45188. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45189. if (start === void 0) { start = 0; }
  45190. if (end === void 0) { end = this.nbParticles - 1; }
  45191. if (update === void 0) { update = true; }
  45192. if (!this._updatable) {
  45193. return this;
  45194. }
  45195. // custom beforeUpdate
  45196. this.beforeUpdateParticles(start, end, update);
  45197. this._cam_axisX.x = 1.0;
  45198. this._cam_axisX.y = 0.0;
  45199. this._cam_axisX.z = 0.0;
  45200. this._cam_axisY.x = 0.0;
  45201. this._cam_axisY.y = 1.0;
  45202. this._cam_axisY.z = 0.0;
  45203. this._cam_axisZ.x = 0.0;
  45204. this._cam_axisZ.y = 0.0;
  45205. this._cam_axisZ.z = 1.0;
  45206. // cases when the World Matrix is to be computed first
  45207. if (this.billboard || this._depthSort) {
  45208. this.mesh.computeWorldMatrix(true);
  45209. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45210. }
  45211. // if the particles will always face the camera
  45212. if (this.billboard) {
  45213. // compute the camera position and un-rotate it by the current mesh rotation
  45214. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45215. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45216. this._cam_axisZ.normalize();
  45217. // same for camera up vector extracted from the cam view matrix
  45218. var view = this._camera.getViewMatrix(true);
  45219. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45220. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45221. this._cam_axisY.normalize();
  45222. this._cam_axisX.normalize();
  45223. }
  45224. // if depthSort, compute the camera global position in the mesh local system
  45225. if (this._depthSort) {
  45226. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45227. }
  45228. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45229. var idx = 0; // current position index in the global array positions32
  45230. var index = 0; // position start index in the global array positions32 of the current particle
  45231. var colidx = 0; // current color index in the global array colors32
  45232. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45233. var uvidx = 0; // current uv index in the global array uvs32
  45234. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45235. var pt = 0; // current index in the particle model shape
  45236. if (this.mesh.isFacetDataEnabled) {
  45237. this._computeBoundingBox = true;
  45238. }
  45239. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45240. if (this._computeBoundingBox) {
  45241. if (start == 0 && end == this.nbParticles - 1) {
  45242. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45243. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45244. }
  45245. else {
  45246. if (this.mesh._boundingInfo) {
  45247. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45248. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45249. }
  45250. }
  45251. }
  45252. // particle loop
  45253. index = this.particles[start]._pos;
  45254. var vpos = (index / 3) | 0;
  45255. colorIndex = vpos * 4;
  45256. uvIndex = vpos * 2;
  45257. for (var p = start; p <= end; p++) {
  45258. this._particle = this.particles[p];
  45259. this._shape = this._particle._model._shape;
  45260. this._shapeUV = this._particle._model._shapeUV;
  45261. // call to custom user function to update the particle properties
  45262. this.updateParticle(this._particle);
  45263. // camera-particle distance for depth sorting
  45264. if (this._depthSort && this._depthSortParticles) {
  45265. var dsp = this.depthSortedParticles[p];
  45266. dsp.ind = this._particle._ind;
  45267. dsp.indicesLength = this._particle._model._indicesLength;
  45268. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45269. }
  45270. // skip the computations for inactive or already invisible particles
  45271. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45272. // increment indexes for the next particle
  45273. pt = this._shape.length;
  45274. index += pt * 3;
  45275. colorIndex += pt * 4;
  45276. uvIndex += pt * 2;
  45277. continue;
  45278. }
  45279. if (this._particle.isVisible) {
  45280. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45281. // particle rotation matrix
  45282. if (this.billboard) {
  45283. this._particle.rotation.x = 0.0;
  45284. this._particle.rotation.y = 0.0;
  45285. }
  45286. if (this._computeParticleRotation || this.billboard) {
  45287. if (this._particle.rotationQuaternion) {
  45288. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45289. }
  45290. else {
  45291. this._yaw = this._particle.rotation.y;
  45292. this._pitch = this._particle.rotation.x;
  45293. this._roll = this._particle.rotation.z;
  45294. this._quaternionRotationYPR();
  45295. }
  45296. this._quaternionToRotationMatrix();
  45297. }
  45298. // particle vertex loop
  45299. for (pt = 0; pt < this._shape.length; pt++) {
  45300. idx = index + pt * 3;
  45301. colidx = colorIndex + pt * 4;
  45302. uvidx = uvIndex + pt * 2;
  45303. this._vertex.x = this._shape[pt].x;
  45304. this._vertex.y = this._shape[pt].y;
  45305. this._vertex.z = this._shape[pt].z;
  45306. if (this._computeParticleVertex) {
  45307. this.updateParticleVertex(this._particle, this._vertex, pt);
  45308. }
  45309. // positions
  45310. this._vertex.x *= this._particle.scaling.x;
  45311. this._vertex.y *= this._particle.scaling.y;
  45312. this._vertex.z *= this._particle.scaling.z;
  45313. this._vertex.x += this._particle.pivot.x;
  45314. this._vertex.y += this._particle.pivot.y;
  45315. this._vertex.z += this._particle.pivot.z;
  45316. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45317. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45318. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45319. 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;
  45320. 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;
  45321. 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;
  45322. if (this._computeBoundingBox) {
  45323. if (this._positions32[idx] < this._minimum.x) {
  45324. this._minimum.x = this._positions32[idx];
  45325. }
  45326. if (this._positions32[idx] > this._maximum.x) {
  45327. this._maximum.x = this._positions32[idx];
  45328. }
  45329. if (this._positions32[idx + 1] < this._minimum.y) {
  45330. this._minimum.y = this._positions32[idx + 1];
  45331. }
  45332. if (this._positions32[idx + 1] > this._maximum.y) {
  45333. this._maximum.y = this._positions32[idx + 1];
  45334. }
  45335. if (this._positions32[idx + 2] < this._minimum.z) {
  45336. this._minimum.z = this._positions32[idx + 2];
  45337. }
  45338. if (this._positions32[idx + 2] > this._maximum.z) {
  45339. this._maximum.z = this._positions32[idx + 2];
  45340. }
  45341. }
  45342. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45343. if (!this._computeParticleVertex) {
  45344. this._normal.x = this._fixedNormal32[idx];
  45345. this._normal.y = this._fixedNormal32[idx + 1];
  45346. this._normal.z = this._fixedNormal32[idx + 2];
  45347. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45348. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45349. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45350. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45351. 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;
  45352. 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;
  45353. }
  45354. if (this._computeParticleColor && this._particle.color) {
  45355. this._colors32[colidx] = this._particle.color.r;
  45356. this._colors32[colidx + 1] = this._particle.color.g;
  45357. this._colors32[colidx + 2] = this._particle.color.b;
  45358. this._colors32[colidx + 3] = this._particle.color.a;
  45359. }
  45360. if (this._computeParticleTexture) {
  45361. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45362. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45363. }
  45364. }
  45365. }
  45366. else {
  45367. this._particle._stillInvisible = true; // mark the particle as invisible
  45368. for (pt = 0; pt < this._shape.length; pt++) {
  45369. idx = index + pt * 3;
  45370. colidx = colorIndex + pt * 4;
  45371. uvidx = uvIndex + pt * 2;
  45372. this._positions32[idx] = 0.0;
  45373. this._positions32[idx + 1] = 0.0;
  45374. this._positions32[idx + 2] = 0.0;
  45375. this._normals32[idx] = 0.0;
  45376. this._normals32[idx + 1] = 0.0;
  45377. this._normals32[idx + 2] = 0.0;
  45378. if (this._computeParticleColor && this._particle.color) {
  45379. this._colors32[colidx] = this._particle.color.r;
  45380. this._colors32[colidx + 1] = this._particle.color.g;
  45381. this._colors32[colidx + 2] = this._particle.color.b;
  45382. this._colors32[colidx + 3] = this._particle.color.a;
  45383. }
  45384. if (this._computeParticleTexture) {
  45385. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45386. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45387. }
  45388. }
  45389. }
  45390. // if the particle intersections must be computed : update the bbInfo
  45391. if (this._particlesIntersect) {
  45392. var bInfo = this._particle._boundingInfo;
  45393. var bBox = bInfo.boundingBox;
  45394. var bSphere = bInfo.boundingSphere;
  45395. if (!this._bSphereOnly) {
  45396. // place, scale and rotate the particle bbox within the SPS local system, then update it
  45397. for (var b = 0; b < bBox.vectors.length; b++) {
  45398. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  45399. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  45400. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  45401. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45402. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45403. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45404. 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;
  45405. 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;
  45406. 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;
  45407. }
  45408. bBox._update(this.mesh._worldMatrix);
  45409. }
  45410. // place and scale the particle bouding sphere in the SPS local system, then update it
  45411. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  45412. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  45413. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  45414. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  45415. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  45416. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  45417. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  45418. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  45419. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  45420. 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));
  45421. bSphere._update(this.mesh._worldMatrix);
  45422. }
  45423. // increment indexes for the next particle
  45424. index = idx + 3;
  45425. colorIndex = colidx + 4;
  45426. uvIndex = uvidx + 2;
  45427. }
  45428. // if the VBO must be updated
  45429. if (update) {
  45430. if (this._computeParticleColor) {
  45431. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  45432. }
  45433. if (this._computeParticleTexture) {
  45434. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  45435. }
  45436. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45437. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  45438. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  45439. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  45440. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  45441. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  45442. for (var i = 0; i < this._normals32.length; i++) {
  45443. this._fixedNormal32[i] = this._normals32[i];
  45444. }
  45445. }
  45446. if (!this.mesh.areNormalsFrozen) {
  45447. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  45448. }
  45449. }
  45450. if (this._depthSort && this._depthSortParticles) {
  45451. this.depthSortedParticles.sort(this._depthSortFunction);
  45452. var dspl = this.depthSortedParticles.length;
  45453. var sorted = 0;
  45454. var lind = 0;
  45455. var sind = 0;
  45456. var sid = 0;
  45457. for (sorted = 0; sorted < dspl; sorted++) {
  45458. lind = this.depthSortedParticles[sorted].indicesLength;
  45459. sind = this.depthSortedParticles[sorted].ind;
  45460. for (var i = 0; i < lind; i++) {
  45461. this._indices32[sid] = this._indices[sind + i];
  45462. sid++;
  45463. }
  45464. }
  45465. this.mesh.updateIndices(this._indices32);
  45466. }
  45467. }
  45468. if (this._computeBoundingBox) {
  45469. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  45470. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  45471. }
  45472. this.afterUpdateParticles(start, end, update);
  45473. return this;
  45474. };
  45475. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  45476. this._halfroll = this._roll * 0.5;
  45477. this._halfpitch = this._pitch * 0.5;
  45478. this._halfyaw = this._yaw * 0.5;
  45479. this._sinRoll = Math.sin(this._halfroll);
  45480. this._cosRoll = Math.cos(this._halfroll);
  45481. this._sinPitch = Math.sin(this._halfpitch);
  45482. this._cosPitch = Math.cos(this._halfpitch);
  45483. this._sinYaw = Math.sin(this._halfyaw);
  45484. this._cosYaw = Math.cos(this._halfyaw);
  45485. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  45486. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  45487. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  45488. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  45489. };
  45490. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  45491. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  45492. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  45493. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  45494. this._rotMatrix.m[3] = 0;
  45495. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  45496. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  45497. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  45498. this._rotMatrix.m[7] = 0;
  45499. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  45500. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  45501. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  45502. this._rotMatrix.m[11] = 0;
  45503. this._rotMatrix.m[12] = 0;
  45504. this._rotMatrix.m[13] = 0;
  45505. this._rotMatrix.m[14] = 0;
  45506. this._rotMatrix.m[15] = 1.0;
  45507. };
  45508. /**
  45509. * Disposes the SPS.
  45510. * Returns nothing.
  45511. */
  45512. SolidParticleSystem.prototype.dispose = function () {
  45513. this.mesh.dispose();
  45514. this.vars = null;
  45515. // drop references to internal big arrays for the GC
  45516. this._positions = null;
  45517. this._indices = null;
  45518. this._normals = null;
  45519. this._uvs = null;
  45520. this._colors = null;
  45521. this._indices32 = null;
  45522. this._positions32 = null;
  45523. this._normals32 = null;
  45524. this._fixedNormal32 = null;
  45525. this._uvs32 = null;
  45526. this._colors32 = null;
  45527. this.pickedParticles = null;
  45528. };
  45529. /**
  45530. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  45531. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45532. * Returns the SPS.
  45533. */
  45534. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  45535. if (!this._isVisibilityBoxLocked) {
  45536. this.mesh.refreshBoundingInfo();
  45537. }
  45538. return this;
  45539. };
  45540. /**
  45541. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  45542. * @param size the size (float) of the visibility box
  45543. * note : this doesn't lock the SPS mesh bounding box.
  45544. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45545. */
  45546. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  45547. var vis = size / 2;
  45548. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  45549. };
  45550. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  45551. // getter and setter
  45552. get: function () {
  45553. return this._alwaysVisible;
  45554. },
  45555. /**
  45556. * Sets the SPS as always visible or not
  45557. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45558. */
  45559. set: function (val) {
  45560. this._alwaysVisible = val;
  45561. this.mesh.alwaysSelectAsActiveMesh = val;
  45562. },
  45563. enumerable: true,
  45564. configurable: true
  45565. });
  45566. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  45567. get: function () {
  45568. return this._isVisibilityBoxLocked;
  45569. },
  45570. /**
  45571. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  45572. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45573. */
  45574. set: function (val) {
  45575. this._isVisibilityBoxLocked = val;
  45576. var boundingInfo = this.mesh.getBoundingInfo();
  45577. if (boundingInfo) {
  45578. boundingInfo.isLocked = val;
  45579. }
  45580. },
  45581. enumerable: true,
  45582. configurable: true
  45583. });
  45584. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  45585. // getters
  45586. get: function () {
  45587. return this._computeParticleRotation;
  45588. },
  45589. // Optimizer setters
  45590. /**
  45591. * Tells to `setParticles()` to compute the particle rotations or not.
  45592. * Default value : true. The SPS is faster when it's set to false.
  45593. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  45594. */
  45595. set: function (val) {
  45596. this._computeParticleRotation = val;
  45597. },
  45598. enumerable: true,
  45599. configurable: true
  45600. });
  45601. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  45602. get: function () {
  45603. return this._computeParticleColor;
  45604. },
  45605. /**
  45606. * Tells to `setParticles()` to compute the particle colors or not.
  45607. * Default value : true. The SPS is faster when it's set to false.
  45608. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  45609. */
  45610. set: function (val) {
  45611. this._computeParticleColor = val;
  45612. },
  45613. enumerable: true,
  45614. configurable: true
  45615. });
  45616. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  45617. get: function () {
  45618. return this._computeParticleTexture;
  45619. },
  45620. /**
  45621. * Tells to `setParticles()` to compute the particle textures or not.
  45622. * Default value : true. The SPS is faster when it's set to false.
  45623. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  45624. */
  45625. set: function (val) {
  45626. this._computeParticleTexture = val;
  45627. },
  45628. enumerable: true,
  45629. configurable: true
  45630. });
  45631. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  45632. get: function () {
  45633. return this._computeParticleVertex;
  45634. },
  45635. /**
  45636. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  45637. * Default value : false. The SPS is faster when it's set to false.
  45638. * Note : the particle custom vertex positions aren't stored values.
  45639. */
  45640. set: function (val) {
  45641. this._computeParticleVertex = val;
  45642. },
  45643. enumerable: true,
  45644. configurable: true
  45645. });
  45646. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  45647. get: function () {
  45648. return this._computeBoundingBox;
  45649. },
  45650. /**
  45651. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  45652. */
  45653. set: function (val) {
  45654. this._computeBoundingBox = val;
  45655. },
  45656. enumerable: true,
  45657. configurable: true
  45658. });
  45659. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  45660. get: function () {
  45661. return this._depthSortParticles;
  45662. },
  45663. /**
  45664. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  45665. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  45666. * Default : `true`
  45667. */
  45668. set: function (val) {
  45669. this._depthSortParticles = val;
  45670. },
  45671. enumerable: true,
  45672. configurable: true
  45673. });
  45674. // =======================================================================
  45675. // Particle behavior logic
  45676. // these following methods may be overwritten by the user to fit his needs
  45677. /**
  45678. * This function does nothing. It may be overwritten to set all the particle first values.
  45679. * The SPS doesn't call this function, you may have to call it by your own.
  45680. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45681. */
  45682. SolidParticleSystem.prototype.initParticles = function () {
  45683. };
  45684. /**
  45685. * This function does nothing. It may be overwritten to recycle a particle.
  45686. * The SPS doesn't call this function, you may have to call it by your own.
  45687. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45688. */
  45689. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  45690. return particle;
  45691. };
  45692. /**
  45693. * Updates a particle : this function should be overwritten by the user.
  45694. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  45695. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45696. * ex : just set a particle position or velocity and recycle conditions
  45697. */
  45698. SolidParticleSystem.prototype.updateParticle = function (particle) {
  45699. return particle;
  45700. };
  45701. /**
  45702. * Updates a vertex of a particle : it can be overwritten by the user.
  45703. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  45704. * @param particle the current particle
  45705. * @param vertex the current index of the current particle
  45706. * @param pt the index of the current vertex in the particle shape
  45707. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  45708. * ex : just set a vertex particle position
  45709. */
  45710. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  45711. return vertex;
  45712. };
  45713. /**
  45714. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  45715. * This does nothing and may be overwritten by the user.
  45716. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45717. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45718. * @param update the boolean update value actually passed to setParticles()
  45719. */
  45720. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  45721. };
  45722. /**
  45723. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  45724. * This will be passed three parameters.
  45725. * This does nothing and may be overwritten by the user.
  45726. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45727. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45728. * @param update the boolean update value actually passed to setParticles()
  45729. */
  45730. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  45731. };
  45732. return SolidParticleSystem;
  45733. }());
  45734. BABYLON.SolidParticleSystem = SolidParticleSystem;
  45735. })(BABYLON || (BABYLON = {}));
  45736. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  45737. var BABYLON;
  45738. (function (BABYLON) {
  45739. var GroundMesh = /** @class */ (function (_super) {
  45740. __extends(GroundMesh, _super);
  45741. function GroundMesh(name, scene) {
  45742. var _this = _super.call(this, name, scene) || this;
  45743. _this.generateOctree = false;
  45744. return _this;
  45745. }
  45746. GroundMesh.prototype.getClassName = function () {
  45747. return "GroundMesh";
  45748. };
  45749. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  45750. get: function () {
  45751. return Math.min(this._subdivisionsX, this._subdivisionsY);
  45752. },
  45753. enumerable: true,
  45754. configurable: true
  45755. });
  45756. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  45757. get: function () {
  45758. return this._subdivisionsX;
  45759. },
  45760. enumerable: true,
  45761. configurable: true
  45762. });
  45763. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  45764. get: function () {
  45765. return this._subdivisionsY;
  45766. },
  45767. enumerable: true,
  45768. configurable: true
  45769. });
  45770. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  45771. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  45772. this._subdivisionsX = chunksCount;
  45773. this._subdivisionsY = chunksCount;
  45774. this.subdivide(chunksCount);
  45775. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  45776. };
  45777. /**
  45778. * Returns a height (y) value in the Worl system :
  45779. * the ground altitude at the coordinates (x, z) expressed in the World system.
  45780. * Returns the ground y position if (x, z) are outside the ground surface.
  45781. */
  45782. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  45783. var world = this.getWorldMatrix();
  45784. var invMat = BABYLON.Tmp.Matrix[5];
  45785. world.invertToRef(invMat);
  45786. var tmpVect = BABYLON.Tmp.Vector3[8];
  45787. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  45788. x = tmpVect.x;
  45789. z = tmpVect.z;
  45790. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45791. return this.position.y;
  45792. }
  45793. if (!this._heightQuads || this._heightQuads.length == 0) {
  45794. this._initHeightQuads();
  45795. this._computeHeightQuads();
  45796. }
  45797. var facet = this._getFacetAt(x, z);
  45798. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  45799. // return y in the World system
  45800. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  45801. return tmpVect.y;
  45802. };
  45803. /**
  45804. * Returns a normalized vector (Vector3) orthogonal to the ground
  45805. * at the ground coordinates (x, z) expressed in the World system.
  45806. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  45807. */
  45808. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  45809. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  45810. this.getNormalAtCoordinatesToRef(x, z, normal);
  45811. return normal;
  45812. };
  45813. /**
  45814. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  45815. * at the ground coordinates (x, z) expressed in the World system.
  45816. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  45817. * Returns the GroundMesh.
  45818. */
  45819. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  45820. var world = this.getWorldMatrix();
  45821. var tmpMat = BABYLON.Tmp.Matrix[5];
  45822. world.invertToRef(tmpMat);
  45823. var tmpVect = BABYLON.Tmp.Vector3[8];
  45824. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  45825. x = tmpVect.x;
  45826. z = tmpVect.z;
  45827. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45828. return this;
  45829. }
  45830. if (!this._heightQuads || this._heightQuads.length == 0) {
  45831. this._initHeightQuads();
  45832. this._computeHeightQuads();
  45833. }
  45834. var facet = this._getFacetAt(x, z);
  45835. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  45836. return this;
  45837. };
  45838. /**
  45839. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  45840. * if the ground has been updated.
  45841. * This can be used in the render loop.
  45842. * Returns the GroundMesh.
  45843. */
  45844. GroundMesh.prototype.updateCoordinateHeights = function () {
  45845. if (!this._heightQuads || this._heightQuads.length == 0) {
  45846. this._initHeightQuads();
  45847. }
  45848. this._computeHeightQuads();
  45849. return this;
  45850. };
  45851. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  45852. GroundMesh.prototype._getFacetAt = function (x, z) {
  45853. // retrieve col and row from x, z coordinates in the ground local system
  45854. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  45855. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  45856. var quad = this._heightQuads[row * this._subdivisionsX + col];
  45857. var facet;
  45858. if (z < quad.slope.x * x + quad.slope.y) {
  45859. facet = quad.facet1;
  45860. }
  45861. else {
  45862. facet = quad.facet2;
  45863. }
  45864. return facet;
  45865. };
  45866. // Creates and populates the heightMap array with "facet" elements :
  45867. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  45868. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45869. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45870. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45871. // Returns the GroundMesh.
  45872. GroundMesh.prototype._initHeightQuads = function () {
  45873. var subdivisionsX = this._subdivisionsX;
  45874. var subdivisionsY = this._subdivisionsY;
  45875. this._heightQuads = new Array();
  45876. for (var row = 0; row < subdivisionsY; row++) {
  45877. for (var col = 0; col < subdivisionsX; col++) {
  45878. 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) };
  45879. this._heightQuads[row * subdivisionsX + col] = quad;
  45880. }
  45881. }
  45882. return this;
  45883. };
  45884. // Compute each quad element values and update the the heightMap array :
  45885. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45886. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45887. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45888. // Returns the GroundMesh.
  45889. GroundMesh.prototype._computeHeightQuads = function () {
  45890. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45891. if (!positions) {
  45892. return this;
  45893. }
  45894. var v1 = BABYLON.Tmp.Vector3[3];
  45895. var v2 = BABYLON.Tmp.Vector3[2];
  45896. var v3 = BABYLON.Tmp.Vector3[1];
  45897. var v4 = BABYLON.Tmp.Vector3[0];
  45898. var v1v2 = BABYLON.Tmp.Vector3[4];
  45899. var v1v3 = BABYLON.Tmp.Vector3[5];
  45900. var v1v4 = BABYLON.Tmp.Vector3[6];
  45901. var norm1 = BABYLON.Tmp.Vector3[7];
  45902. var norm2 = BABYLON.Tmp.Vector3[8];
  45903. var i = 0;
  45904. var j = 0;
  45905. var k = 0;
  45906. var cd = 0; // 2D slope coefficient : z = cd * x + h
  45907. var h = 0;
  45908. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  45909. var d2 = 0;
  45910. var subdivisionsX = this._subdivisionsX;
  45911. var subdivisionsY = this._subdivisionsY;
  45912. for (var row = 0; row < subdivisionsY; row++) {
  45913. for (var col = 0; col < subdivisionsX; col++) {
  45914. i = col * 3;
  45915. j = row * (subdivisionsX + 1) * 3;
  45916. k = (row + 1) * (subdivisionsX + 1) * 3;
  45917. v1.x = positions[j + i];
  45918. v1.y = positions[j + i + 1];
  45919. v1.z = positions[j + i + 2];
  45920. v2.x = positions[j + i + 3];
  45921. v2.y = positions[j + i + 4];
  45922. v2.z = positions[j + i + 5];
  45923. v3.x = positions[k + i];
  45924. v3.y = positions[k + i + 1];
  45925. v3.z = positions[k + i + 2];
  45926. v4.x = positions[k + i + 3];
  45927. v4.y = positions[k + i + 4];
  45928. v4.z = positions[k + i + 5];
  45929. // 2D slope V1V4
  45930. cd = (v4.z - v1.z) / (v4.x - v1.x);
  45931. h = v1.z - cd * v1.x; // v1 belongs to the slope
  45932. // facet equations :
  45933. // we compute each facet normal vector
  45934. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  45935. // we compute the value d by applying the equation to v1 which belongs to the plane
  45936. // then we store the facet equation in a Vector4
  45937. v2.subtractToRef(v1, v1v2);
  45938. v3.subtractToRef(v1, v1v3);
  45939. v4.subtractToRef(v1, v1v4);
  45940. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  45941. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  45942. norm1.normalize();
  45943. norm2.normalize();
  45944. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  45945. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  45946. var quad = this._heightQuads[row * subdivisionsX + col];
  45947. quad.slope.copyFromFloats(cd, h);
  45948. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  45949. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  45950. }
  45951. }
  45952. return this;
  45953. };
  45954. GroundMesh.prototype.serialize = function (serializationObject) {
  45955. _super.prototype.serialize.call(this, serializationObject);
  45956. serializationObject.subdivisionsX = this._subdivisionsX;
  45957. serializationObject.subdivisionsY = this._subdivisionsY;
  45958. serializationObject.minX = this._minX;
  45959. serializationObject.maxX = this._maxX;
  45960. serializationObject.minZ = this._minZ;
  45961. serializationObject.maxZ = this._maxZ;
  45962. serializationObject.width = this._width;
  45963. serializationObject.height = this._height;
  45964. };
  45965. GroundMesh.Parse = function (parsedMesh, scene) {
  45966. var result = new GroundMesh(parsedMesh.name, scene);
  45967. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  45968. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  45969. result._minX = parsedMesh.minX;
  45970. result._maxX = parsedMesh.maxX;
  45971. result._minZ = parsedMesh.minZ;
  45972. result._maxZ = parsedMesh.maxZ;
  45973. result._width = parsedMesh.width;
  45974. result._height = parsedMesh.height;
  45975. return result;
  45976. };
  45977. return GroundMesh;
  45978. }(BABYLON.Mesh));
  45979. BABYLON.GroundMesh = GroundMesh;
  45980. })(BABYLON || (BABYLON = {}));
  45981. //# sourceMappingURL=babylon.groundMesh.js.map
  45982. var BABYLON;
  45983. (function (BABYLON) {
  45984. /**
  45985. * Creates an instance based on a source mesh.
  45986. */
  45987. var InstancedMesh = /** @class */ (function (_super) {
  45988. __extends(InstancedMesh, _super);
  45989. function InstancedMesh(name, source) {
  45990. var _this = _super.call(this, name, source.getScene()) || this;
  45991. source.instances.push(_this);
  45992. _this._sourceMesh = source;
  45993. _this.position.copyFrom(source.position);
  45994. _this.rotation.copyFrom(source.rotation);
  45995. _this.scaling.copyFrom(source.scaling);
  45996. if (source.rotationQuaternion) {
  45997. _this.rotationQuaternion = source.rotationQuaternion.clone();
  45998. }
  45999. _this.infiniteDistance = source.infiniteDistance;
  46000. _this.setPivotMatrix(source.getPivotMatrix());
  46001. _this.refreshBoundingInfo();
  46002. _this._syncSubMeshes();
  46003. return _this;
  46004. }
  46005. /**
  46006. * Returns the string "InstancedMesh".
  46007. */
  46008. InstancedMesh.prototype.getClassName = function () {
  46009. return "InstancedMesh";
  46010. };
  46011. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46012. // Methods
  46013. get: function () {
  46014. return this._sourceMesh.receiveShadows;
  46015. },
  46016. enumerable: true,
  46017. configurable: true
  46018. });
  46019. Object.defineProperty(InstancedMesh.prototype, "material", {
  46020. get: function () {
  46021. return this._sourceMesh.material;
  46022. },
  46023. enumerable: true,
  46024. configurable: true
  46025. });
  46026. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46027. get: function () {
  46028. return this._sourceMesh.visibility;
  46029. },
  46030. enumerable: true,
  46031. configurable: true
  46032. });
  46033. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46034. get: function () {
  46035. return this._sourceMesh.skeleton;
  46036. },
  46037. enumerable: true,
  46038. configurable: true
  46039. });
  46040. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46041. get: function () {
  46042. return this._sourceMesh.renderingGroupId;
  46043. },
  46044. enumerable: true,
  46045. configurable: true
  46046. });
  46047. /**
  46048. * Returns the total number of vertices (integer).
  46049. */
  46050. InstancedMesh.prototype.getTotalVertices = function () {
  46051. return this._sourceMesh.getTotalVertices();
  46052. };
  46053. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46054. get: function () {
  46055. return this._sourceMesh;
  46056. },
  46057. enumerable: true,
  46058. configurable: true
  46059. });
  46060. /**
  46061. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46062. */
  46063. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46064. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46065. };
  46066. /**
  46067. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46068. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46069. * The `data` are either a numeric array either a Float32Array.
  46070. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46071. * 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).
  46072. * Note that a new underlying VertexBuffer object is created each call.
  46073. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46074. *
  46075. * Possible `kind` values :
  46076. * - BABYLON.VertexBuffer.PositionKind
  46077. * - BABYLON.VertexBuffer.UVKind
  46078. * - BABYLON.VertexBuffer.UV2Kind
  46079. * - BABYLON.VertexBuffer.UV3Kind
  46080. * - BABYLON.VertexBuffer.UV4Kind
  46081. * - BABYLON.VertexBuffer.UV5Kind
  46082. * - BABYLON.VertexBuffer.UV6Kind
  46083. * - BABYLON.VertexBuffer.ColorKind
  46084. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46085. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46086. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46087. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46088. *
  46089. * Returns the Mesh.
  46090. */
  46091. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46092. if (this.sourceMesh) {
  46093. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46094. }
  46095. return this.sourceMesh;
  46096. };
  46097. /**
  46098. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46099. * If the mesh has no geometry, it is simply returned as it is.
  46100. * The `data` are either a numeric array either a Float32Array.
  46101. * No new underlying VertexBuffer object is created.
  46102. * 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.
  46103. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46104. *
  46105. * Possible `kind` values :
  46106. * - BABYLON.VertexBuffer.PositionKind
  46107. * - BABYLON.VertexBuffer.UVKind
  46108. * - BABYLON.VertexBuffer.UV2Kind
  46109. * - BABYLON.VertexBuffer.UV3Kind
  46110. * - BABYLON.VertexBuffer.UV4Kind
  46111. * - BABYLON.VertexBuffer.UV5Kind
  46112. * - BABYLON.VertexBuffer.UV6Kind
  46113. * - BABYLON.VertexBuffer.ColorKind
  46114. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46115. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46116. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46117. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46118. *
  46119. * Returns the Mesh.
  46120. */
  46121. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46122. if (this.sourceMesh) {
  46123. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46124. }
  46125. return this.sourceMesh;
  46126. };
  46127. /**
  46128. * Sets the mesh indices.
  46129. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46130. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46131. * This method creates a new index buffer each call.
  46132. * Returns the Mesh.
  46133. */
  46134. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46135. if (totalVertices === void 0) { totalVertices = null; }
  46136. if (this.sourceMesh) {
  46137. this.sourceMesh.setIndices(indices, totalVertices);
  46138. }
  46139. return this.sourceMesh;
  46140. };
  46141. /**
  46142. * Boolean : True if the mesh owns the requested kind of data.
  46143. */
  46144. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46145. return this._sourceMesh.isVerticesDataPresent(kind);
  46146. };
  46147. /**
  46148. * Returns an array of indices (IndicesArray).
  46149. */
  46150. InstancedMesh.prototype.getIndices = function () {
  46151. return this._sourceMesh.getIndices();
  46152. };
  46153. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46154. get: function () {
  46155. return this._sourceMesh._positions;
  46156. },
  46157. enumerable: true,
  46158. configurable: true
  46159. });
  46160. /**
  46161. * Sets a new updated BoundingInfo to the mesh.
  46162. * Returns the mesh.
  46163. */
  46164. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46165. var meshBB = this._sourceMesh.getBoundingInfo();
  46166. if (meshBB) {
  46167. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46168. }
  46169. this._updateBoundingInfo();
  46170. return this;
  46171. };
  46172. InstancedMesh.prototype._preActivate = function () {
  46173. if (this._currentLOD) {
  46174. this._currentLOD._preActivate();
  46175. }
  46176. return this;
  46177. };
  46178. InstancedMesh.prototype._activate = function (renderId) {
  46179. if (this._currentLOD) {
  46180. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46181. }
  46182. return this;
  46183. };
  46184. /**
  46185. * Returns the current associated LOD AbstractMesh.
  46186. */
  46187. InstancedMesh.prototype.getLOD = function (camera) {
  46188. if (!camera) {
  46189. return this;
  46190. }
  46191. var boundingInfo = this.getBoundingInfo();
  46192. if (!boundingInfo) {
  46193. return this;
  46194. }
  46195. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46196. if (this._currentLOD === this.sourceMesh) {
  46197. return this;
  46198. }
  46199. return this._currentLOD;
  46200. };
  46201. InstancedMesh.prototype._syncSubMeshes = function () {
  46202. this.releaseSubMeshes();
  46203. if (this._sourceMesh.subMeshes) {
  46204. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46205. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46206. }
  46207. }
  46208. return this;
  46209. };
  46210. InstancedMesh.prototype._generatePointsArray = function () {
  46211. return this._sourceMesh._generatePointsArray();
  46212. };
  46213. /**
  46214. * Creates a new InstancedMesh from the current mesh.
  46215. * - name (string) : the cloned mesh name
  46216. * - newParent (optional Node) : the optional Node to parent the clone to.
  46217. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46218. *
  46219. * Returns the clone.
  46220. */
  46221. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46222. var result = this._sourceMesh.createInstance(name);
  46223. // Deep copy
  46224. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46225. // Bounding info
  46226. this.refreshBoundingInfo();
  46227. // Parent
  46228. if (newParent) {
  46229. result.parent = newParent;
  46230. }
  46231. if (!doNotCloneChildren) {
  46232. // Children
  46233. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46234. var mesh = this.getScene().meshes[index];
  46235. if (mesh.parent === this) {
  46236. mesh.clone(mesh.name, result);
  46237. }
  46238. }
  46239. }
  46240. result.computeWorldMatrix(true);
  46241. return result;
  46242. };
  46243. /**
  46244. * Disposes the InstancedMesh.
  46245. * Returns nothing.
  46246. */
  46247. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46248. // Remove from mesh
  46249. var index = this._sourceMesh.instances.indexOf(this);
  46250. this._sourceMesh.instances.splice(index, 1);
  46251. _super.prototype.dispose.call(this, doNotRecurse);
  46252. };
  46253. return InstancedMesh;
  46254. }(BABYLON.AbstractMesh));
  46255. BABYLON.InstancedMesh = InstancedMesh;
  46256. })(BABYLON || (BABYLON = {}));
  46257. //# sourceMappingURL=babylon.instancedMesh.js.map
  46258. var BABYLON;
  46259. (function (BABYLON) {
  46260. var LinesMesh = /** @class */ (function (_super) {
  46261. __extends(LinesMesh, _super);
  46262. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  46263. if (scene === void 0) { scene = null; }
  46264. if (parent === void 0) { parent = null; }
  46265. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46266. _this.useVertexColor = useVertexColor;
  46267. _this.color = new BABYLON.Color3(1, 1, 1);
  46268. _this.alpha = 1;
  46269. if (source) {
  46270. _this.color = source.color.clone();
  46271. _this.alpha = source.alpha;
  46272. _this.useVertexColor = source.useVertexColor;
  46273. }
  46274. _this._intersectionThreshold = 0.1;
  46275. var options = {
  46276. attributes: [BABYLON.VertexBuffer.PositionKind],
  46277. uniforms: ["world", "viewProjection"],
  46278. needAlphaBlending: false,
  46279. };
  46280. if (!useVertexColor) {
  46281. options.uniforms.push("color");
  46282. options.needAlphaBlending = true;
  46283. }
  46284. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46285. return _this;
  46286. }
  46287. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46288. /**
  46289. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46290. * This margin is expressed in world space coordinates, so its value may vary.
  46291. * Default value is 0.1
  46292. * @returns the intersection Threshold value.
  46293. */
  46294. get: function () {
  46295. return this._intersectionThreshold;
  46296. },
  46297. /**
  46298. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46299. * This margin is expressed in world space coordinates, so its value may vary.
  46300. * @param value the new threshold to apply
  46301. */
  46302. set: function (value) {
  46303. if (this._intersectionThreshold === value) {
  46304. return;
  46305. }
  46306. this._intersectionThreshold = value;
  46307. if (this.geometry) {
  46308. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46309. }
  46310. },
  46311. enumerable: true,
  46312. configurable: true
  46313. });
  46314. /**
  46315. * Returns the string "LineMesh"
  46316. */
  46317. LinesMesh.prototype.getClassName = function () {
  46318. return "LinesMesh";
  46319. };
  46320. Object.defineProperty(LinesMesh.prototype, "material", {
  46321. get: function () {
  46322. return this._colorShader;
  46323. },
  46324. set: function (value) {
  46325. // Do nothing
  46326. },
  46327. enumerable: true,
  46328. configurable: true
  46329. });
  46330. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46331. get: function () {
  46332. return false;
  46333. },
  46334. enumerable: true,
  46335. configurable: true
  46336. });
  46337. LinesMesh.prototype.createInstance = function (name) {
  46338. throw new Error("LinesMeshes do not support createInstance.");
  46339. };
  46340. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46341. if (!this._geometry) {
  46342. return this;
  46343. }
  46344. // VBOs
  46345. this._geometry._bind(this._colorShader.getEffect());
  46346. // Color
  46347. if (!this.useVertexColor) {
  46348. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46349. }
  46350. return this;
  46351. };
  46352. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46353. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46354. return this;
  46355. }
  46356. var engine = this.getScene().getEngine();
  46357. // Draw order
  46358. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46359. return this;
  46360. };
  46361. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46362. this._colorShader.dispose();
  46363. _super.prototype.dispose.call(this, doNotRecurse);
  46364. };
  46365. /**
  46366. * Returns a new LineMesh object cloned from the current one.
  46367. */
  46368. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46369. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  46370. };
  46371. return LinesMesh;
  46372. }(BABYLON.Mesh));
  46373. BABYLON.LinesMesh = LinesMesh;
  46374. })(BABYLON || (BABYLON = {}));
  46375. //# sourceMappingURL=babylon.linesMesh.js.map
  46376. var BABYLON;
  46377. (function (BABYLON) {
  46378. var ShaderMaterial = /** @class */ (function (_super) {
  46379. __extends(ShaderMaterial, _super);
  46380. function ShaderMaterial(name, scene, shaderPath, options) {
  46381. var _this = _super.call(this, name, scene) || this;
  46382. _this._textures = {};
  46383. _this._textureArrays = {};
  46384. _this._floats = {};
  46385. _this._floatsArrays = {};
  46386. _this._colors3 = {};
  46387. _this._colors3Arrays = {};
  46388. _this._colors4 = {};
  46389. _this._vectors2 = {};
  46390. _this._vectors3 = {};
  46391. _this._vectors4 = {};
  46392. _this._matrices = {};
  46393. _this._matrices3x3 = {};
  46394. _this._matrices2x2 = {};
  46395. _this._vectors3Arrays = {};
  46396. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46397. _this._shaderPath = shaderPath;
  46398. options.needAlphaBlending = options.needAlphaBlending || false;
  46399. options.needAlphaTesting = options.needAlphaTesting || false;
  46400. options.attributes = options.attributes || ["position", "normal", "uv"];
  46401. options.uniforms = options.uniforms || ["worldViewProjection"];
  46402. options.uniformBuffers = options.uniformBuffers || [];
  46403. options.samplers = options.samplers || [];
  46404. options.defines = options.defines || [];
  46405. _this._options = options;
  46406. return _this;
  46407. }
  46408. ShaderMaterial.prototype.getClassName = function () {
  46409. return "ShaderMaterial";
  46410. };
  46411. ShaderMaterial.prototype.needAlphaBlending = function () {
  46412. return this._options.needAlphaBlending;
  46413. };
  46414. ShaderMaterial.prototype.needAlphaTesting = function () {
  46415. return this._options.needAlphaTesting;
  46416. };
  46417. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46418. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46419. this._options.uniforms.push(uniformName);
  46420. }
  46421. };
  46422. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46423. if (this._options.samplers.indexOf(name) === -1) {
  46424. this._options.samplers.push(name);
  46425. }
  46426. this._textures[name] = texture;
  46427. return this;
  46428. };
  46429. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46430. if (this._options.samplers.indexOf(name) === -1) {
  46431. this._options.samplers.push(name);
  46432. }
  46433. this._checkUniform(name);
  46434. this._textureArrays[name] = textures;
  46435. return this;
  46436. };
  46437. ShaderMaterial.prototype.setFloat = function (name, value) {
  46438. this._checkUniform(name);
  46439. this._floats[name] = value;
  46440. return this;
  46441. };
  46442. ShaderMaterial.prototype.setFloats = function (name, value) {
  46443. this._checkUniform(name);
  46444. this._floatsArrays[name] = value;
  46445. return this;
  46446. };
  46447. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46448. this._checkUniform(name);
  46449. this._colors3[name] = value;
  46450. return this;
  46451. };
  46452. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  46453. this._checkUniform(name);
  46454. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  46455. color.toArray(arr, arr.length);
  46456. return arr;
  46457. }, []);
  46458. return this;
  46459. };
  46460. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46461. this._checkUniform(name);
  46462. this._colors4[name] = value;
  46463. return this;
  46464. };
  46465. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46466. this._checkUniform(name);
  46467. this._vectors2[name] = value;
  46468. return this;
  46469. };
  46470. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46471. this._checkUniform(name);
  46472. this._vectors3[name] = value;
  46473. return this;
  46474. };
  46475. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46476. this._checkUniform(name);
  46477. this._vectors4[name] = value;
  46478. return this;
  46479. };
  46480. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46481. this._checkUniform(name);
  46482. this._matrices[name] = value;
  46483. return this;
  46484. };
  46485. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46486. this._checkUniform(name);
  46487. this._matrices3x3[name] = value;
  46488. return this;
  46489. };
  46490. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46491. this._checkUniform(name);
  46492. this._matrices2x2[name] = value;
  46493. return this;
  46494. };
  46495. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46496. this._checkUniform(name);
  46497. this._vectors3Arrays[name] = value;
  46498. return this;
  46499. };
  46500. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46501. if (!mesh) {
  46502. return true;
  46503. }
  46504. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46505. return false;
  46506. }
  46507. return false;
  46508. };
  46509. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46510. var scene = this.getScene();
  46511. var engine = scene.getEngine();
  46512. if (!this.checkReadyOnEveryCall) {
  46513. if (this._renderId === scene.getRenderId()) {
  46514. if (this._checkCache(scene, mesh, useInstances)) {
  46515. return true;
  46516. }
  46517. }
  46518. }
  46519. // Instances
  46520. var defines = [];
  46521. var attribs = [];
  46522. var fallbacks = new BABYLON.EffectFallbacks();
  46523. if (useInstances) {
  46524. defines.push("#define INSTANCES");
  46525. }
  46526. for (var index = 0; index < this._options.defines.length; index++) {
  46527. defines.push(this._options.defines[index]);
  46528. }
  46529. for (var index = 0; index < this._options.attributes.length; index++) {
  46530. attribs.push(this._options.attributes[index]);
  46531. }
  46532. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  46533. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46534. defines.push("#define VERTEXCOLOR");
  46535. }
  46536. // Bones
  46537. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  46538. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46539. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46540. if (mesh.numBoneInfluencers > 4) {
  46541. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46542. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46543. }
  46544. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46545. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46546. fallbacks.addCPUSkinningFallback(0, mesh);
  46547. if (this._options.uniforms.indexOf("mBones") === -1) {
  46548. this._options.uniforms.push("mBones");
  46549. }
  46550. }
  46551. else {
  46552. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46553. }
  46554. // Textures
  46555. for (var name in this._textures) {
  46556. if (!this._textures[name].isReady()) {
  46557. return false;
  46558. }
  46559. }
  46560. // Alpha test
  46561. if (engine.getAlphaTesting()) {
  46562. defines.push("#define ALPHATEST");
  46563. }
  46564. var previousEffect = this._effect;
  46565. var join = defines.join("\n");
  46566. this._effect = engine.createEffect(this._shaderPath, {
  46567. attributes: attribs,
  46568. uniformsNames: this._options.uniforms,
  46569. uniformBuffersNames: this._options.uniformBuffers,
  46570. samplers: this._options.samplers,
  46571. defines: join,
  46572. fallbacks: fallbacks,
  46573. onCompiled: this.onCompiled,
  46574. onError: this.onError
  46575. }, engine);
  46576. if (!this._effect.isReady()) {
  46577. return false;
  46578. }
  46579. if (previousEffect !== this._effect) {
  46580. scene.resetCachedMaterial();
  46581. }
  46582. this._renderId = scene.getRenderId();
  46583. return true;
  46584. };
  46585. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46586. var scene = this.getScene();
  46587. if (!this._effect) {
  46588. return;
  46589. }
  46590. if (this._options.uniforms.indexOf("world") !== -1) {
  46591. this._effect.setMatrix("world", world);
  46592. }
  46593. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46594. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46595. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46596. }
  46597. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46598. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46599. }
  46600. };
  46601. ShaderMaterial.prototype.bind = function (world, mesh) {
  46602. // Std values
  46603. this.bindOnlyWorldMatrix(world);
  46604. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  46605. if (this._options.uniforms.indexOf("view") !== -1) {
  46606. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46607. }
  46608. if (this._options.uniforms.indexOf("projection") !== -1) {
  46609. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46610. }
  46611. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46612. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46613. }
  46614. // Bones
  46615. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46616. var name;
  46617. // Texture
  46618. for (name in this._textures) {
  46619. this._effect.setTexture(name, this._textures[name]);
  46620. }
  46621. // Texture arrays
  46622. for (name in this._textureArrays) {
  46623. this._effect.setTextureArray(name, this._textureArrays[name]);
  46624. }
  46625. // Float
  46626. for (name in this._floats) {
  46627. this._effect.setFloat(name, this._floats[name]);
  46628. }
  46629. // Float s
  46630. for (name in this._floatsArrays) {
  46631. this._effect.setArray(name, this._floatsArrays[name]);
  46632. }
  46633. // Color3
  46634. for (name in this._colors3) {
  46635. this._effect.setColor3(name, this._colors3[name]);
  46636. }
  46637. for (name in this._colors3Arrays) {
  46638. this._effect.setArray3(name, this._colors3Arrays[name]);
  46639. }
  46640. // Color4
  46641. for (name in this._colors4) {
  46642. var color = this._colors4[name];
  46643. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46644. }
  46645. // Vector2
  46646. for (name in this._vectors2) {
  46647. this._effect.setVector2(name, this._vectors2[name]);
  46648. }
  46649. // Vector3
  46650. for (name in this._vectors3) {
  46651. this._effect.setVector3(name, this._vectors3[name]);
  46652. }
  46653. // Vector4
  46654. for (name in this._vectors4) {
  46655. this._effect.setVector4(name, this._vectors4[name]);
  46656. }
  46657. // Matrix
  46658. for (name in this._matrices) {
  46659. this._effect.setMatrix(name, this._matrices[name]);
  46660. }
  46661. // Matrix 3x3
  46662. for (name in this._matrices3x3) {
  46663. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46664. }
  46665. // Matrix 2x2
  46666. for (name in this._matrices2x2) {
  46667. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46668. }
  46669. // Vector3Array
  46670. for (name in this._vectors3Arrays) {
  46671. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46672. }
  46673. }
  46674. this._afterBind(mesh);
  46675. };
  46676. ShaderMaterial.prototype.getActiveTextures = function () {
  46677. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46678. for (var name in this._textures) {
  46679. activeTextures.push(this._textures[name]);
  46680. }
  46681. for (var name in this._textureArrays) {
  46682. var array = this._textureArrays[name];
  46683. for (var index = 0; index < array.length; index++) {
  46684. activeTextures.push(array[index]);
  46685. }
  46686. }
  46687. return activeTextures;
  46688. };
  46689. ShaderMaterial.prototype.hasTexture = function (texture) {
  46690. if (_super.prototype.hasTexture.call(this, texture)) {
  46691. return true;
  46692. }
  46693. for (var name in this._textures) {
  46694. if (this._textures[name] === texture) {
  46695. return true;
  46696. }
  46697. }
  46698. for (var name in this._textureArrays) {
  46699. var array = this._textureArrays[name];
  46700. for (var index = 0; index < array.length; index++) {
  46701. if (array[index] === texture) {
  46702. return true;
  46703. }
  46704. }
  46705. }
  46706. return false;
  46707. };
  46708. ShaderMaterial.prototype.clone = function (name) {
  46709. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46710. return newShaderMaterial;
  46711. };
  46712. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46713. if (forceDisposeTextures) {
  46714. var name;
  46715. for (name in this._textures) {
  46716. this._textures[name].dispose();
  46717. }
  46718. for (name in this._textureArrays) {
  46719. var array = this._textureArrays[name];
  46720. for (var index = 0; index < array.length; index++) {
  46721. array[index].dispose();
  46722. }
  46723. }
  46724. }
  46725. this._textures = {};
  46726. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46727. };
  46728. ShaderMaterial.prototype.serialize = function () {
  46729. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46730. serializationObject.customType = "BABYLON.ShaderMaterial";
  46731. serializationObject.options = this._options;
  46732. serializationObject.shaderPath = this._shaderPath;
  46733. var name;
  46734. // Texture
  46735. serializationObject.textures = {};
  46736. for (name in this._textures) {
  46737. serializationObject.textures[name] = this._textures[name].serialize();
  46738. }
  46739. // Texture arrays
  46740. serializationObject.textureArrays = {};
  46741. for (name in this._textureArrays) {
  46742. serializationObject.textureArrays[name] = [];
  46743. var array = this._textureArrays[name];
  46744. for (var index = 0; index < array.length; index++) {
  46745. serializationObject.textureArrays[name].push(array[index].serialize());
  46746. }
  46747. }
  46748. // Float
  46749. serializationObject.floats = {};
  46750. for (name in this._floats) {
  46751. serializationObject.floats[name] = this._floats[name];
  46752. }
  46753. // Float s
  46754. serializationObject.FloatArrays = {};
  46755. for (name in this._floatsArrays) {
  46756. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  46757. }
  46758. // Color3
  46759. serializationObject.colors3 = {};
  46760. for (name in this._colors3) {
  46761. serializationObject.colors3[name] = this._colors3[name].asArray();
  46762. }
  46763. // Color3 array
  46764. serializationObject.colors3Arrays = {};
  46765. for (name in this._colors3Arrays) {
  46766. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  46767. }
  46768. // Color4
  46769. serializationObject.colors4 = {};
  46770. for (name in this._colors4) {
  46771. serializationObject.colors4[name] = this._colors4[name].asArray();
  46772. }
  46773. // Vector2
  46774. serializationObject.vectors2 = {};
  46775. for (name in this._vectors2) {
  46776. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46777. }
  46778. // Vector3
  46779. serializationObject.vectors3 = {};
  46780. for (name in this._vectors3) {
  46781. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46782. }
  46783. // Vector4
  46784. serializationObject.vectors4 = {};
  46785. for (name in this._vectors4) {
  46786. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46787. }
  46788. // Matrix
  46789. serializationObject.matrices = {};
  46790. for (name in this._matrices) {
  46791. serializationObject.matrices[name] = this._matrices[name].asArray();
  46792. }
  46793. // Matrix 3x3
  46794. serializationObject.matrices3x3 = {};
  46795. for (name in this._matrices3x3) {
  46796. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46797. }
  46798. // Matrix 2x2
  46799. serializationObject.matrices2x2 = {};
  46800. for (name in this._matrices2x2) {
  46801. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46802. }
  46803. // Vector3Array
  46804. serializationObject.vectors3Arrays = {};
  46805. for (name in this._vectors3Arrays) {
  46806. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46807. }
  46808. return serializationObject;
  46809. };
  46810. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46811. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46812. var name;
  46813. // Texture
  46814. for (name in source.textures) {
  46815. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46816. }
  46817. // Texture arrays
  46818. for (name in source.textureArrays) {
  46819. var array = source.textureArrays[name];
  46820. var textureArray = new Array();
  46821. for (var index = 0; index < array.length; index++) {
  46822. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46823. }
  46824. material.setTextureArray(name, textureArray);
  46825. }
  46826. // Float
  46827. for (name in source.floats) {
  46828. material.setFloat(name, source.floats[name]);
  46829. }
  46830. // Float s
  46831. for (name in source.floatsArrays) {
  46832. material.setFloats(name, source.floatsArrays[name]);
  46833. }
  46834. // Color3
  46835. for (name in source.colors3) {
  46836. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46837. }
  46838. // Color3 arrays
  46839. for (name in source.colors3Arrays) {
  46840. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  46841. if (i % 3 === 0) {
  46842. arr.push([num]);
  46843. }
  46844. else {
  46845. arr[arr.length - 1].push(num);
  46846. }
  46847. return arr;
  46848. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  46849. material.setColor3Array(name, colors);
  46850. }
  46851. // Color4
  46852. for (name in source.colors4) {
  46853. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46854. }
  46855. // Vector2
  46856. for (name in source.vectors2) {
  46857. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46858. }
  46859. // Vector3
  46860. for (name in source.vectors3) {
  46861. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46862. }
  46863. // Vector4
  46864. for (name in source.vectors4) {
  46865. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46866. }
  46867. // Matrix
  46868. for (name in source.matrices) {
  46869. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46870. }
  46871. // Matrix 3x3
  46872. for (name in source.matrices3x3) {
  46873. material.setMatrix3x3(name, source.matrices3x3[name]);
  46874. }
  46875. // Matrix 2x2
  46876. for (name in source.matrices2x2) {
  46877. material.setMatrix2x2(name, source.matrices2x2[name]);
  46878. }
  46879. // Vector3Array
  46880. for (name in source.vectors3Arrays) {
  46881. material.setArray3(name, source.vectors3Arrays[name]);
  46882. }
  46883. return material;
  46884. };
  46885. return ShaderMaterial;
  46886. }(BABYLON.Material));
  46887. BABYLON.ShaderMaterial = ShaderMaterial;
  46888. })(BABYLON || (BABYLON = {}));
  46889. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46890. var BABYLON;
  46891. (function (BABYLON) {
  46892. var MeshBuilder = /** @class */ (function () {
  46893. function MeshBuilder() {
  46894. }
  46895. MeshBuilder.updateSideOrientation = function (orientation) {
  46896. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  46897. return BABYLON.Mesh.DOUBLESIDE;
  46898. }
  46899. if (orientation === undefined || orientation === null) {
  46900. return BABYLON.Mesh.FRONTSIDE;
  46901. }
  46902. return orientation;
  46903. };
  46904. /**
  46905. * Creates a box mesh.
  46906. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  46907. * The parameter `size` sets the size (float) of each box side (default 1).
  46908. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  46909. * 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).
  46910. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46911. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46912. * 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).
  46913. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46914. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46915. */
  46916. MeshBuilder.CreateBox = function (name, options, scene) {
  46917. if (scene === void 0) { scene = null; }
  46918. var box = new BABYLON.Mesh(name, scene);
  46919. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46920. box._originalBuilderSideOrientation = options.sideOrientation;
  46921. var vertexData = BABYLON.VertexData.CreateBox(options);
  46922. vertexData.applyToMesh(box, options.updatable);
  46923. return box;
  46924. };
  46925. /**
  46926. * Creates a sphere mesh.
  46927. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  46928. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  46929. * 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`).
  46930. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  46931. * 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
  46932. * 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).
  46933. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46934. * 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).
  46935. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46936. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46937. */
  46938. MeshBuilder.CreateSphere = function (name, options, scene) {
  46939. var sphere = new BABYLON.Mesh(name, scene);
  46940. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46941. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46942. var vertexData = BABYLON.VertexData.CreateSphere(options);
  46943. vertexData.applyToMesh(sphere, options.updatable);
  46944. return sphere;
  46945. };
  46946. /**
  46947. * Creates a plane polygonal mesh. By default, this is a disc.
  46948. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  46949. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  46950. * 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.
  46951. * 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
  46952. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46953. * 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).
  46954. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46956. */
  46957. MeshBuilder.CreateDisc = function (name, options, scene) {
  46958. if (scene === void 0) { scene = null; }
  46959. var disc = new BABYLON.Mesh(name, scene);
  46960. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46961. disc._originalBuilderSideOrientation = options.sideOrientation;
  46962. var vertexData = BABYLON.VertexData.CreateDisc(options);
  46963. vertexData.applyToMesh(disc, options.updatable);
  46964. return disc;
  46965. };
  46966. /**
  46967. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  46968. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  46969. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  46970. * 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`).
  46971. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  46972. * 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.
  46973. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46974. * 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).
  46975. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46976. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46977. */
  46978. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  46979. var sphere = new BABYLON.Mesh(name, scene);
  46980. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46981. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46982. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  46983. vertexData.applyToMesh(sphere, options.updatable);
  46984. return sphere;
  46985. };
  46986. ;
  46987. /**
  46988. * Creates a ribbon mesh.
  46989. * 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.
  46990. *
  46991. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  46992. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  46993. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  46994. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  46995. * 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.
  46996. * 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.
  46997. * 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
  46998. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46999. * 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).
  47000. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47001. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47002. * 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.
  47003. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  47004. * 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
  47005. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47006. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47007. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47008. */
  47009. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47010. if (scene === void 0) { scene = null; }
  47011. var pathArray = options.pathArray;
  47012. var closeArray = options.closeArray;
  47013. var closePath = options.closePath;
  47014. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47015. var instance = options.instance;
  47016. var updatable = options.updatable;
  47017. if (instance) {
  47018. // positionFunction : ribbon case
  47019. // only pathArray and sideOrientation parameters are taken into account for positions update
  47020. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47021. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47022. var positionFunction = function (positions) {
  47023. var minlg = pathArray[0].length;
  47024. var i = 0;
  47025. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47026. for (var si = 1; si <= ns; si++) {
  47027. for (var p = 0; p < pathArray.length; p++) {
  47028. var path = pathArray[p];
  47029. var l = path.length;
  47030. minlg = (minlg < l) ? minlg : l;
  47031. var j = 0;
  47032. while (j < minlg) {
  47033. positions[i] = path[j].x;
  47034. positions[i + 1] = path[j].y;
  47035. positions[i + 2] = path[j].z;
  47036. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47037. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47038. }
  47039. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47040. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47041. }
  47042. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47043. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47044. }
  47045. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47046. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47047. }
  47048. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47049. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47050. }
  47051. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47052. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47053. }
  47054. j++;
  47055. i += 3;
  47056. }
  47057. if (instance._closePath) {
  47058. positions[i] = path[0].x;
  47059. positions[i + 1] = path[0].y;
  47060. positions[i + 2] = path[0].z;
  47061. i += 3;
  47062. }
  47063. }
  47064. }
  47065. };
  47066. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47067. positionFunction(positions);
  47068. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  47069. instance._boundingInfo.update(instance._worldMatrix);
  47070. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47071. if (options.colors) {
  47072. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47073. for (var c = 0; c < options.colors.length; c++) {
  47074. colors[c * 4] = options.colors[c].r;
  47075. colors[c * 4 + 1] = options.colors[c].g;
  47076. colors[c * 4 + 2] = options.colors[c].b;
  47077. colors[c * 4 + 3] = options.colors[c].a;
  47078. }
  47079. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  47080. }
  47081. if (options.uvs) {
  47082. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47083. for (var i = 0; i < options.uvs.length; i++) {
  47084. uvs[i * 2] = options.uvs[i].x;
  47085. uvs[i * 2 + 1] = options.uvs[i].y;
  47086. }
  47087. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  47088. }
  47089. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  47090. var indices = instance.getIndices();
  47091. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47092. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47093. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47094. if (instance._closePath) {
  47095. var indexFirst = 0;
  47096. var indexLast = 0;
  47097. for (var p = 0; p < pathArray.length; p++) {
  47098. indexFirst = instance._idx[p] * 3;
  47099. if (p + 1 < pathArray.length) {
  47100. indexLast = (instance._idx[p + 1] - 1) * 3;
  47101. }
  47102. else {
  47103. indexLast = normals.length - 3;
  47104. }
  47105. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47106. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47107. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47108. normals[indexLast] = normals[indexFirst];
  47109. normals[indexLast + 1] = normals[indexFirst + 1];
  47110. normals[indexLast + 2] = normals[indexFirst + 2];
  47111. }
  47112. }
  47113. if (!(instance.areNormalsFrozen)) {
  47114. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47115. }
  47116. }
  47117. return instance;
  47118. }
  47119. else {
  47120. var ribbon = new BABYLON.Mesh(name, scene);
  47121. ribbon._originalBuilderSideOrientation = sideOrientation;
  47122. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47123. if (closePath) {
  47124. ribbon._idx = vertexData._idx;
  47125. }
  47126. ribbon._closePath = closePath;
  47127. ribbon._closeArray = closeArray;
  47128. vertexData.applyToMesh(ribbon, updatable);
  47129. return ribbon;
  47130. }
  47131. };
  47132. /**
  47133. * Creates a cylinder or a cone mesh.
  47134. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  47135. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  47136. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  47137. * 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.
  47138. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  47139. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  47140. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  47141. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  47142. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  47143. * 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).
  47144. * 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
  47145. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  47146. * 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
  47147. * 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.
  47148. * If `enclose` is false, a ring surface is one element.
  47149. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  47150. * 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
  47151. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47152. * 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).
  47153. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47154. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47155. */
  47156. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47157. var cylinder = new BABYLON.Mesh(name, scene);
  47158. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47159. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47160. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47161. vertexData.applyToMesh(cylinder, options.updatable);
  47162. return cylinder;
  47163. };
  47164. /**
  47165. * Creates a torus mesh.
  47166. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47167. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47168. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47169. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47171. * 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).
  47172. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47174. */
  47175. MeshBuilder.CreateTorus = function (name, options, scene) {
  47176. var torus = new BABYLON.Mesh(name, scene);
  47177. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47178. torus._originalBuilderSideOrientation = options.sideOrientation;
  47179. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47180. vertexData.applyToMesh(torus, options.updatable);
  47181. return torus;
  47182. };
  47183. /**
  47184. * Creates a torus knot mesh.
  47185. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47186. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47187. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47188. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47189. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47190. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47191. * 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).
  47192. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47193. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47194. */
  47195. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47196. var torusKnot = new BABYLON.Mesh(name, scene);
  47197. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47198. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47199. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47200. vertexData.applyToMesh(torusKnot, options.updatable);
  47201. return torusKnot;
  47202. };
  47203. /**
  47204. * Creates a line system mesh.
  47205. * A line system is a pool of many lines gathered in a single mesh.
  47206. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47207. * 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.
  47208. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47209. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47210. * 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
  47211. * 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
  47212. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47213. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47214. */
  47215. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47216. var instance = options.instance;
  47217. var lines = options.lines;
  47218. if (instance) {
  47219. var positionFunction = function (positions) {
  47220. var i = 0;
  47221. for (var l = 0; l < lines.length; l++) {
  47222. var points = lines[l];
  47223. for (var p = 0; p < points.length; p++) {
  47224. positions[i] = points[p].x;
  47225. positions[i + 1] = points[p].y;
  47226. positions[i + 2] = points[p].z;
  47227. i += 3;
  47228. }
  47229. }
  47230. };
  47231. instance.updateMeshPositions(positionFunction, false);
  47232. return instance;
  47233. }
  47234. // line system creation
  47235. var lineSystem = new BABYLON.LinesMesh(name, scene);
  47236. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47237. vertexData.applyToMesh(lineSystem, options.updatable);
  47238. return lineSystem;
  47239. };
  47240. /**
  47241. * Creates a line mesh.
  47242. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47243. * 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.
  47244. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47245. * The parameter `points` is an array successive Vector3.
  47246. * 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
  47247. * When updating an instance, remember that only point positions can change, not the number of points.
  47248. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47249. */
  47250. MeshBuilder.CreateLines = function (name, options, scene) {
  47251. if (scene === void 0) { scene = null; }
  47252. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  47253. return lines;
  47254. };
  47255. /**
  47256. * Creates a dashed line mesh.
  47257. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47258. * 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.
  47259. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47260. * The parameter `points` is an array successive Vector3.
  47261. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47262. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47263. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47264. * 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
  47265. * When updating an instance, remember that only point positions can change, not the number of points.
  47266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47267. */
  47268. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47269. if (scene === void 0) { scene = null; }
  47270. var points = options.points;
  47271. var instance = options.instance;
  47272. var gapSize = options.gapSize || 1;
  47273. var dashSize = options.dashSize || 3;
  47274. if (instance) {
  47275. var positionFunction = function (positions) {
  47276. var curvect = BABYLON.Vector3.Zero();
  47277. var nbSeg = positions.length / 6;
  47278. var lg = 0;
  47279. var nb = 0;
  47280. var shft = 0;
  47281. var dashshft = 0;
  47282. var curshft = 0;
  47283. var p = 0;
  47284. var i = 0;
  47285. var j = 0;
  47286. for (i = 0; i < points.length - 1; i++) {
  47287. points[i + 1].subtractToRef(points[i], curvect);
  47288. lg += curvect.length();
  47289. }
  47290. shft = lg / nbSeg;
  47291. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47292. for (i = 0; i < points.length - 1; i++) {
  47293. points[i + 1].subtractToRef(points[i], curvect);
  47294. nb = Math.floor(curvect.length() / shft);
  47295. curvect.normalize();
  47296. j = 0;
  47297. while (j < nb && p < positions.length) {
  47298. curshft = shft * j;
  47299. positions[p] = points[i].x + curshft * curvect.x;
  47300. positions[p + 1] = points[i].y + curshft * curvect.y;
  47301. positions[p + 2] = points[i].z + curshft * curvect.z;
  47302. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47303. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47304. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47305. p += 6;
  47306. j++;
  47307. }
  47308. }
  47309. while (p < positions.length) {
  47310. positions[p] = points[i].x;
  47311. positions[p + 1] = points[i].y;
  47312. positions[p + 2] = points[i].z;
  47313. p += 3;
  47314. }
  47315. };
  47316. instance.updateMeshPositions(positionFunction, false);
  47317. return instance;
  47318. }
  47319. // dashed lines creation
  47320. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47321. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47322. vertexData.applyToMesh(dashedLines, options.updatable);
  47323. dashedLines.dashSize = dashSize;
  47324. dashedLines.gapSize = gapSize;
  47325. return dashedLines;
  47326. };
  47327. /**
  47328. * Creates an extruded shape mesh.
  47329. * 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.
  47330. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47331. *
  47332. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47333. * 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
  47334. * extruded along the Z axis.
  47335. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47336. * 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.
  47337. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47338. * 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
  47339. * 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
  47340. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47342. * 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).
  47343. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47344. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47345. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47346. */
  47347. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  47348. if (scene === void 0) { scene = null; }
  47349. var path = options.path;
  47350. var shape = options.shape;
  47351. var scale = options.scale || 1;
  47352. var rotation = options.rotation || 0;
  47353. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47354. var updatable = options.updatable;
  47355. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47356. var instance = options.instance || null;
  47357. var invertUV = options.invertUV || false;
  47358. 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);
  47359. };
  47360. /**
  47361. * Creates an custom extruded shape mesh.
  47362. * 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.
  47363. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  47364. *
  47365. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47366. * 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
  47367. * extruded along the Z axis.
  47368. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47369. * 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
  47370. * and the distance of this point from the begining of the path :
  47371. * ```javascript
  47372. * var rotationFunction = function(i, distance) {
  47373. * // do things
  47374. * return rotationValue; }
  47375. * ```
  47376. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  47377. * 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
  47378. * and the distance of this point from the begining of the path :
  47379. * ```javascript
  47380. * var scaleFunction = function(i, distance) {
  47381. * // do things
  47382. * return scaleValue;}
  47383. * ```
  47384. * It must returns a float value that will be the scale value applied to the shape on each path point.
  47385. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  47386. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  47387. * 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
  47388. * 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
  47389. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47390. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47391. * 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).
  47392. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47393. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47394. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47395. */
  47396. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  47397. var path = options.path;
  47398. var shape = options.shape;
  47399. var scaleFunction = options.scaleFunction || (function () { return 1; });
  47400. var rotationFunction = options.rotationFunction || (function () { return 0; });
  47401. var ribbonCloseArray = options.ribbonCloseArray || false;
  47402. var ribbonClosePath = options.ribbonClosePath || false;
  47403. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47404. var updatable = options.updatable;
  47405. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47406. var instance = options.instance;
  47407. var invertUV = options.invertUV || false;
  47408. 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);
  47409. };
  47410. /**
  47411. * Creates lathe mesh.
  47412. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  47413. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  47414. *
  47415. * 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
  47416. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  47417. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  47418. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  47419. * 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.
  47420. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  47421. * 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
  47422. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47423. * 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).
  47424. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47425. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47426. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47427. */
  47428. MeshBuilder.CreateLathe = function (name, options, scene) {
  47429. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  47430. var closed = (options.closed === undefined) ? true : options.closed;
  47431. var shape = options.shape;
  47432. var radius = options.radius || 1;
  47433. var tessellation = options.tessellation || 64;
  47434. var updatable = options.updatable;
  47435. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47436. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47437. var pi2 = Math.PI * 2;
  47438. var paths = new Array();
  47439. var invertUV = options.invertUV || false;
  47440. var i = 0;
  47441. var p = 0;
  47442. var step = pi2 / tessellation * arc;
  47443. var rotated;
  47444. var path = new Array();
  47445. ;
  47446. for (i = 0; i <= tessellation; i++) {
  47447. var path = [];
  47448. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  47449. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  47450. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  47451. }
  47452. for (p = 0; p < shape.length; p++) {
  47453. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  47454. path.push(rotated);
  47455. }
  47456. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  47457. 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));
  47458. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  47459. }
  47460. paths.push(path);
  47461. }
  47462. // lathe ribbon
  47463. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47464. return lathe;
  47465. };
  47466. /**
  47467. * Creates a plane mesh.
  47468. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47469. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  47470. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  47471. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  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 mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47476. */
  47477. MeshBuilder.CreatePlane = function (name, options, scene) {
  47478. var plane = new BABYLON.Mesh(name, scene);
  47479. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47480. plane._originalBuilderSideOrientation = options.sideOrientation;
  47481. var vertexData = BABYLON.VertexData.CreatePlane(options);
  47482. vertexData.applyToMesh(plane, options.updatable);
  47483. if (options.sourcePlane) {
  47484. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  47485. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  47486. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  47487. plane.rotate(vectorProduct, product);
  47488. }
  47489. return plane;
  47490. };
  47491. /**
  47492. * Creates a ground mesh.
  47493. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47494. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  47495. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  47496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47497. */
  47498. MeshBuilder.CreateGround = function (name, options, scene) {
  47499. var ground = new BABYLON.GroundMesh(name, scene);
  47500. ground._setReady(false);
  47501. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  47502. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  47503. ground._width = options.width || 1;
  47504. ground._height = options.height || 1;
  47505. ground._maxX = ground._width / 2;
  47506. ground._maxZ = ground._height / 2;
  47507. ground._minX = -ground._maxX;
  47508. ground._minZ = -ground._maxZ;
  47509. var vertexData = BABYLON.VertexData.CreateGround(options);
  47510. vertexData.applyToMesh(ground, options.updatable);
  47511. ground._setReady(true);
  47512. return ground;
  47513. };
  47514. /**
  47515. * Creates a tiled ground mesh.
  47516. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  47517. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  47518. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  47519. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  47520. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  47521. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  47522. * numbers of subdivisions on the ground width and height of each tile.
  47523. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47524. */
  47525. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  47526. var tiledGround = new BABYLON.Mesh(name, scene);
  47527. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  47528. vertexData.applyToMesh(tiledGround, options.updatable);
  47529. return tiledGround;
  47530. };
  47531. /**
  47532. * Creates a ground mesh from a height map.
  47533. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  47534. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  47535. * The parameter `url` sets the URL of the height map image resource.
  47536. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  47537. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  47538. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  47539. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  47540. * 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.
  47541. * 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).
  47542. * This function is passed the newly built mesh :
  47543. * ```javascript
  47544. * function(mesh) { // do things
  47545. * return; }
  47546. * ```
  47547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47548. */
  47549. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  47550. var width = options.width || 10.0;
  47551. var height = options.height || 10.0;
  47552. var subdivisions = options.subdivisions || 1 | 0;
  47553. var minHeight = options.minHeight || 0.0;
  47554. var maxHeight = options.maxHeight || 1.0;
  47555. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  47556. var updatable = options.updatable;
  47557. var onReady = options.onReady;
  47558. var ground = new BABYLON.GroundMesh(name, scene);
  47559. ground._subdivisionsX = subdivisions;
  47560. ground._subdivisionsY = subdivisions;
  47561. ground._width = width;
  47562. ground._height = height;
  47563. ground._maxX = ground._width / 2.0;
  47564. ground._maxZ = ground._height / 2.0;
  47565. ground._minX = -ground._maxX;
  47566. ground._minZ = -ground._maxZ;
  47567. ground._setReady(false);
  47568. var onload = function (img) {
  47569. // Getting height map data
  47570. var canvas = document.createElement("canvas");
  47571. var context = canvas.getContext("2d");
  47572. if (!context) {
  47573. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  47574. }
  47575. var bufferWidth = img.width;
  47576. var bufferHeight = img.height;
  47577. canvas.width = bufferWidth;
  47578. canvas.height = bufferHeight;
  47579. context.drawImage(img, 0, 0);
  47580. // Create VertexData from map data
  47581. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  47582. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  47583. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  47584. width: width, height: height,
  47585. subdivisions: subdivisions,
  47586. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  47587. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  47588. });
  47589. vertexData.applyToMesh(ground, updatable);
  47590. ground._setReady(true);
  47591. //execute ready callback, if set
  47592. if (onReady) {
  47593. onReady(ground);
  47594. }
  47595. };
  47596. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  47597. return ground;
  47598. };
  47599. /**
  47600. * Creates a polygon mesh.
  47601. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  47602. * 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.
  47603. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47604. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47605. * 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).
  47606. * Remember you can only change the shape positions, not their number when updating a polygon.
  47607. */
  47608. MeshBuilder.CreatePolygon = function (name, options, scene) {
  47609. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47610. var shape = options.shape;
  47611. var holes = options.holes || [];
  47612. var depth = options.depth || 0;
  47613. var contours = [];
  47614. var hole = [];
  47615. for (var i = 0; i < shape.length; i++) {
  47616. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  47617. }
  47618. var epsilon = 0.00000001;
  47619. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  47620. contours.pop();
  47621. }
  47622. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  47623. for (var hNb = 0; hNb < holes.length; hNb++) {
  47624. hole = [];
  47625. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  47626. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  47627. }
  47628. polygonTriangulation.addHole(hole);
  47629. }
  47630. var polygon = polygonTriangulation.build(options.updatable, depth);
  47631. polygon._originalBuilderSideOrientation = options.sideOrientation;
  47632. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  47633. vertexData.applyToMesh(polygon, options.updatable);
  47634. return polygon;
  47635. };
  47636. ;
  47637. /**
  47638. * Creates an extruded polygon mesh, with depth in the Y direction.
  47639. * 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).
  47640. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47641. */
  47642. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  47643. return MeshBuilder.CreatePolygon(name, options, scene);
  47644. };
  47645. ;
  47646. /**
  47647. * Creates a tube mesh.
  47648. * 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.
  47649. *
  47650. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  47651. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  47652. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  47653. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  47654. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  47655. * 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.
  47656. * It must return a radius value (positive float) :
  47657. * ```javascript
  47658. * var radiusFunction = function(i, distance) {
  47659. * // do things
  47660. * return radius; }
  47661. * ```
  47662. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  47663. * 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
  47664. * 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
  47665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47666. * 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).
  47667. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47668. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47669. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47670. */
  47671. MeshBuilder.CreateTube = function (name, options, scene) {
  47672. var path = options.path;
  47673. var instance = options.instance;
  47674. var radius = 1.0;
  47675. if (instance) {
  47676. radius = instance.radius;
  47677. }
  47678. if (options.radius !== undefined) {
  47679. radius = options.radius;
  47680. }
  47681. ;
  47682. var tessellation = options.tessellation || 64 | 0;
  47683. var radiusFunction = options.radiusFunction || null;
  47684. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47685. var invertUV = options.invertUV || false;
  47686. var updatable = options.updatable;
  47687. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47688. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  47689. // tube geometry
  47690. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  47691. var tangents = path3D.getTangents();
  47692. var normals = path3D.getNormals();
  47693. var distances = path3D.getDistances();
  47694. var pi2 = Math.PI * 2;
  47695. var step = pi2 / tessellation * arc;
  47696. var returnRadius = function () { return radius; };
  47697. var radiusFunctionFinal = radiusFunction || returnRadius;
  47698. var circlePath;
  47699. var rad;
  47700. var normal;
  47701. var rotated;
  47702. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47703. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47704. for (var i = 0; i < path.length; i++) {
  47705. rad = radiusFunctionFinal(i, distances[i]); // current radius
  47706. circlePath = Array(); // current circle array
  47707. normal = normals[i]; // current normal
  47708. for (var t = 0; t < tessellation; t++) {
  47709. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  47710. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  47711. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  47712. rotated.scaleInPlace(rad).addInPlace(path[i]);
  47713. circlePath[t] = rotated;
  47714. }
  47715. circlePaths[index] = circlePath;
  47716. index++;
  47717. }
  47718. // cap
  47719. var capPath = function (nbPoints, pathIndex) {
  47720. var pointCap = Array();
  47721. for (var i = 0; i < nbPoints; i++) {
  47722. pointCap.push(path[pathIndex]);
  47723. }
  47724. return pointCap;
  47725. };
  47726. switch (cap) {
  47727. case BABYLON.Mesh.NO_CAP:
  47728. break;
  47729. case BABYLON.Mesh.CAP_START:
  47730. circlePaths[0] = capPath(tessellation, 0);
  47731. circlePaths[1] = circlePaths[2].slice(0);
  47732. break;
  47733. case BABYLON.Mesh.CAP_END:
  47734. circlePaths[index] = circlePaths[index - 1].slice(0);
  47735. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47736. break;
  47737. case BABYLON.Mesh.CAP_ALL:
  47738. circlePaths[0] = capPath(tessellation, 0);
  47739. circlePaths[1] = circlePaths[2].slice(0);
  47740. circlePaths[index] = circlePaths[index - 1].slice(0);
  47741. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47742. break;
  47743. default:
  47744. break;
  47745. }
  47746. return circlePaths;
  47747. };
  47748. var path3D;
  47749. var pathArray;
  47750. if (instance) {
  47751. var arc = options.arc || instance.arc;
  47752. path3D = (instance.path3D).update(path);
  47753. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  47754. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  47755. instance.path3D = path3D;
  47756. instance.pathArray = pathArray;
  47757. instance.arc = arc;
  47758. instance.radius = radius;
  47759. return instance;
  47760. }
  47761. // tube creation
  47762. path3D = new BABYLON.Path3D(path);
  47763. var newPathArray = new Array();
  47764. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47765. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  47766. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47767. tube.pathArray = pathArray;
  47768. tube.path3D = path3D;
  47769. tube.tessellation = tessellation;
  47770. tube.cap = cap;
  47771. tube.arc = options.arc;
  47772. tube.radius = radius;
  47773. return tube;
  47774. };
  47775. /**
  47776. * Creates a polyhedron mesh.
  47777. *
  47778. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  47779. * 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
  47780. * to choose the wanted type.
  47781. * The parameter `size` (positive float, default 1) sets the polygon size.
  47782. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  47783. * 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`.
  47784. * 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
  47785. * 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)`).
  47786. * 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
  47787. * 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.
  47788. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47789. * 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).
  47790. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47792. */
  47793. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  47794. var polyhedron = new BABYLON.Mesh(name, scene);
  47795. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47796. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  47797. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  47798. vertexData.applyToMesh(polyhedron, options.updatable);
  47799. return polyhedron;
  47800. };
  47801. /**
  47802. * Creates a decal mesh.
  47803. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  47804. * 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.
  47805. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  47806. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  47807. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  47808. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  47809. */
  47810. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  47811. var indices = sourceMesh.getIndices();
  47812. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47813. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47814. var position = options.position || BABYLON.Vector3.Zero();
  47815. var normal = options.normal || BABYLON.Vector3.Up();
  47816. var size = options.size || BABYLON.Vector3.One();
  47817. var angle = options.angle || 0;
  47818. // Getting correct rotation
  47819. if (!normal) {
  47820. var target = new BABYLON.Vector3(0, 0, 1);
  47821. var camera = sourceMesh.getScene().activeCamera;
  47822. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  47823. normal = camera.globalPosition.subtract(cameraWorldTarget);
  47824. }
  47825. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  47826. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  47827. var pitch = Math.atan2(normal.y, len);
  47828. // Matrix
  47829. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  47830. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  47831. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  47832. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  47833. var vertexData = new BABYLON.VertexData();
  47834. vertexData.indices = [];
  47835. vertexData.positions = [];
  47836. vertexData.normals = [];
  47837. vertexData.uvs = [];
  47838. var currentVertexDataIndex = 0;
  47839. var extractDecalVector3 = function (indexId) {
  47840. var result = new BABYLON.PositionNormalVertex();
  47841. if (!indices || !positions || !normals) {
  47842. return result;
  47843. }
  47844. var vertexId = indices[indexId];
  47845. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  47846. // Send vector to decal local world
  47847. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  47848. // Get normal
  47849. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  47850. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  47851. return result;
  47852. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  47853. var clip = function (vertices, axis) {
  47854. if (vertices.length === 0) {
  47855. return vertices;
  47856. }
  47857. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  47858. var clipVertices = function (v0, v1) {
  47859. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  47860. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  47861. };
  47862. var result = new Array();
  47863. for (var index = 0; index < vertices.length; index += 3) {
  47864. var v1Out;
  47865. var v2Out;
  47866. var v3Out;
  47867. var total = 0;
  47868. var nV1 = null;
  47869. var nV2 = null;
  47870. var nV3 = null;
  47871. var nV4 = null;
  47872. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  47873. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  47874. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  47875. v1Out = d1 > 0;
  47876. v2Out = d2 > 0;
  47877. v3Out = d3 > 0;
  47878. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  47879. switch (total) {
  47880. case 0:
  47881. result.push(vertices[index]);
  47882. result.push(vertices[index + 1]);
  47883. result.push(vertices[index + 2]);
  47884. break;
  47885. case 1:
  47886. if (v1Out) {
  47887. nV1 = vertices[index + 1];
  47888. nV2 = vertices[index + 2];
  47889. nV3 = clipVertices(vertices[index], nV1);
  47890. nV4 = clipVertices(vertices[index], nV2);
  47891. }
  47892. if (v2Out) {
  47893. nV1 = vertices[index];
  47894. nV2 = vertices[index + 2];
  47895. nV3 = clipVertices(vertices[index + 1], nV1);
  47896. nV4 = clipVertices(vertices[index + 1], nV2);
  47897. result.push(nV3);
  47898. result.push(nV2.clone());
  47899. result.push(nV1.clone());
  47900. result.push(nV2.clone());
  47901. result.push(nV3.clone());
  47902. result.push(nV4);
  47903. break;
  47904. }
  47905. if (v3Out) {
  47906. nV1 = vertices[index];
  47907. nV2 = vertices[index + 1];
  47908. nV3 = clipVertices(vertices[index + 2], nV1);
  47909. nV4 = clipVertices(vertices[index + 2], nV2);
  47910. }
  47911. if (nV1 && nV2 && nV3 && nV4) {
  47912. result.push(nV1.clone());
  47913. result.push(nV2.clone());
  47914. result.push(nV3);
  47915. result.push(nV4);
  47916. result.push(nV3.clone());
  47917. result.push(nV2.clone());
  47918. }
  47919. break;
  47920. case 2:
  47921. if (!v1Out) {
  47922. nV1 = vertices[index].clone();
  47923. nV2 = clipVertices(nV1, vertices[index + 1]);
  47924. nV3 = clipVertices(nV1, vertices[index + 2]);
  47925. result.push(nV1);
  47926. result.push(nV2);
  47927. result.push(nV3);
  47928. }
  47929. if (!v2Out) {
  47930. nV1 = vertices[index + 1].clone();
  47931. nV2 = clipVertices(nV1, vertices[index + 2]);
  47932. nV3 = clipVertices(nV1, vertices[index]);
  47933. result.push(nV1);
  47934. result.push(nV2);
  47935. result.push(nV3);
  47936. }
  47937. if (!v3Out) {
  47938. nV1 = vertices[index + 2].clone();
  47939. nV2 = clipVertices(nV1, vertices[index]);
  47940. nV3 = clipVertices(nV1, vertices[index + 1]);
  47941. result.push(nV1);
  47942. result.push(nV2);
  47943. result.push(nV3);
  47944. }
  47945. break;
  47946. case 3:
  47947. break;
  47948. }
  47949. }
  47950. return result;
  47951. };
  47952. for (var index = 0; index < indices.length; index += 3) {
  47953. var faceVertices = new Array();
  47954. faceVertices.push(extractDecalVector3(index));
  47955. faceVertices.push(extractDecalVector3(index + 1));
  47956. faceVertices.push(extractDecalVector3(index + 2));
  47957. // Clip
  47958. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  47959. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  47960. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  47961. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  47962. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  47963. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  47964. if (faceVertices.length === 0) {
  47965. continue;
  47966. }
  47967. // Add UVs and get back to world
  47968. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  47969. var vertex = faceVertices[vIndex];
  47970. //TODO check for Int32Array | Uint32Array | Uint16Array
  47971. vertexData.indices.push(currentVertexDataIndex);
  47972. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  47973. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  47974. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  47975. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  47976. currentVertexDataIndex++;
  47977. }
  47978. }
  47979. // Return mesh
  47980. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  47981. vertexData.applyToMesh(decal);
  47982. decal.position = position.clone();
  47983. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  47984. return decal;
  47985. };
  47986. // Privates
  47987. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  47988. // extrusion geometry
  47989. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  47990. var tangents = path3D.getTangents();
  47991. var normals = path3D.getNormals();
  47992. var binormals = path3D.getBinormals();
  47993. var distances = path3D.getDistances();
  47994. var angle = 0;
  47995. var returnScale = function () { return scale !== null ? scale : 1; };
  47996. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  47997. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  47998. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  47999. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48000. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48001. for (var i = 0; i < curve.length; i++) {
  48002. var shapePath = new Array();
  48003. var angleStep = rotate(i, distances[i]);
  48004. var scaleRatio = scl(i, distances[i]);
  48005. for (var p = 0; p < shape.length; p++) {
  48006. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48007. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48008. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48009. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48010. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48011. shapePath[p] = rotated;
  48012. }
  48013. shapePaths[index] = shapePath;
  48014. angle += angleStep;
  48015. index++;
  48016. }
  48017. // cap
  48018. var capPath = function (shapePath) {
  48019. var pointCap = Array();
  48020. var barycenter = BABYLON.Vector3.Zero();
  48021. var i;
  48022. for (i = 0; i < shapePath.length; i++) {
  48023. barycenter.addInPlace(shapePath[i]);
  48024. }
  48025. barycenter.scaleInPlace(1.0 / shapePath.length);
  48026. for (i = 0; i < shapePath.length; i++) {
  48027. pointCap.push(barycenter);
  48028. }
  48029. return pointCap;
  48030. };
  48031. switch (cap) {
  48032. case BABYLON.Mesh.NO_CAP:
  48033. break;
  48034. case BABYLON.Mesh.CAP_START:
  48035. shapePaths[0] = capPath(shapePaths[2]);
  48036. shapePaths[1] = shapePaths[2];
  48037. break;
  48038. case BABYLON.Mesh.CAP_END:
  48039. shapePaths[index] = shapePaths[index - 1];
  48040. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48041. break;
  48042. case BABYLON.Mesh.CAP_ALL:
  48043. shapePaths[0] = capPath(shapePaths[2]);
  48044. shapePaths[1] = shapePaths[2];
  48045. shapePaths[index] = shapePaths[index - 1];
  48046. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48047. break;
  48048. default:
  48049. break;
  48050. }
  48051. return shapePaths;
  48052. };
  48053. var path3D;
  48054. var pathArray;
  48055. if (instance) {
  48056. path3D = (instance.path3D).update(curve);
  48057. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  48058. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  48059. return instance;
  48060. }
  48061. // extruded shape creation
  48062. path3D = new BABYLON.Path3D(curve);
  48063. var newShapePaths = new Array();
  48064. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48065. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  48066. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  48067. extrudedGeneric.pathArray = pathArray;
  48068. extrudedGeneric.path3D = path3D;
  48069. extrudedGeneric.cap = cap;
  48070. return extrudedGeneric;
  48071. };
  48072. return MeshBuilder;
  48073. }());
  48074. BABYLON.MeshBuilder = MeshBuilder;
  48075. })(BABYLON || (BABYLON = {}));
  48076. //# sourceMappingURL=babylon.meshBuilder.js.map
  48077. var BABYLON;
  48078. (function (BABYLON) {
  48079. var AudioEngine = /** @class */ (function () {
  48080. function AudioEngine() {
  48081. this._audioContext = null;
  48082. this._audioContextInitialized = false;
  48083. this.canUseWebAudio = false;
  48084. this.WarnedWebAudioUnsupported = false;
  48085. this.unlocked = false;
  48086. this.isMP3supported = false;
  48087. this.isOGGsupported = false;
  48088. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  48089. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  48090. this.canUseWebAudio = true;
  48091. }
  48092. var audioElem = document.createElement('audio');
  48093. try {
  48094. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48095. this.isMP3supported = true;
  48096. }
  48097. }
  48098. catch (e) {
  48099. // protect error during capability check.
  48100. }
  48101. try {
  48102. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48103. this.isOGGsupported = true;
  48104. }
  48105. }
  48106. catch (e) {
  48107. // protect error during capability check.
  48108. }
  48109. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  48110. this._unlockiOSaudio();
  48111. }
  48112. else {
  48113. this.unlocked = true;
  48114. }
  48115. }
  48116. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  48117. get: function () {
  48118. if (!this._audioContextInitialized) {
  48119. this._initializeAudioContext();
  48120. }
  48121. return this._audioContext;
  48122. },
  48123. enumerable: true,
  48124. configurable: true
  48125. });
  48126. AudioEngine.prototype._unlockiOSaudio = function () {
  48127. var _this = this;
  48128. var unlockaudio = function () {
  48129. if (!_this.audioContext) {
  48130. return;
  48131. }
  48132. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  48133. var source = _this.audioContext.createBufferSource();
  48134. source.buffer = buffer;
  48135. source.connect(_this.audioContext.destination);
  48136. source.start(0);
  48137. setTimeout(function () {
  48138. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  48139. _this.unlocked = true;
  48140. window.removeEventListener('touchend', unlockaudio, false);
  48141. if (_this.onAudioUnlocked) {
  48142. _this.onAudioUnlocked();
  48143. }
  48144. }
  48145. }, 0);
  48146. };
  48147. window.addEventListener('touchend', unlockaudio, false);
  48148. };
  48149. AudioEngine.prototype._initializeAudioContext = function () {
  48150. try {
  48151. if (this.canUseWebAudio) {
  48152. this._audioContext = new AudioContext();
  48153. // create a global volume gain node
  48154. this.masterGain = this._audioContext.createGain();
  48155. this.masterGain.gain.value = 1;
  48156. this.masterGain.connect(this._audioContext.destination);
  48157. this._audioContextInitialized = true;
  48158. }
  48159. }
  48160. catch (e) {
  48161. this.canUseWebAudio = false;
  48162. BABYLON.Tools.Error("Web Audio: " + e.message);
  48163. }
  48164. };
  48165. AudioEngine.prototype.dispose = function () {
  48166. if (this.canUseWebAudio && this._audioContextInitialized) {
  48167. if (this._connectedAnalyser && this._audioContext) {
  48168. this._connectedAnalyser.stopDebugCanvas();
  48169. this._connectedAnalyser.dispose();
  48170. this.masterGain.disconnect();
  48171. this.masterGain.connect(this._audioContext.destination);
  48172. this._connectedAnalyser = null;
  48173. }
  48174. this.masterGain.gain.value = 1;
  48175. }
  48176. this.WarnedWebAudioUnsupported = false;
  48177. };
  48178. AudioEngine.prototype.getGlobalVolume = function () {
  48179. if (this.canUseWebAudio && this._audioContextInitialized) {
  48180. return this.masterGain.gain.value;
  48181. }
  48182. else {
  48183. return -1;
  48184. }
  48185. };
  48186. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48187. if (this.canUseWebAudio && this._audioContextInitialized) {
  48188. this.masterGain.gain.value = newVolume;
  48189. }
  48190. };
  48191. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48192. if (this._connectedAnalyser) {
  48193. this._connectedAnalyser.stopDebugCanvas();
  48194. }
  48195. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48196. this._connectedAnalyser = analyser;
  48197. this.masterGain.disconnect();
  48198. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48199. }
  48200. };
  48201. return AudioEngine;
  48202. }());
  48203. BABYLON.AudioEngine = AudioEngine;
  48204. })(BABYLON || (BABYLON = {}));
  48205. //# sourceMappingURL=babylon.audioEngine.js.map
  48206. var BABYLON;
  48207. (function (BABYLON) {
  48208. var Sound = /** @class */ (function () {
  48209. /**
  48210. * Create a sound and attach it to a scene
  48211. * @param name Name of your sound
  48212. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48213. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48214. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48215. */
  48216. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48217. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48218. var _this = this;
  48219. this.autoplay = false;
  48220. this.loop = false;
  48221. this.useCustomAttenuation = false;
  48222. this.spatialSound = false;
  48223. this.refDistance = 1;
  48224. this.rolloffFactor = 1;
  48225. this.maxDistance = 100;
  48226. this.distanceModel = "linear";
  48227. this._panningModel = "equalpower";
  48228. this._playbackRate = 1;
  48229. this._streaming = false;
  48230. this._startTime = 0;
  48231. this._startOffset = 0;
  48232. this._position = BABYLON.Vector3.Zero();
  48233. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48234. this._volume = 1;
  48235. this._isLoaded = false;
  48236. this._isReadyToPlay = false;
  48237. this.isPlaying = false;
  48238. this.isPaused = false;
  48239. this._isDirectional = false;
  48240. // Used if you'd like to create a directional sound.
  48241. // If not set, the sound will be omnidirectional
  48242. this._coneInnerAngle = 360;
  48243. this._coneOuterAngle = 360;
  48244. this._coneOuterGain = 0;
  48245. this._isOutputConnected = false;
  48246. this._urlType = "Unknown";
  48247. this.name = name;
  48248. this._scene = scene;
  48249. this._readyToPlayCallback = readyToPlayCallback;
  48250. // Default custom attenuation function is a linear attenuation
  48251. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48252. if (currentDistance < maxDistance) {
  48253. return currentVolume * (1 - currentDistance / maxDistance);
  48254. }
  48255. else {
  48256. return 0;
  48257. }
  48258. };
  48259. if (options) {
  48260. this.autoplay = options.autoplay || false;
  48261. this.loop = options.loop || false;
  48262. // if volume === 0, we need another way to check this option
  48263. if (options.volume !== undefined) {
  48264. this._volume = options.volume;
  48265. }
  48266. this.spatialSound = options.spatialSound || false;
  48267. this.maxDistance = options.maxDistance || 100;
  48268. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48269. this.rolloffFactor = options.rolloffFactor || 1;
  48270. this.refDistance = options.refDistance || 1;
  48271. this.distanceModel = options.distanceModel || "linear";
  48272. this._playbackRate = options.playbackRate || 1;
  48273. this._streaming = options.streaming || false;
  48274. }
  48275. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48276. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48277. this._soundGain.gain.value = this._volume;
  48278. this._inputAudioNode = this._soundGain;
  48279. this._ouputAudioNode = this._soundGain;
  48280. if (this.spatialSound) {
  48281. this._createSpatialParameters();
  48282. }
  48283. this._scene.mainSoundTrack.AddSound(this);
  48284. var validParameter = true;
  48285. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48286. if (urlOrArrayBuffer) {
  48287. if (typeof (urlOrArrayBuffer) === "string")
  48288. this._urlType = "String";
  48289. if (Array.isArray(urlOrArrayBuffer))
  48290. this._urlType = "Array";
  48291. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48292. this._urlType = "ArrayBuffer";
  48293. var urls = [];
  48294. var codecSupportedFound = false;
  48295. switch (this._urlType) {
  48296. case "ArrayBuffer":
  48297. if (urlOrArrayBuffer.byteLength > 0) {
  48298. codecSupportedFound = true;
  48299. this._soundLoaded(urlOrArrayBuffer);
  48300. }
  48301. break;
  48302. case "String":
  48303. urls.push(urlOrArrayBuffer);
  48304. case "Array":
  48305. if (urls.length === 0)
  48306. urls = urlOrArrayBuffer;
  48307. // If we found a supported format, we load it immediately and stop the loop
  48308. for (var i = 0; i < urls.length; i++) {
  48309. var url = urls[i];
  48310. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48311. codecSupportedFound = true;
  48312. }
  48313. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48314. codecSupportedFound = true;
  48315. }
  48316. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48317. codecSupportedFound = true;
  48318. }
  48319. if (url.indexOf("blob:") !== -1) {
  48320. codecSupportedFound = true;
  48321. }
  48322. if (codecSupportedFound) {
  48323. // Loading sound using XHR2
  48324. if (!this._streaming) {
  48325. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48326. }
  48327. else {
  48328. this._htmlAudioElement = new Audio(url);
  48329. this._htmlAudioElement.controls = false;
  48330. this._htmlAudioElement.loop = this.loop;
  48331. this._htmlAudioElement.crossOrigin = "anonymous";
  48332. this._htmlAudioElement.preload = "auto";
  48333. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48334. _this._isReadyToPlay = true;
  48335. if (_this.autoplay) {
  48336. _this.play();
  48337. }
  48338. if (_this._readyToPlayCallback) {
  48339. _this._readyToPlayCallback();
  48340. }
  48341. });
  48342. document.body.appendChild(this._htmlAudioElement);
  48343. }
  48344. break;
  48345. }
  48346. }
  48347. break;
  48348. default:
  48349. validParameter = false;
  48350. break;
  48351. }
  48352. if (!validParameter) {
  48353. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  48354. }
  48355. else {
  48356. if (!codecSupportedFound) {
  48357. this._isReadyToPlay = true;
  48358. // Simulating a ready to play event to avoid breaking code path
  48359. if (this._readyToPlayCallback) {
  48360. window.setTimeout(function () {
  48361. if (_this._readyToPlayCallback) {
  48362. _this._readyToPlayCallback();
  48363. }
  48364. }, 1000);
  48365. }
  48366. }
  48367. }
  48368. }
  48369. }
  48370. else {
  48371. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  48372. this._scene.mainSoundTrack.AddSound(this);
  48373. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  48374. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  48375. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  48376. }
  48377. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  48378. if (this._readyToPlayCallback) {
  48379. window.setTimeout(function () {
  48380. if (_this._readyToPlayCallback) {
  48381. _this._readyToPlayCallback();
  48382. }
  48383. }, 1000);
  48384. }
  48385. }
  48386. }
  48387. Sound.prototype.dispose = function () {
  48388. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  48389. if (this.isPlaying) {
  48390. this.stop();
  48391. }
  48392. this._isReadyToPlay = false;
  48393. if (this.soundTrackId === -1) {
  48394. this._scene.mainSoundTrack.RemoveSound(this);
  48395. }
  48396. else {
  48397. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  48398. }
  48399. if (this._soundGain) {
  48400. this._soundGain.disconnect();
  48401. this._soundGain = null;
  48402. }
  48403. if (this._soundPanner) {
  48404. this._soundPanner.disconnect();
  48405. this._soundPanner = null;
  48406. }
  48407. if (this._soundSource) {
  48408. this._soundSource.disconnect();
  48409. this._soundSource = null;
  48410. }
  48411. this._audioBuffer = null;
  48412. if (this._htmlAudioElement) {
  48413. this._htmlAudioElement.pause();
  48414. this._htmlAudioElement.src = "";
  48415. document.body.removeChild(this._htmlAudioElement);
  48416. }
  48417. if (this._connectedMesh && this._registerFunc) {
  48418. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48419. this._connectedMesh = null;
  48420. }
  48421. }
  48422. };
  48423. Sound.prototype.isReady = function () {
  48424. return this._isReadyToPlay;
  48425. };
  48426. Sound.prototype._soundLoaded = function (audioData) {
  48427. var _this = this;
  48428. this._isLoaded = true;
  48429. if (!BABYLON.Engine.audioEngine.audioContext) {
  48430. return;
  48431. }
  48432. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  48433. _this._audioBuffer = buffer;
  48434. _this._isReadyToPlay = true;
  48435. if (_this.autoplay) {
  48436. _this.play();
  48437. }
  48438. if (_this._readyToPlayCallback) {
  48439. _this._readyToPlayCallback();
  48440. }
  48441. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  48442. };
  48443. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  48444. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48445. this._audioBuffer = audioBuffer;
  48446. this._isReadyToPlay = true;
  48447. }
  48448. };
  48449. Sound.prototype.updateOptions = function (options) {
  48450. if (options) {
  48451. this.loop = options.loop || this.loop;
  48452. this.maxDistance = options.maxDistance || this.maxDistance;
  48453. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  48454. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  48455. this.refDistance = options.refDistance || this.refDistance;
  48456. this.distanceModel = options.distanceModel || this.distanceModel;
  48457. this._playbackRate = options.playbackRate || this._playbackRate;
  48458. this._updateSpatialParameters();
  48459. if (this.isPlaying) {
  48460. if (this._streaming) {
  48461. this._htmlAudioElement.playbackRate = this._playbackRate;
  48462. }
  48463. else {
  48464. if (this._soundSource) {
  48465. this._soundSource.playbackRate.value = this._playbackRate;
  48466. }
  48467. }
  48468. }
  48469. }
  48470. };
  48471. Sound.prototype._createSpatialParameters = function () {
  48472. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48473. if (this._scene.headphone) {
  48474. this._panningModel = "HRTF";
  48475. }
  48476. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  48477. this._updateSpatialParameters();
  48478. this._soundPanner.connect(this._ouputAudioNode);
  48479. this._inputAudioNode = this._soundPanner;
  48480. }
  48481. };
  48482. Sound.prototype._updateSpatialParameters = function () {
  48483. if (this.spatialSound && this._soundPanner) {
  48484. if (this.useCustomAttenuation) {
  48485. // Tricks to disable in a way embedded Web Audio attenuation
  48486. this._soundPanner.distanceModel = "linear";
  48487. this._soundPanner.maxDistance = Number.MAX_VALUE;
  48488. this._soundPanner.refDistance = 1;
  48489. this._soundPanner.rolloffFactor = 1;
  48490. this._soundPanner.panningModel = this._panningModel;
  48491. }
  48492. else {
  48493. this._soundPanner.distanceModel = this.distanceModel;
  48494. this._soundPanner.maxDistance = this.maxDistance;
  48495. this._soundPanner.refDistance = this.refDistance;
  48496. this._soundPanner.rolloffFactor = this.rolloffFactor;
  48497. this._soundPanner.panningModel = this._panningModel;
  48498. }
  48499. }
  48500. };
  48501. Sound.prototype.switchPanningModelToHRTF = function () {
  48502. this._panningModel = "HRTF";
  48503. this._switchPanningModel();
  48504. };
  48505. Sound.prototype.switchPanningModelToEqualPower = function () {
  48506. this._panningModel = "equalpower";
  48507. this._switchPanningModel();
  48508. };
  48509. Sound.prototype._switchPanningModel = function () {
  48510. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48511. this._soundPanner.panningModel = this._panningModel;
  48512. }
  48513. };
  48514. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  48515. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48516. if (this._isOutputConnected) {
  48517. this._ouputAudioNode.disconnect();
  48518. }
  48519. this._ouputAudioNode.connect(soundTrackAudioNode);
  48520. this._isOutputConnected = true;
  48521. }
  48522. };
  48523. /**
  48524. * Transform this sound into a directional source
  48525. * @param coneInnerAngle Size of the inner cone in degree
  48526. * @param coneOuterAngle Size of the outer cone in degree
  48527. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  48528. */
  48529. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  48530. if (coneOuterAngle < coneInnerAngle) {
  48531. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  48532. return;
  48533. }
  48534. this._coneInnerAngle = coneInnerAngle;
  48535. this._coneOuterAngle = coneOuterAngle;
  48536. this._coneOuterGain = coneOuterGain;
  48537. this._isDirectional = true;
  48538. if (this.isPlaying && this.loop) {
  48539. this.stop();
  48540. this.play();
  48541. }
  48542. };
  48543. Sound.prototype.setPosition = function (newPosition) {
  48544. this._position = newPosition;
  48545. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48546. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48547. }
  48548. };
  48549. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  48550. this._localDirection = newLocalDirection;
  48551. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  48552. this._updateDirection();
  48553. }
  48554. };
  48555. Sound.prototype._updateDirection = function () {
  48556. if (!this._connectedMesh || !this._soundPanner) {
  48557. return;
  48558. }
  48559. var mat = this._connectedMesh.getWorldMatrix();
  48560. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  48561. direction.normalize();
  48562. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  48563. };
  48564. Sound.prototype.updateDistanceFromListener = function () {
  48565. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  48566. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  48567. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  48568. }
  48569. };
  48570. Sound.prototype.setAttenuationFunction = function (callback) {
  48571. this._customAttenuationFunction = callback;
  48572. };
  48573. /**
  48574. * Play the sound
  48575. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  48576. * @param offset (optional) Start the sound setting it at a specific time
  48577. */
  48578. Sound.prototype.play = function (time, offset) {
  48579. var _this = this;
  48580. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  48581. try {
  48582. if (this._startOffset < 0) {
  48583. time = -this._startOffset;
  48584. this._startOffset = 0;
  48585. }
  48586. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48587. if (!this._soundSource || !this._streamingSource) {
  48588. if (this.spatialSound && this._soundPanner) {
  48589. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48590. if (this._isDirectional) {
  48591. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  48592. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  48593. this._soundPanner.coneOuterGain = this._coneOuterGain;
  48594. if (this._connectedMesh) {
  48595. this._updateDirection();
  48596. }
  48597. else {
  48598. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  48599. }
  48600. }
  48601. }
  48602. }
  48603. if (this._streaming) {
  48604. if (!this._streamingSource) {
  48605. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  48606. this._htmlAudioElement.onended = function () { _this._onended(); };
  48607. this._htmlAudioElement.playbackRate = this._playbackRate;
  48608. }
  48609. this._streamingSource.disconnect();
  48610. this._streamingSource.connect(this._inputAudioNode);
  48611. this._htmlAudioElement.play();
  48612. }
  48613. else {
  48614. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  48615. this._soundSource.buffer = this._audioBuffer;
  48616. this._soundSource.connect(this._inputAudioNode);
  48617. this._soundSource.loop = this.loop;
  48618. this._soundSource.playbackRate.value = this._playbackRate;
  48619. this._soundSource.onended = function () { _this._onended(); };
  48620. if (this._soundSource.buffer) {
  48621. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  48622. }
  48623. }
  48624. this._startTime = startTime;
  48625. this.isPlaying = true;
  48626. this.isPaused = false;
  48627. }
  48628. catch (ex) {
  48629. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  48630. }
  48631. }
  48632. };
  48633. Sound.prototype._onended = function () {
  48634. this.isPlaying = false;
  48635. if (this.onended) {
  48636. this.onended();
  48637. }
  48638. };
  48639. /**
  48640. * Stop the sound
  48641. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  48642. */
  48643. Sound.prototype.stop = function (time) {
  48644. if (this.isPlaying) {
  48645. if (this._streaming) {
  48646. this._htmlAudioElement.pause();
  48647. // Test needed for Firefox or it will generate an Invalid State Error
  48648. if (this._htmlAudioElement.currentTime > 0) {
  48649. this._htmlAudioElement.currentTime = 0;
  48650. }
  48651. }
  48652. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  48653. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48654. this._soundSource.stop(stopTime);
  48655. this._soundSource.onended = function () { };
  48656. if (!this.isPaused) {
  48657. this._startOffset = 0;
  48658. }
  48659. }
  48660. this.isPlaying = false;
  48661. }
  48662. };
  48663. Sound.prototype.pause = function () {
  48664. if (this.isPlaying) {
  48665. this.isPaused = true;
  48666. if (this._streaming) {
  48667. this._htmlAudioElement.pause();
  48668. }
  48669. else if (BABYLON.Engine.audioEngine.audioContext) {
  48670. this.stop(0);
  48671. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  48672. }
  48673. }
  48674. };
  48675. Sound.prototype.setVolume = function (newVolume, time) {
  48676. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  48677. if (time && BABYLON.Engine.audioEngine.audioContext) {
  48678. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  48679. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  48680. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  48681. }
  48682. else {
  48683. this._soundGain.gain.value = newVolume;
  48684. }
  48685. }
  48686. this._volume = newVolume;
  48687. };
  48688. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  48689. this._playbackRate = newPlaybackRate;
  48690. if (this.isPlaying) {
  48691. if (this._streaming) {
  48692. this._htmlAudioElement.playbackRate = this._playbackRate;
  48693. }
  48694. else if (this._soundSource) {
  48695. this._soundSource.playbackRate.value = this._playbackRate;
  48696. }
  48697. }
  48698. };
  48699. Sound.prototype.getVolume = function () {
  48700. return this._volume;
  48701. };
  48702. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  48703. var _this = this;
  48704. if (this._connectedMesh && this._registerFunc) {
  48705. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48706. this._registerFunc = null;
  48707. }
  48708. this._connectedMesh = meshToConnectTo;
  48709. if (!this.spatialSound) {
  48710. this.spatialSound = true;
  48711. this._createSpatialParameters();
  48712. if (this.isPlaying && this.loop) {
  48713. this.stop();
  48714. this.play();
  48715. }
  48716. }
  48717. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  48718. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  48719. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  48720. };
  48721. Sound.prototype.detachFromMesh = function () {
  48722. if (this._connectedMesh && this._registerFunc) {
  48723. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48724. this._registerFunc = null;
  48725. this._connectedMesh = null;
  48726. }
  48727. };
  48728. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  48729. var boundingInfo = connectedMesh.getBoundingInfo();
  48730. if (!boundingInfo) {
  48731. return;
  48732. }
  48733. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  48734. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  48735. this._updateDirection();
  48736. }
  48737. };
  48738. Sound.prototype.clone = function () {
  48739. var _this = this;
  48740. if (!this._streaming) {
  48741. var setBufferAndRun = function () {
  48742. if (_this._isReadyToPlay) {
  48743. clonedSound._audioBuffer = _this.getAudioBuffer();
  48744. clonedSound._isReadyToPlay = true;
  48745. if (clonedSound.autoplay) {
  48746. clonedSound.play();
  48747. }
  48748. }
  48749. else {
  48750. window.setTimeout(setBufferAndRun, 300);
  48751. }
  48752. };
  48753. var currentOptions = {
  48754. autoplay: this.autoplay, loop: this.loop,
  48755. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  48756. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  48757. refDistance: this.refDistance, distanceModel: this.distanceModel
  48758. };
  48759. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  48760. if (this.useCustomAttenuation) {
  48761. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  48762. }
  48763. clonedSound.setPosition(this._position);
  48764. clonedSound.setPlaybackRate(this._playbackRate);
  48765. setBufferAndRun();
  48766. return clonedSound;
  48767. }
  48768. else {
  48769. return null;
  48770. }
  48771. };
  48772. Sound.prototype.getAudioBuffer = function () {
  48773. return this._audioBuffer;
  48774. };
  48775. Sound.prototype.serialize = function () {
  48776. var serializationObject = {
  48777. name: this.name,
  48778. url: this.name,
  48779. autoplay: this.autoplay,
  48780. loop: this.loop,
  48781. volume: this._volume,
  48782. spatialSound: this.spatialSound,
  48783. maxDistance: this.maxDistance,
  48784. rolloffFactor: this.rolloffFactor,
  48785. refDistance: this.refDistance,
  48786. distanceModel: this.distanceModel,
  48787. playbackRate: this._playbackRate,
  48788. panningModel: this._panningModel,
  48789. soundTrackId: this.soundTrackId
  48790. };
  48791. if (this.spatialSound) {
  48792. if (this._connectedMesh)
  48793. serializationObject.connectedMeshId = this._connectedMesh.id;
  48794. serializationObject.position = this._position.asArray();
  48795. serializationObject.refDistance = this.refDistance;
  48796. serializationObject.distanceModel = this.distanceModel;
  48797. serializationObject.isDirectional = this._isDirectional;
  48798. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  48799. serializationObject.coneInnerAngle = this._coneInnerAngle;
  48800. serializationObject.coneOuterAngle = this._coneOuterAngle;
  48801. serializationObject.coneOuterGain = this._coneOuterGain;
  48802. }
  48803. return serializationObject;
  48804. };
  48805. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  48806. var soundName = parsedSound.name;
  48807. var soundUrl;
  48808. if (parsedSound.url) {
  48809. soundUrl = rootUrl + parsedSound.url;
  48810. }
  48811. else {
  48812. soundUrl = rootUrl + soundName;
  48813. }
  48814. var options = {
  48815. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  48816. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  48817. rolloffFactor: parsedSound.rolloffFactor,
  48818. refDistance: parsedSound.refDistance,
  48819. distanceModel: parsedSound.distanceModel,
  48820. playbackRate: parsedSound.playbackRate
  48821. };
  48822. var newSound;
  48823. if (!sourceSound) {
  48824. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  48825. scene._addPendingData(newSound);
  48826. }
  48827. else {
  48828. var setBufferAndRun = function () {
  48829. if (sourceSound._isReadyToPlay) {
  48830. newSound._audioBuffer = sourceSound.getAudioBuffer();
  48831. newSound._isReadyToPlay = true;
  48832. if (newSound.autoplay) {
  48833. newSound.play();
  48834. }
  48835. }
  48836. else {
  48837. window.setTimeout(setBufferAndRun, 300);
  48838. }
  48839. };
  48840. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  48841. setBufferAndRun();
  48842. }
  48843. if (parsedSound.position) {
  48844. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  48845. newSound.setPosition(soundPosition);
  48846. }
  48847. if (parsedSound.isDirectional) {
  48848. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  48849. if (parsedSound.localDirectionToMesh) {
  48850. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  48851. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  48852. }
  48853. }
  48854. if (parsedSound.connectedMeshId) {
  48855. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  48856. if (connectedMesh) {
  48857. newSound.attachToMesh(connectedMesh);
  48858. }
  48859. }
  48860. return newSound;
  48861. };
  48862. return Sound;
  48863. }());
  48864. BABYLON.Sound = Sound;
  48865. })(BABYLON || (BABYLON = {}));
  48866. //# sourceMappingURL=babylon.sound.js.map
  48867. var BABYLON;
  48868. (function (BABYLON) {
  48869. var SoundTrack = /** @class */ (function () {
  48870. function SoundTrack(scene, options) {
  48871. this.id = -1;
  48872. this._isMainTrack = false;
  48873. this._isInitialized = false;
  48874. this._scene = scene;
  48875. this.soundCollection = new Array();
  48876. this._options = options;
  48877. if (!this._isMainTrack) {
  48878. this._scene.soundTracks.push(this);
  48879. this.id = this._scene.soundTracks.length - 1;
  48880. }
  48881. }
  48882. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  48883. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48884. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  48885. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  48886. if (this._options) {
  48887. if (this._options.volume) {
  48888. this._outputAudioNode.gain.value = this._options.volume;
  48889. }
  48890. if (this._options.mainTrack) {
  48891. this._isMainTrack = this._options.mainTrack;
  48892. }
  48893. }
  48894. this._isInitialized = true;
  48895. }
  48896. };
  48897. SoundTrack.prototype.dispose = function () {
  48898. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48899. if (this._connectedAnalyser) {
  48900. this._connectedAnalyser.stopDebugCanvas();
  48901. }
  48902. while (this.soundCollection.length) {
  48903. this.soundCollection[0].dispose();
  48904. }
  48905. if (this._outputAudioNode) {
  48906. this._outputAudioNode.disconnect();
  48907. }
  48908. this._outputAudioNode = null;
  48909. }
  48910. };
  48911. SoundTrack.prototype.AddSound = function (sound) {
  48912. if (!this._isInitialized) {
  48913. this._initializeSoundTrackAudioGraph();
  48914. }
  48915. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48916. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  48917. }
  48918. if (sound.soundTrackId) {
  48919. if (sound.soundTrackId === -1) {
  48920. this._scene.mainSoundTrack.RemoveSound(sound);
  48921. }
  48922. else {
  48923. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  48924. }
  48925. }
  48926. this.soundCollection.push(sound);
  48927. sound.soundTrackId = this.id;
  48928. };
  48929. SoundTrack.prototype.RemoveSound = function (sound) {
  48930. var index = this.soundCollection.indexOf(sound);
  48931. if (index !== -1) {
  48932. this.soundCollection.splice(index, 1);
  48933. }
  48934. };
  48935. SoundTrack.prototype.setVolume = function (newVolume) {
  48936. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48937. this._outputAudioNode.gain.value = newVolume;
  48938. }
  48939. };
  48940. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  48941. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48942. for (var i = 0; i < this.soundCollection.length; i++) {
  48943. this.soundCollection[i].switchPanningModelToHRTF();
  48944. }
  48945. }
  48946. };
  48947. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  48948. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48949. for (var i = 0; i < this.soundCollection.length; i++) {
  48950. this.soundCollection[i].switchPanningModelToEqualPower();
  48951. }
  48952. }
  48953. };
  48954. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  48955. if (this._connectedAnalyser) {
  48956. this._connectedAnalyser.stopDebugCanvas();
  48957. }
  48958. this._connectedAnalyser = analyser;
  48959. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48960. this._outputAudioNode.disconnect();
  48961. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  48962. }
  48963. };
  48964. return SoundTrack;
  48965. }());
  48966. BABYLON.SoundTrack = SoundTrack;
  48967. })(BABYLON || (BABYLON = {}));
  48968. //# sourceMappingURL=babylon.soundtrack.js.map
  48969. var BABYLON;
  48970. (function (BABYLON) {
  48971. var Analyser = /** @class */ (function () {
  48972. function Analyser(scene) {
  48973. this.SMOOTHING = 0.75;
  48974. this.FFT_SIZE = 512;
  48975. this.BARGRAPHAMPLITUDE = 256;
  48976. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  48977. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  48978. this._scene = scene;
  48979. this._audioEngine = BABYLON.Engine.audioEngine;
  48980. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  48981. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  48982. this._webAudioAnalyser.minDecibels = -140;
  48983. this._webAudioAnalyser.maxDecibels = 0;
  48984. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48985. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48986. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  48987. }
  48988. }
  48989. Analyser.prototype.getFrequencyBinCount = function () {
  48990. if (this._audioEngine.canUseWebAudio) {
  48991. return this._webAudioAnalyser.frequencyBinCount;
  48992. }
  48993. else {
  48994. return 0;
  48995. }
  48996. };
  48997. Analyser.prototype.getByteFrequencyData = function () {
  48998. if (this._audioEngine.canUseWebAudio) {
  48999. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49000. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49001. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49002. }
  49003. return this._byteFreqs;
  49004. };
  49005. Analyser.prototype.getByteTimeDomainData = function () {
  49006. if (this._audioEngine.canUseWebAudio) {
  49007. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49008. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49009. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49010. }
  49011. return this._byteTime;
  49012. };
  49013. Analyser.prototype.getFloatFrequencyData = function () {
  49014. if (this._audioEngine.canUseWebAudio) {
  49015. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49016. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49017. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49018. }
  49019. return this._floatFreqs;
  49020. };
  49021. Analyser.prototype.drawDebugCanvas = function () {
  49022. var _this = this;
  49023. if (this._audioEngine.canUseWebAudio) {
  49024. if (!this._debugCanvas) {
  49025. this._debugCanvas = document.createElement("canvas");
  49026. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49027. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49028. this._debugCanvas.style.position = "absolute";
  49029. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49030. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49031. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49032. document.body.appendChild(this._debugCanvas);
  49033. this._registerFunc = function () {
  49034. _this.drawDebugCanvas();
  49035. };
  49036. this._scene.registerBeforeRender(this._registerFunc);
  49037. }
  49038. if (this._registerFunc && this._debugCanvasContext) {
  49039. var workingArray = this.getByteFrequencyData();
  49040. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49041. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49042. // Draw the frequency domain chart.
  49043. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49044. var value = workingArray[i];
  49045. var percent = value / this.BARGRAPHAMPLITUDE;
  49046. var height = this.DEBUGCANVASSIZE.height * percent;
  49047. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49048. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49049. var hue = i / this.getFrequencyBinCount() * 360;
  49050. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49051. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49052. }
  49053. }
  49054. }
  49055. };
  49056. Analyser.prototype.stopDebugCanvas = function () {
  49057. if (this._debugCanvas) {
  49058. if (this._registerFunc) {
  49059. this._scene.unregisterBeforeRender(this._registerFunc);
  49060. this._registerFunc = null;
  49061. }
  49062. document.body.removeChild(this._debugCanvas);
  49063. this._debugCanvas = null;
  49064. this._debugCanvasContext = null;
  49065. }
  49066. };
  49067. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49068. if (this._audioEngine.canUseWebAudio) {
  49069. inputAudioNode.connect(this._webAudioAnalyser);
  49070. this._webAudioAnalyser.connect(outputAudioNode);
  49071. }
  49072. };
  49073. Analyser.prototype.dispose = function () {
  49074. if (this._audioEngine.canUseWebAudio) {
  49075. this._webAudioAnalyser.disconnect();
  49076. }
  49077. };
  49078. return Analyser;
  49079. }());
  49080. BABYLON.Analyser = Analyser;
  49081. })(BABYLON || (BABYLON = {}));
  49082. //# sourceMappingURL=babylon.analyser.js.map
  49083. var BABYLON;
  49084. (function (BABYLON) {
  49085. var CubeTexture = /** @class */ (function (_super) {
  49086. __extends(CubeTexture, _super);
  49087. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  49088. if (extensions === void 0) { extensions = null; }
  49089. if (noMipmap === void 0) { noMipmap = false; }
  49090. if (files === void 0) { files = null; }
  49091. if (onLoad === void 0) { onLoad = null; }
  49092. if (onError === void 0) { onError = null; }
  49093. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49094. if (prefiltered === void 0) { prefiltered = false; }
  49095. if (forcedExtension === void 0) { forcedExtension = null; }
  49096. var _this = _super.call(this, scene) || this;
  49097. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49098. _this.name = rootUrl;
  49099. _this.url = rootUrl;
  49100. _this._noMipmap = noMipmap;
  49101. _this.hasAlpha = false;
  49102. _this._format = format;
  49103. _this._prefiltered = prefiltered;
  49104. _this.isCube = true;
  49105. _this._textureMatrix = BABYLON.Matrix.Identity();
  49106. if (prefiltered) {
  49107. _this.gammaSpace = false;
  49108. }
  49109. if (!rootUrl && !files) {
  49110. return _this;
  49111. }
  49112. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  49113. if (!files) {
  49114. if (!extensions) {
  49115. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  49116. }
  49117. files = [];
  49118. for (var index = 0; index < extensions.length; index++) {
  49119. files.push(rootUrl + extensions[index]);
  49120. }
  49121. _this._extensions = extensions;
  49122. }
  49123. _this._files = files;
  49124. if (!_this._texture) {
  49125. if (!scene.useDelayedTextureLoading) {
  49126. if (prefiltered) {
  49127. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  49128. }
  49129. else {
  49130. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  49131. }
  49132. }
  49133. else {
  49134. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49135. }
  49136. }
  49137. else if (onLoad) {
  49138. if (_this._texture.isReady) {
  49139. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  49140. }
  49141. else {
  49142. _this._texture.onLoadedObservable.add(onLoad);
  49143. }
  49144. }
  49145. return _this;
  49146. }
  49147. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  49148. return new CubeTexture("", scene, null, noMipmap, files);
  49149. };
  49150. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  49151. if (forcedExtension === void 0) { forcedExtension = null; }
  49152. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  49153. };
  49154. // Methods
  49155. CubeTexture.prototype.delayLoad = function () {
  49156. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49157. return;
  49158. }
  49159. var scene = this.getScene();
  49160. if (!scene) {
  49161. return;
  49162. }
  49163. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49164. this._texture = this._getFromCache(this.url, this._noMipmap);
  49165. if (!this._texture) {
  49166. if (this._prefiltered) {
  49167. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49168. }
  49169. else {
  49170. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49171. }
  49172. }
  49173. };
  49174. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49175. return this._textureMatrix;
  49176. };
  49177. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49178. this._textureMatrix = value;
  49179. };
  49180. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49181. var texture = BABYLON.SerializationHelper.Parse(function () {
  49182. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49183. }, parsedTexture, scene);
  49184. // Animations
  49185. if (parsedTexture.animations) {
  49186. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49187. var parsedAnimation = parsedTexture.animations[animationIndex];
  49188. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49189. }
  49190. }
  49191. return texture;
  49192. };
  49193. CubeTexture.prototype.clone = function () {
  49194. var _this = this;
  49195. return BABYLON.SerializationHelper.Clone(function () {
  49196. var scene = _this.getScene();
  49197. if (!scene) {
  49198. return _this;
  49199. }
  49200. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49201. }, this);
  49202. };
  49203. return CubeTexture;
  49204. }(BABYLON.BaseTexture));
  49205. BABYLON.CubeTexture = CubeTexture;
  49206. })(BABYLON || (BABYLON = {}));
  49207. //# sourceMappingURL=babylon.cubeTexture.js.map
  49208. var BABYLON;
  49209. (function (BABYLON) {
  49210. var RenderTargetTexture = /** @class */ (function (_super) {
  49211. __extends(RenderTargetTexture, _super);
  49212. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49213. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49214. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49215. if (isCube === void 0) { isCube = false; }
  49216. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49217. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49218. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49219. if (isMulti === void 0) { isMulti = false; }
  49220. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49221. _this.isCube = isCube;
  49222. /**
  49223. * Use this list to define the list of mesh you want to render.
  49224. */
  49225. _this.renderList = new Array();
  49226. _this.renderParticles = true;
  49227. _this.renderSprites = false;
  49228. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49229. _this.ignoreCameraViewport = false;
  49230. // Events
  49231. /**
  49232. * An event triggered when the texture is unbind.
  49233. * @type {BABYLON.Observable}
  49234. */
  49235. _this.onBeforeBindObservable = new BABYLON.Observable();
  49236. /**
  49237. * An event triggered when the texture is unbind.
  49238. * @type {BABYLON.Observable}
  49239. */
  49240. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49241. /**
  49242. * An event triggered before rendering the texture
  49243. * @type {BABYLON.Observable}
  49244. */
  49245. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49246. /**
  49247. * An event triggered after rendering the texture
  49248. * @type {BABYLON.Observable}
  49249. */
  49250. _this.onAfterRenderObservable = new BABYLON.Observable();
  49251. /**
  49252. * An event triggered after the texture clear
  49253. * @type {BABYLON.Observable}
  49254. */
  49255. _this.onClearObservable = new BABYLON.Observable();
  49256. _this._currentRefreshId = -1;
  49257. _this._refreshRate = 1;
  49258. _this._samples = 1;
  49259. scene = _this.getScene();
  49260. if (!scene) {
  49261. return _this;
  49262. }
  49263. _this.name = name;
  49264. _this.isRenderTarget = true;
  49265. _this._size = size;
  49266. _this._generateMipMaps = generateMipMaps ? true : false;
  49267. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49268. // Rendering groups
  49269. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49270. if (isMulti) {
  49271. return _this;
  49272. }
  49273. _this._renderTargetOptions = {
  49274. generateMipMaps: generateMipMaps,
  49275. type: type,
  49276. samplingMode: samplingMode,
  49277. generateDepthBuffer: generateDepthBuffer,
  49278. generateStencilBuffer: generateStencilBuffer
  49279. };
  49280. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49281. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49282. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49283. }
  49284. if (isCube) {
  49285. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  49286. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49287. _this._textureMatrix = BABYLON.Matrix.Identity();
  49288. }
  49289. else {
  49290. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  49291. }
  49292. return _this;
  49293. }
  49294. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49295. get: function () {
  49296. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49297. },
  49298. enumerable: true,
  49299. configurable: true
  49300. });
  49301. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49302. get: function () {
  49303. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49304. },
  49305. enumerable: true,
  49306. configurable: true
  49307. });
  49308. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49309. get: function () {
  49310. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49311. },
  49312. enumerable: true,
  49313. configurable: true
  49314. });
  49315. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49316. set: function (callback) {
  49317. if (this._onAfterUnbindObserver) {
  49318. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49319. }
  49320. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49321. },
  49322. enumerable: true,
  49323. configurable: true
  49324. });
  49325. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  49326. set: function (callback) {
  49327. if (this._onBeforeRenderObserver) {
  49328. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49329. }
  49330. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49331. },
  49332. enumerable: true,
  49333. configurable: true
  49334. });
  49335. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49336. set: function (callback) {
  49337. if (this._onAfterRenderObserver) {
  49338. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49339. }
  49340. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49341. },
  49342. enumerable: true,
  49343. configurable: true
  49344. });
  49345. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  49346. set: function (callback) {
  49347. if (this._onClearObserver) {
  49348. this.onClearObservable.remove(this._onClearObserver);
  49349. }
  49350. this._onClearObserver = this.onClearObservable.add(callback);
  49351. },
  49352. enumerable: true,
  49353. configurable: true
  49354. });
  49355. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  49356. get: function () {
  49357. return this._renderTargetOptions;
  49358. },
  49359. enumerable: true,
  49360. configurable: true
  49361. });
  49362. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  49363. get: function () {
  49364. return this._samples;
  49365. },
  49366. set: function (value) {
  49367. if (this._samples === value) {
  49368. return;
  49369. }
  49370. var scene = this.getScene();
  49371. if (!scene) {
  49372. return;
  49373. }
  49374. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  49375. },
  49376. enumerable: true,
  49377. configurable: true
  49378. });
  49379. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  49380. this._currentRefreshId = -1;
  49381. };
  49382. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  49383. get: function () {
  49384. return this._refreshRate;
  49385. },
  49386. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49387. set: function (value) {
  49388. this._refreshRate = value;
  49389. this.resetRefreshCounter();
  49390. },
  49391. enumerable: true,
  49392. configurable: true
  49393. });
  49394. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  49395. if (!this._postProcessManager) {
  49396. var scene = this.getScene();
  49397. if (!scene) {
  49398. return;
  49399. }
  49400. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  49401. this._postProcesses = new Array();
  49402. }
  49403. this._postProcesses.push(postProcess);
  49404. this._postProcesses[0].autoClear = false;
  49405. };
  49406. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  49407. if (!this._postProcesses) {
  49408. return;
  49409. }
  49410. if (dispose) {
  49411. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  49412. var postProcess = _a[_i];
  49413. postProcess.dispose();
  49414. }
  49415. }
  49416. this._postProcesses = [];
  49417. };
  49418. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  49419. if (!this._postProcesses) {
  49420. return;
  49421. }
  49422. var index = this._postProcesses.indexOf(postProcess);
  49423. if (index === -1) {
  49424. return;
  49425. }
  49426. this._postProcesses.splice(index, 1);
  49427. if (this._postProcesses.length > 0) {
  49428. this._postProcesses[0].autoClear = false;
  49429. }
  49430. };
  49431. RenderTargetTexture.prototype._shouldRender = function () {
  49432. if (this._currentRefreshId === -1) {
  49433. this._currentRefreshId = 1;
  49434. return true;
  49435. }
  49436. if (this.refreshRate === this._currentRefreshId) {
  49437. this._currentRefreshId = 1;
  49438. return true;
  49439. }
  49440. this._currentRefreshId++;
  49441. return false;
  49442. };
  49443. RenderTargetTexture.prototype.getRenderSize = function () {
  49444. return this._size;
  49445. };
  49446. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  49447. get: function () {
  49448. return true;
  49449. },
  49450. enumerable: true,
  49451. configurable: true
  49452. });
  49453. RenderTargetTexture.prototype.scale = function (ratio) {
  49454. var newSize = this._size * ratio;
  49455. this.resize(newSize);
  49456. };
  49457. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  49458. if (this.isCube) {
  49459. return this._textureMatrix;
  49460. }
  49461. return _super.prototype.getReflectionTextureMatrix.call(this);
  49462. };
  49463. RenderTargetTexture.prototype.resize = function (size) {
  49464. this.releaseInternalTexture();
  49465. var scene = this.getScene();
  49466. if (!scene) {
  49467. return;
  49468. }
  49469. if (this.isCube) {
  49470. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  49471. }
  49472. else {
  49473. this._texture = scene.getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  49474. }
  49475. this._size = size;
  49476. };
  49477. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  49478. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  49479. if (dumpForDebug === void 0) { dumpForDebug = false; }
  49480. var scene = this.getScene();
  49481. if (!scene) {
  49482. return;
  49483. }
  49484. var engine = scene.getEngine();
  49485. if (this.useCameraPostProcesses !== undefined) {
  49486. useCameraPostProcess = this.useCameraPostProcesses;
  49487. }
  49488. if (this._waitingRenderList) {
  49489. this.renderList = [];
  49490. for (var index = 0; index < this._waitingRenderList.length; index++) {
  49491. var id = this._waitingRenderList[index];
  49492. var mesh_1 = scene.getMeshByID(id);
  49493. if (mesh_1) {
  49494. this.renderList.push(mesh_1);
  49495. }
  49496. }
  49497. delete this._waitingRenderList;
  49498. }
  49499. // Is predicate defined?
  49500. if (this.renderListPredicate) {
  49501. if (this.renderList) {
  49502. this.renderList.splice(0); // Clear previous renderList
  49503. }
  49504. else {
  49505. this.renderList = [];
  49506. }
  49507. var scene = this.getScene();
  49508. if (!scene) {
  49509. return;
  49510. }
  49511. var sceneMeshes = scene.meshes;
  49512. for (var index = 0; index < sceneMeshes.length; index++) {
  49513. var mesh = sceneMeshes[index];
  49514. if (this.renderListPredicate(mesh)) {
  49515. this.renderList.push(mesh);
  49516. }
  49517. }
  49518. }
  49519. this.onBeforeBindObservable.notifyObservers(this);
  49520. // Set custom projection.
  49521. // Needs to be before binding to prevent changing the aspect ratio.
  49522. var camera;
  49523. if (this.activeCamera) {
  49524. camera = this.activeCamera;
  49525. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  49526. if (this.activeCamera !== scene.activeCamera) {
  49527. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  49528. }
  49529. }
  49530. else {
  49531. camera = scene.activeCamera;
  49532. if (camera) {
  49533. engine.setViewport(camera.viewport, this._size, this._size);
  49534. }
  49535. }
  49536. // Prepare renderingManager
  49537. this._renderingManager.reset();
  49538. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  49539. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  49540. var sceneRenderId = scene.getRenderId();
  49541. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  49542. var mesh = currentRenderList[meshIndex];
  49543. if (mesh) {
  49544. if (!mesh.isReady()) {
  49545. // Reset _currentRefreshId
  49546. this.resetRefreshCounter();
  49547. continue;
  49548. }
  49549. mesh._preActivateForIntermediateRendering(sceneRenderId);
  49550. var isMasked = void 0;
  49551. if (!this.renderList && camera) {
  49552. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  49553. }
  49554. else {
  49555. isMasked = false;
  49556. }
  49557. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  49558. mesh._activate(sceneRenderId);
  49559. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49560. var subMesh = mesh.subMeshes[subIndex];
  49561. scene._activeIndices.addCount(subMesh.indexCount, false);
  49562. this._renderingManager.dispatch(subMesh);
  49563. }
  49564. }
  49565. }
  49566. }
  49567. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  49568. var particleSystem = scene.particleSystems[particleIndex];
  49569. var emitter = particleSystem.emitter;
  49570. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  49571. continue;
  49572. }
  49573. if (currentRenderList.indexOf(emitter) >= 0) {
  49574. this._renderingManager.dispatchParticles(particleSystem);
  49575. }
  49576. }
  49577. if (this.isCube) {
  49578. for (var face = 0; face < 6; face++) {
  49579. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49580. scene.incrementRenderId();
  49581. scene.resetCachedMaterial();
  49582. }
  49583. }
  49584. else {
  49585. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49586. }
  49587. this.onAfterUnbindObservable.notifyObservers(this);
  49588. if (scene.activeCamera) {
  49589. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  49590. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  49591. }
  49592. engine.setViewport(scene.activeCamera.viewport);
  49593. }
  49594. scene.resetCachedMaterial();
  49595. };
  49596. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  49597. var _this = this;
  49598. var scene = this.getScene();
  49599. if (!scene) {
  49600. return;
  49601. }
  49602. var engine = scene.getEngine();
  49603. if (!this._texture) {
  49604. return;
  49605. }
  49606. // Bind
  49607. if (this._postProcessManager) {
  49608. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  49609. }
  49610. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  49611. if (this._texture) {
  49612. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  49613. }
  49614. }
  49615. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  49616. // Clear
  49617. if (this.onClearObservable.hasObservers()) {
  49618. this.onClearObservable.notifyObservers(engine);
  49619. }
  49620. else {
  49621. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  49622. }
  49623. if (!this._doNotChangeAspectRatio) {
  49624. scene.updateTransformMatrix(true);
  49625. }
  49626. // Render
  49627. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  49628. if (this._postProcessManager) {
  49629. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  49630. }
  49631. else if (useCameraPostProcess) {
  49632. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  49633. }
  49634. if (!this._doNotChangeAspectRatio) {
  49635. scene.updateTransformMatrix(true);
  49636. }
  49637. // Dump ?
  49638. if (dumpForDebug) {
  49639. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  49640. }
  49641. // Unbind
  49642. if (!this.isCube || faceIndex === 5) {
  49643. if (this.isCube) {
  49644. if (faceIndex === 5) {
  49645. engine.generateMipMapsForCubemap(this._texture);
  49646. }
  49647. }
  49648. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  49649. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  49650. });
  49651. }
  49652. else {
  49653. this.onAfterRenderObservable.notifyObservers(faceIndex);
  49654. }
  49655. };
  49656. /**
  49657. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  49658. * This allowed control for front to back rendering or reversly depending of the special needs.
  49659. *
  49660. * @param renderingGroupId The rendering group id corresponding to its index
  49661. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  49662. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  49663. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  49664. */
  49665. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  49666. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  49667. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  49668. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  49669. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  49670. };
  49671. /**
  49672. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  49673. *
  49674. * @param renderingGroupId The rendering group id corresponding to its index
  49675. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  49676. */
  49677. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  49678. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  49679. };
  49680. RenderTargetTexture.prototype.clone = function () {
  49681. var textureSize = this.getSize();
  49682. 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);
  49683. // Base texture
  49684. newTexture.hasAlpha = this.hasAlpha;
  49685. newTexture.level = this.level;
  49686. // RenderTarget Texture
  49687. newTexture.coordinatesMode = this.coordinatesMode;
  49688. if (this.renderList) {
  49689. newTexture.renderList = this.renderList.slice(0);
  49690. }
  49691. return newTexture;
  49692. };
  49693. RenderTargetTexture.prototype.serialize = function () {
  49694. if (!this.name) {
  49695. return null;
  49696. }
  49697. var serializationObject = _super.prototype.serialize.call(this);
  49698. serializationObject.renderTargetSize = this.getRenderSize();
  49699. serializationObject.renderList = [];
  49700. if (this.renderList) {
  49701. for (var index = 0; index < this.renderList.length; index++) {
  49702. serializationObject.renderList.push(this.renderList[index].id);
  49703. }
  49704. }
  49705. return serializationObject;
  49706. };
  49707. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  49708. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  49709. var objBuffer = this.getInternalTexture();
  49710. var scene = this.getScene();
  49711. if (objBuffer && scene) {
  49712. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  49713. }
  49714. };
  49715. RenderTargetTexture.prototype.dispose = function () {
  49716. if (this._postProcessManager) {
  49717. this._postProcessManager.dispose();
  49718. this._postProcessManager = null;
  49719. }
  49720. this.clearPostProcesses(true);
  49721. this.renderList = null;
  49722. // Remove from custom render targets
  49723. var scene = this.getScene();
  49724. if (!scene) {
  49725. return;
  49726. }
  49727. var index = scene.customRenderTargets.indexOf(this);
  49728. if (index >= 0) {
  49729. scene.customRenderTargets.splice(index, 1);
  49730. }
  49731. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  49732. var camera = _a[_i];
  49733. index = camera.customRenderTargets.indexOf(this);
  49734. if (index >= 0) {
  49735. camera.customRenderTargets.splice(index, 1);
  49736. }
  49737. }
  49738. _super.prototype.dispose.call(this);
  49739. };
  49740. RenderTargetTexture.prototype._rebuild = function () {
  49741. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  49742. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  49743. }
  49744. if (this._postProcessManager) {
  49745. this._postProcessManager._rebuild();
  49746. }
  49747. };
  49748. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  49749. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  49750. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  49751. return RenderTargetTexture;
  49752. }(BABYLON.Texture));
  49753. BABYLON.RenderTargetTexture = RenderTargetTexture;
  49754. })(BABYLON || (BABYLON = {}));
  49755. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  49756. var BABYLON;
  49757. (function (BABYLON) {
  49758. ;
  49759. var MultiRenderTarget = /** @class */ (function (_super) {
  49760. __extends(MultiRenderTarget, _super);
  49761. function MultiRenderTarget(name, size, count, scene, options) {
  49762. var _this = this;
  49763. options = options || {};
  49764. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  49765. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  49766. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  49767. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  49768. _this._engine = scene.getEngine();
  49769. if (!_this.isSupported) {
  49770. _this.dispose();
  49771. return;
  49772. }
  49773. var types = [];
  49774. var samplingModes = [];
  49775. for (var i = 0; i < count; i++) {
  49776. if (options.types && options.types[i]) {
  49777. types.push(options.types[i]);
  49778. }
  49779. else {
  49780. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  49781. }
  49782. if (options.samplingModes && options.samplingModes[i]) {
  49783. samplingModes.push(options.samplingModes[i]);
  49784. }
  49785. else {
  49786. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49787. }
  49788. }
  49789. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  49790. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  49791. _this._count = count;
  49792. _this._size = size;
  49793. _this._multiRenderTargetOptions = {
  49794. samplingModes: samplingModes,
  49795. generateMipMaps: generateMipMaps,
  49796. generateDepthBuffer: generateDepthBuffer,
  49797. generateStencilBuffer: generateStencilBuffer,
  49798. generateDepthTexture: generateDepthTexture,
  49799. types: types,
  49800. textureCount: count
  49801. };
  49802. _this._createInternalTextures();
  49803. _this._createTextures();
  49804. return _this;
  49805. }
  49806. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  49807. get: function () {
  49808. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  49809. },
  49810. enumerable: true,
  49811. configurable: true
  49812. });
  49813. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  49814. get: function () {
  49815. return this._textures;
  49816. },
  49817. enumerable: true,
  49818. configurable: true
  49819. });
  49820. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  49821. get: function () {
  49822. return this._textures[this._textures.length - 1];
  49823. },
  49824. enumerable: true,
  49825. configurable: true
  49826. });
  49827. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  49828. set: function (wrap) {
  49829. if (this._textures) {
  49830. for (var i = 0; i < this._textures.length; i++) {
  49831. this._textures[i].wrapU = wrap;
  49832. }
  49833. }
  49834. },
  49835. enumerable: true,
  49836. configurable: true
  49837. });
  49838. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  49839. set: function (wrap) {
  49840. if (this._textures) {
  49841. for (var i = 0; i < this._textures.length; i++) {
  49842. this._textures[i].wrapV = wrap;
  49843. }
  49844. }
  49845. },
  49846. enumerable: true,
  49847. configurable: true
  49848. });
  49849. MultiRenderTarget.prototype._rebuild = function () {
  49850. this.releaseInternalTextures();
  49851. this._createInternalTextures();
  49852. for (var i = 0; i < this._internalTextures.length; i++) {
  49853. var texture = this._textures[i];
  49854. texture._texture = this._internalTextures[i];
  49855. }
  49856. // Keeps references to frame buffer and stencil/depth buffer
  49857. this._texture = this._internalTextures[0];
  49858. };
  49859. MultiRenderTarget.prototype._createInternalTextures = function () {
  49860. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  49861. };
  49862. MultiRenderTarget.prototype._createTextures = function () {
  49863. this._textures = [];
  49864. for (var i = 0; i < this._internalTextures.length; i++) {
  49865. var texture = new BABYLON.Texture(null, this.getScene());
  49866. texture._texture = this._internalTextures[i];
  49867. this._textures.push(texture);
  49868. }
  49869. // Keeps references to frame buffer and stencil/depth buffer
  49870. this._texture = this._internalTextures[0];
  49871. };
  49872. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  49873. get: function () {
  49874. return this._samples;
  49875. },
  49876. set: function (value) {
  49877. if (this._samples === value) {
  49878. return;
  49879. }
  49880. for (var i = 0; i < this._internalTextures.length; i++) {
  49881. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  49882. }
  49883. },
  49884. enumerable: true,
  49885. configurable: true
  49886. });
  49887. MultiRenderTarget.prototype.resize = function (size) {
  49888. this.releaseInternalTextures();
  49889. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  49890. this._createInternalTextures();
  49891. };
  49892. MultiRenderTarget.prototype.dispose = function () {
  49893. this.releaseInternalTextures();
  49894. _super.prototype.dispose.call(this);
  49895. };
  49896. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  49897. if (!this._internalTextures) {
  49898. return;
  49899. }
  49900. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  49901. if (this._internalTextures[i] !== undefined) {
  49902. this._internalTextures[i].dispose();
  49903. this._internalTextures.splice(i, 1);
  49904. }
  49905. }
  49906. };
  49907. return MultiRenderTarget;
  49908. }(BABYLON.RenderTargetTexture));
  49909. BABYLON.MultiRenderTarget = MultiRenderTarget;
  49910. })(BABYLON || (BABYLON = {}));
  49911. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  49912. var BABYLON;
  49913. (function (BABYLON) {
  49914. var MirrorTexture = /** @class */ (function (_super) {
  49915. __extends(MirrorTexture, _super);
  49916. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  49917. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49919. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49920. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  49921. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  49922. _this._transformMatrix = BABYLON.Matrix.Zero();
  49923. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  49924. _this._blurKernelX = 0;
  49925. _this._blurKernelY = 0;
  49926. _this._blurRatio = 1.0;
  49927. _this.ignoreCameraViewport = true;
  49928. _this.onBeforeRenderObservable.add(function () {
  49929. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  49930. _this._savedViewMatrix = scene.getViewMatrix();
  49931. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  49932. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  49933. scene.clipPlane = _this.mirrorPlane;
  49934. scene.getEngine().cullBackFaces = false;
  49935. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  49936. });
  49937. _this.onAfterRenderObservable.add(function () {
  49938. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  49939. scene.getEngine().cullBackFaces = true;
  49940. scene._mirroredCameraPosition = null;
  49941. delete scene.clipPlane;
  49942. });
  49943. return _this;
  49944. }
  49945. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  49946. get: function () {
  49947. return this._blurRatio;
  49948. },
  49949. set: function (value) {
  49950. if (this._blurRatio === value) {
  49951. return;
  49952. }
  49953. this._blurRatio = value;
  49954. this._preparePostProcesses();
  49955. },
  49956. enumerable: true,
  49957. configurable: true
  49958. });
  49959. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  49960. set: function (value) {
  49961. this.blurKernelX = value;
  49962. this.blurKernelY = value;
  49963. },
  49964. enumerable: true,
  49965. configurable: true
  49966. });
  49967. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  49968. get: function () {
  49969. return this._blurKernelX;
  49970. },
  49971. set: function (value) {
  49972. if (this._blurKernelX === value) {
  49973. return;
  49974. }
  49975. this._blurKernelX = value;
  49976. this._preparePostProcesses();
  49977. },
  49978. enumerable: true,
  49979. configurable: true
  49980. });
  49981. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  49982. get: function () {
  49983. return this._blurKernelY;
  49984. },
  49985. set: function (value) {
  49986. if (this._blurKernelY === value) {
  49987. return;
  49988. }
  49989. this._blurKernelY = value;
  49990. this._preparePostProcesses();
  49991. },
  49992. enumerable: true,
  49993. configurable: true
  49994. });
  49995. MirrorTexture.prototype._preparePostProcesses = function () {
  49996. this.clearPostProcesses(true);
  49997. if (this._blurKernelX && this._blurKernelY) {
  49998. var engine = this.getScene().getEngine();
  49999. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50000. 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);
  50001. this._blurX.autoClear = false;
  50002. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  50003. this._blurX.outputTexture = this._texture;
  50004. }
  50005. else {
  50006. this._blurX.alwaysForcePOT = true;
  50007. }
  50008. 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);
  50009. this._blurY.autoClear = false;
  50010. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  50011. this.addPostProcess(this._blurX);
  50012. this.addPostProcess(this._blurY);
  50013. }
  50014. };
  50015. MirrorTexture.prototype.clone = function () {
  50016. var scene = this.getScene();
  50017. if (!scene) {
  50018. return this;
  50019. }
  50020. var textureSize = this.getSize();
  50021. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  50022. // Base texture
  50023. newTexture.hasAlpha = this.hasAlpha;
  50024. newTexture.level = this.level;
  50025. // Mirror Texture
  50026. newTexture.mirrorPlane = this.mirrorPlane.clone();
  50027. if (this.renderList) {
  50028. newTexture.renderList = this.renderList.slice(0);
  50029. }
  50030. return newTexture;
  50031. };
  50032. MirrorTexture.prototype.serialize = function () {
  50033. if (!this.name) {
  50034. return null;
  50035. }
  50036. var serializationObject = _super.prototype.serialize.call(this);
  50037. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  50038. return serializationObject;
  50039. };
  50040. return MirrorTexture;
  50041. }(BABYLON.RenderTargetTexture));
  50042. BABYLON.MirrorTexture = MirrorTexture;
  50043. })(BABYLON || (BABYLON = {}));
  50044. //# sourceMappingURL=babylon.mirrorTexture.js.map
  50045. var BABYLON;
  50046. (function (BABYLON) {
  50047. /**
  50048. * Creates a refraction texture used by refraction channel of the standard material.
  50049. * @param name the texture name
  50050. * @param size size of the underlying texture
  50051. * @param scene root scene
  50052. */
  50053. var RefractionTexture = /** @class */ (function (_super) {
  50054. __extends(RefractionTexture, _super);
  50055. function RefractionTexture(name, size, scene, generateMipMaps) {
  50056. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  50057. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  50058. _this.depth = 2.0;
  50059. _this.onBeforeRenderObservable.add(function () {
  50060. scene.clipPlane = _this.refractionPlane;
  50061. });
  50062. _this.onAfterRenderObservable.add(function () {
  50063. delete scene.clipPlane;
  50064. });
  50065. return _this;
  50066. }
  50067. RefractionTexture.prototype.clone = function () {
  50068. var scene = this.getScene();
  50069. if (!scene) {
  50070. return this;
  50071. }
  50072. var textureSize = this.getSize();
  50073. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  50074. // Base texture
  50075. newTexture.hasAlpha = this.hasAlpha;
  50076. newTexture.level = this.level;
  50077. // Refraction Texture
  50078. newTexture.refractionPlane = this.refractionPlane.clone();
  50079. if (this.renderList) {
  50080. newTexture.renderList = this.renderList.slice(0);
  50081. }
  50082. newTexture.depth = this.depth;
  50083. return newTexture;
  50084. };
  50085. RefractionTexture.prototype.serialize = function () {
  50086. if (!this.name) {
  50087. return null;
  50088. }
  50089. var serializationObject = _super.prototype.serialize.call(this);
  50090. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  50091. serializationObject.depth = this.depth;
  50092. return serializationObject;
  50093. };
  50094. return RefractionTexture;
  50095. }(BABYLON.RenderTargetTexture));
  50096. BABYLON.RefractionTexture = RefractionTexture;
  50097. })(BABYLON || (BABYLON = {}));
  50098. //# sourceMappingURL=babylon.refractionTexture.js.map
  50099. var BABYLON;
  50100. (function (BABYLON) {
  50101. var DynamicTexture = /** @class */ (function (_super) {
  50102. __extends(DynamicTexture, _super);
  50103. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  50104. if (scene === void 0) { scene = null; }
  50105. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50106. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50107. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  50108. _this.name = name;
  50109. _this._engine = _this.getScene().getEngine();
  50110. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50111. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50112. _this._generateMipMaps = generateMipMaps;
  50113. if (options.getContext) {
  50114. _this._canvas = options;
  50115. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50116. }
  50117. else {
  50118. _this._canvas = document.createElement("canvas");
  50119. if (options.width) {
  50120. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50121. }
  50122. else {
  50123. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  50124. }
  50125. }
  50126. var textureSize = _this.getSize();
  50127. _this._canvas.width = textureSize.width;
  50128. _this._canvas.height = textureSize.height;
  50129. _this._context = _this._canvas.getContext("2d");
  50130. return _this;
  50131. }
  50132. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  50133. get: function () {
  50134. return true;
  50135. },
  50136. enumerable: true,
  50137. configurable: true
  50138. });
  50139. DynamicTexture.prototype._recreate = function (textureSize) {
  50140. this._canvas.width = textureSize.width;
  50141. this._canvas.height = textureSize.height;
  50142. this.releaseInternalTexture();
  50143. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  50144. };
  50145. DynamicTexture.prototype.scale = function (ratio) {
  50146. var textureSize = this.getSize();
  50147. textureSize.width *= ratio;
  50148. textureSize.height *= ratio;
  50149. this._recreate(textureSize);
  50150. };
  50151. DynamicTexture.prototype.scaleTo = function (width, height) {
  50152. var textureSize = this.getSize();
  50153. textureSize.width = width;
  50154. textureSize.height = height;
  50155. this._recreate(textureSize);
  50156. };
  50157. DynamicTexture.prototype.getContext = function () {
  50158. return this._context;
  50159. };
  50160. DynamicTexture.prototype.clear = function () {
  50161. var size = this.getSize();
  50162. this._context.fillRect(0, 0, size.width, size.height);
  50163. };
  50164. DynamicTexture.prototype.update = function (invertY) {
  50165. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50166. };
  50167. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50168. if (update === void 0) { update = true; }
  50169. var size = this.getSize();
  50170. if (clearColor) {
  50171. this._context.fillStyle = clearColor;
  50172. this._context.fillRect(0, 0, size.width, size.height);
  50173. }
  50174. this._context.font = font;
  50175. if (x === null || x === undefined) {
  50176. var textSize = this._context.measureText(text);
  50177. x = (size.width - textSize.width) / 2;
  50178. }
  50179. if (y === null || y === undefined) {
  50180. var fontSize = parseInt((font.replace(/\D/g, '')));
  50181. ;
  50182. y = (size.height / 2) + (fontSize / 3.65);
  50183. }
  50184. this._context.fillStyle = color;
  50185. this._context.fillText(text, x, y);
  50186. if (update) {
  50187. this.update(invertY);
  50188. }
  50189. };
  50190. DynamicTexture.prototype.clone = function () {
  50191. var scene = this.getScene();
  50192. if (!scene) {
  50193. return this;
  50194. }
  50195. var textureSize = this.getSize();
  50196. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50197. // Base texture
  50198. newTexture.hasAlpha = this.hasAlpha;
  50199. newTexture.level = this.level;
  50200. // Dynamic Texture
  50201. newTexture.wrapU = this.wrapU;
  50202. newTexture.wrapV = this.wrapV;
  50203. return newTexture;
  50204. };
  50205. DynamicTexture.prototype._rebuild = function () {
  50206. this.update();
  50207. };
  50208. return DynamicTexture;
  50209. }(BABYLON.Texture));
  50210. BABYLON.DynamicTexture = DynamicTexture;
  50211. })(BABYLON || (BABYLON = {}));
  50212. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50213. var BABYLON;
  50214. (function (BABYLON) {
  50215. var VideoTexture = /** @class */ (function (_super) {
  50216. __extends(VideoTexture, _super);
  50217. /**
  50218. * Creates a video texture.
  50219. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50220. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50221. * @param {BABYLON.Scene} scene is obviously the current scene.
  50222. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50223. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50224. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50225. */
  50226. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50227. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50228. if (invertY === void 0) { invertY = false; }
  50229. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50230. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50231. _this._autoLaunch = true;
  50232. var urls = null;
  50233. _this.name = name;
  50234. if (urlsOrVideo instanceof HTMLVideoElement) {
  50235. _this.video = urlsOrVideo;
  50236. }
  50237. else {
  50238. urls = urlsOrVideo;
  50239. _this.video = document.createElement("video");
  50240. _this.video.autoplay = false;
  50241. _this.video.loop = true;
  50242. }
  50243. _this._engine = _this.getScene().getEngine();
  50244. _this._generateMipMaps = generateMipMaps;
  50245. _this._samplingMode = samplingMode;
  50246. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  50247. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50248. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50249. }
  50250. else {
  50251. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50252. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50253. _this._generateMipMaps = false;
  50254. }
  50255. if (urls) {
  50256. _this.video.addEventListener("canplay", function () {
  50257. _this._createTexture();
  50258. });
  50259. urls.forEach(function (url) {
  50260. var source = document.createElement("source");
  50261. source.src = url;
  50262. _this.video.appendChild(source);
  50263. });
  50264. }
  50265. else {
  50266. _this._createTexture();
  50267. }
  50268. _this._lastUpdate = BABYLON.Tools.Now;
  50269. return _this;
  50270. }
  50271. VideoTexture.prototype.__setTextureReady = function () {
  50272. if (this._texture) {
  50273. this._texture.isReady = true;
  50274. }
  50275. };
  50276. VideoTexture.prototype._createTexture = function () {
  50277. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  50278. if (this._autoLaunch) {
  50279. this._autoLaunch = false;
  50280. this.video.play();
  50281. }
  50282. this._setTextureReady = this.__setTextureReady.bind(this);
  50283. this.video.addEventListener("playing", this._setTextureReady);
  50284. };
  50285. VideoTexture.prototype._rebuild = function () {
  50286. this.update();
  50287. };
  50288. VideoTexture.prototype.update = function () {
  50289. var now = BABYLON.Tools.Now;
  50290. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  50291. return false;
  50292. }
  50293. this._lastUpdate = now;
  50294. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  50295. return true;
  50296. };
  50297. VideoTexture.prototype.dispose = function () {
  50298. _super.prototype.dispose.call(this);
  50299. this.video.removeEventListener("playing", this._setTextureReady);
  50300. };
  50301. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  50302. var video = document.createElement("video");
  50303. var constraintsDeviceId;
  50304. if (constraints && constraints.deviceId) {
  50305. constraintsDeviceId = {
  50306. exact: constraints.deviceId
  50307. };
  50308. }
  50309. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  50310. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  50311. if (navigator.getUserMedia) {
  50312. navigator.getUserMedia({
  50313. video: {
  50314. deviceId: constraintsDeviceId,
  50315. width: {
  50316. min: (constraints && constraints.minWidth) || 256,
  50317. max: (constraints && constraints.maxWidth) || 640
  50318. },
  50319. height: {
  50320. min: (constraints && constraints.minHeight) || 256,
  50321. max: (constraints && constraints.maxHeight) || 480
  50322. }
  50323. }
  50324. }, function (stream) {
  50325. if (video.mozSrcObject !== undefined) {
  50326. video.mozSrcObject = stream;
  50327. }
  50328. else {
  50329. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  50330. }
  50331. video.play();
  50332. if (onReady) {
  50333. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  50334. }
  50335. }, function (e) {
  50336. BABYLON.Tools.Error(e.name);
  50337. });
  50338. }
  50339. };
  50340. return VideoTexture;
  50341. }(BABYLON.Texture));
  50342. BABYLON.VideoTexture = VideoTexture;
  50343. })(BABYLON || (BABYLON = {}));
  50344. //# sourceMappingURL=babylon.videoTexture.js.map
  50345. var BABYLON;
  50346. (function (BABYLON) {
  50347. var RawTexture = /** @class */ (function (_super) {
  50348. __extends(RawTexture, _super);
  50349. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50350. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50351. if (invertY === void 0) { invertY = false; }
  50352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50353. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50354. _this.format = format;
  50355. _this._engine = scene.getEngine();
  50356. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50357. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50358. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50359. return _this;
  50360. }
  50361. RawTexture.prototype.update = function (data) {
  50362. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  50363. };
  50364. // Statics
  50365. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50366. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50367. if (invertY === void 0) { invertY = false; }
  50368. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50369. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50370. };
  50371. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50372. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50373. if (invertY === void 0) { invertY = false; }
  50374. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50375. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50376. };
  50377. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50378. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50379. if (invertY === void 0) { invertY = false; }
  50380. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50381. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50382. };
  50383. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50384. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50385. if (invertY === void 0) { invertY = false; }
  50386. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50387. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50388. };
  50389. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50390. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50391. if (invertY === void 0) { invertY = false; }
  50392. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50393. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50394. };
  50395. return RawTexture;
  50396. }(BABYLON.Texture));
  50397. BABYLON.RawTexture = RawTexture;
  50398. })(BABYLON || (BABYLON = {}));
  50399. //# sourceMappingURL=babylon.rawTexture.js.map
  50400. var BABYLON;
  50401. (function (BABYLON) {
  50402. var PostProcess = /** @class */ (function () {
  50403. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  50404. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  50405. if (defines === void 0) { defines = null; }
  50406. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50407. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  50408. if (blockCompilation === void 0) { blockCompilation = false; }
  50409. this.name = name;
  50410. this.width = -1;
  50411. this.height = -1;
  50412. this.autoClear = true;
  50413. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  50414. /*
  50415. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  50416. Can only be used on a single postprocess or on the last one of a chain.
  50417. */
  50418. this.enablePixelPerfectMode = false;
  50419. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  50420. this.alwaysForcePOT = false;
  50421. this.samples = 1;
  50422. this.adaptScaleToCurrentViewport = false;
  50423. this._reusable = false;
  50424. this._textures = new BABYLON.SmartArray(2);
  50425. this._currentRenderTextureInd = 0;
  50426. this._scaleRatio = new BABYLON.Vector2(1, 1);
  50427. this._texelSize = BABYLON.Vector2.Zero();
  50428. // Events
  50429. /**
  50430. * An event triggered when the postprocess is activated.
  50431. * @type {BABYLON.Observable}
  50432. */
  50433. this.onActivateObservable = new BABYLON.Observable();
  50434. /**
  50435. * An event triggered when the postprocess changes its size.
  50436. * @type {BABYLON.Observable}
  50437. */
  50438. this.onSizeChangedObservable = new BABYLON.Observable();
  50439. /**
  50440. * An event triggered when the postprocess applies its effect.
  50441. * @type {BABYLON.Observable}
  50442. */
  50443. this.onApplyObservable = new BABYLON.Observable();
  50444. /**
  50445. * An event triggered before rendering the postprocess
  50446. * @type {BABYLON.Observable}
  50447. */
  50448. this.onBeforeRenderObservable = new BABYLON.Observable();
  50449. /**
  50450. * An event triggered after rendering the postprocess
  50451. * @type {BABYLON.Observable}
  50452. */
  50453. this.onAfterRenderObservable = new BABYLON.Observable();
  50454. if (camera != null) {
  50455. this._camera = camera;
  50456. this._scene = camera.getScene();
  50457. camera.attachPostProcess(this);
  50458. this._engine = this._scene.getEngine();
  50459. this._scene.postProcesses.push(this);
  50460. }
  50461. else if (engine) {
  50462. this._engine = engine;
  50463. this._engine.postProcesses.push(this);
  50464. }
  50465. this._options = options;
  50466. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  50467. this._reusable = reusable || false;
  50468. this._textureType = textureType;
  50469. this._samplers = samplers || [];
  50470. this._samplers.push("textureSampler");
  50471. this._fragmentUrl = fragmentUrl;
  50472. this._vertexUrl = vertexUrl;
  50473. this._parameters = parameters || [];
  50474. this._parameters.push("scale");
  50475. this._indexParameters = indexParameters;
  50476. if (!blockCompilation) {
  50477. this.updateEffect(defines);
  50478. }
  50479. }
  50480. Object.defineProperty(PostProcess.prototype, "onActivate", {
  50481. set: function (callback) {
  50482. if (this._onActivateObserver) {
  50483. this.onActivateObservable.remove(this._onActivateObserver);
  50484. }
  50485. if (callback) {
  50486. this._onActivateObserver = this.onActivateObservable.add(callback);
  50487. }
  50488. },
  50489. enumerable: true,
  50490. configurable: true
  50491. });
  50492. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  50493. set: function (callback) {
  50494. if (this._onSizeChangedObserver) {
  50495. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  50496. }
  50497. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  50498. },
  50499. enumerable: true,
  50500. configurable: true
  50501. });
  50502. Object.defineProperty(PostProcess.prototype, "onApply", {
  50503. set: function (callback) {
  50504. if (this._onApplyObserver) {
  50505. this.onApplyObservable.remove(this._onApplyObserver);
  50506. }
  50507. this._onApplyObserver = this.onApplyObservable.add(callback);
  50508. },
  50509. enumerable: true,
  50510. configurable: true
  50511. });
  50512. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  50513. set: function (callback) {
  50514. if (this._onBeforeRenderObserver) {
  50515. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50516. }
  50517. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50518. },
  50519. enumerable: true,
  50520. configurable: true
  50521. });
  50522. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  50523. set: function (callback) {
  50524. if (this._onAfterRenderObserver) {
  50525. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50526. }
  50527. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50528. },
  50529. enumerable: true,
  50530. configurable: true
  50531. });
  50532. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  50533. get: function () {
  50534. return this._textures.data[this._currentRenderTextureInd];
  50535. },
  50536. set: function (value) {
  50537. this._forcedOutputTexture = value;
  50538. },
  50539. enumerable: true,
  50540. configurable: true
  50541. });
  50542. PostProcess.prototype.getCamera = function () {
  50543. return this._camera;
  50544. };
  50545. Object.defineProperty(PostProcess.prototype, "texelSize", {
  50546. get: function () {
  50547. if (this._shareOutputWithPostProcess) {
  50548. return this._shareOutputWithPostProcess.texelSize;
  50549. }
  50550. if (this._forcedOutputTexture) {
  50551. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  50552. }
  50553. return this._texelSize;
  50554. },
  50555. enumerable: true,
  50556. configurable: true
  50557. });
  50558. PostProcess.prototype.getEngine = function () {
  50559. return this._engine;
  50560. };
  50561. PostProcess.prototype.getEffect = function () {
  50562. return this._effect;
  50563. };
  50564. PostProcess.prototype.shareOutputWith = function (postProcess) {
  50565. this._disposeTextures();
  50566. this._shareOutputWithPostProcess = postProcess;
  50567. return this;
  50568. };
  50569. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  50570. if (defines === void 0) { defines = null; }
  50571. if (uniforms === void 0) { uniforms = null; }
  50572. if (samplers === void 0) { samplers = null; }
  50573. 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);
  50574. };
  50575. PostProcess.prototype.isReusable = function () {
  50576. return this._reusable;
  50577. };
  50578. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  50579. PostProcess.prototype.markTextureDirty = function () {
  50580. this.width = -1;
  50581. };
  50582. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  50583. var _this = this;
  50584. if (sourceTexture === void 0) { sourceTexture = null; }
  50585. camera = camera || this._camera;
  50586. var scene = camera.getScene();
  50587. var engine = scene.getEngine();
  50588. var maxSize = engine.getCaps().maxTextureSize;
  50589. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  50590. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  50591. var desiredWidth = (this._options.width || requiredWidth);
  50592. var desiredHeight = this._options.height || requiredHeight;
  50593. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  50594. if (this.adaptScaleToCurrentViewport) {
  50595. var currentViewport = engine.currentViewport;
  50596. if (currentViewport) {
  50597. desiredWidth *= currentViewport.width;
  50598. desiredHeight *= currentViewport.height;
  50599. }
  50600. }
  50601. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  50602. if (!this._options.width) {
  50603. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  50604. }
  50605. if (!this._options.height) {
  50606. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  50607. }
  50608. }
  50609. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  50610. if (this._textures.length > 0) {
  50611. for (var i = 0; i < this._textures.length; i++) {
  50612. this._engine._releaseTexture(this._textures.data[i]);
  50613. }
  50614. this._textures.reset();
  50615. }
  50616. this.width = desiredWidth;
  50617. this.height = desiredHeight;
  50618. var textureSize = { width: this.width, height: this.height };
  50619. var textureOptions = {
  50620. generateMipMaps: false,
  50621. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  50622. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  50623. samplingMode: this.renderTargetSamplingMode,
  50624. type: this._textureType
  50625. };
  50626. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50627. if (this._reusable) {
  50628. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50629. }
  50630. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  50631. this.onSizeChangedObservable.notifyObservers(this);
  50632. }
  50633. this._textures.forEach(function (texture) {
  50634. if (texture.samples !== _this.samples) {
  50635. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  50636. }
  50637. });
  50638. }
  50639. var target;
  50640. if (this._shareOutputWithPostProcess) {
  50641. target = this._shareOutputWithPostProcess.outputTexture;
  50642. }
  50643. else if (this._forcedOutputTexture) {
  50644. target = this._forcedOutputTexture;
  50645. this.width = this._forcedOutputTexture.width;
  50646. this.height = this._forcedOutputTexture.height;
  50647. }
  50648. else {
  50649. target = this.outputTexture;
  50650. }
  50651. if (this.enablePixelPerfectMode) {
  50652. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  50653. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  50654. }
  50655. else {
  50656. this._scaleRatio.copyFromFloats(1, 1);
  50657. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  50658. }
  50659. this.onActivateObservable.notifyObservers(camera);
  50660. // Clear
  50661. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  50662. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  50663. }
  50664. if (this._reusable) {
  50665. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  50666. }
  50667. };
  50668. Object.defineProperty(PostProcess.prototype, "isSupported", {
  50669. get: function () {
  50670. return this._effect.isSupported;
  50671. },
  50672. enumerable: true,
  50673. configurable: true
  50674. });
  50675. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  50676. get: function () {
  50677. if (this._shareOutputWithPostProcess) {
  50678. return this._shareOutputWithPostProcess.aspectRatio;
  50679. }
  50680. if (this._forcedOutputTexture) {
  50681. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  50682. }
  50683. return this.width / this.height;
  50684. },
  50685. enumerable: true,
  50686. configurable: true
  50687. });
  50688. PostProcess.prototype.apply = function () {
  50689. // Check
  50690. if (!this._effect || !this._effect.isReady())
  50691. return null;
  50692. // States
  50693. this._engine.enableEffect(this._effect);
  50694. this._engine.setState(false);
  50695. this._engine.setDepthBuffer(false);
  50696. this._engine.setDepthWrite(false);
  50697. // Alpha
  50698. this._engine.setAlphaMode(this.alphaMode);
  50699. if (this.alphaConstants) {
  50700. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  50701. }
  50702. // Texture
  50703. var source;
  50704. if (this._shareOutputWithPostProcess) {
  50705. source = this._shareOutputWithPostProcess.outputTexture;
  50706. }
  50707. else if (this._forcedOutputTexture) {
  50708. source = this._forcedOutputTexture;
  50709. }
  50710. else {
  50711. source = this.outputTexture;
  50712. }
  50713. this._effect._bindTexture("textureSampler", source);
  50714. // Parameters
  50715. this._effect.setVector2("scale", this._scaleRatio);
  50716. this.onApplyObservable.notifyObservers(this._effect);
  50717. return this._effect;
  50718. };
  50719. PostProcess.prototype._disposeTextures = function () {
  50720. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  50721. return;
  50722. }
  50723. if (this._textures.length > 0) {
  50724. for (var i = 0; i < this._textures.length; i++) {
  50725. this._engine._releaseTexture(this._textures.data[i]);
  50726. }
  50727. }
  50728. this._textures.dispose();
  50729. };
  50730. PostProcess.prototype.dispose = function (camera) {
  50731. camera = camera || this._camera;
  50732. this._disposeTextures();
  50733. if (this._scene) {
  50734. var index_1 = this._scene.postProcesses.indexOf(this);
  50735. if (index_1 !== -1) {
  50736. this._scene.postProcesses.splice(index_1, 1);
  50737. }
  50738. }
  50739. else {
  50740. var index_2 = this._engine.postProcesses.indexOf(this);
  50741. if (index_2 !== -1) {
  50742. this._engine.postProcesses.splice(index_2, 1);
  50743. }
  50744. }
  50745. if (!camera) {
  50746. return;
  50747. }
  50748. camera.detachPostProcess(this);
  50749. var index = camera._postProcesses.indexOf(this);
  50750. if (index === 0 && camera._postProcesses.length > 0) {
  50751. this._camera._postProcesses[0].markTextureDirty();
  50752. }
  50753. this.onActivateObservable.clear();
  50754. this.onAfterRenderObservable.clear();
  50755. this.onApplyObservable.clear();
  50756. this.onBeforeRenderObservable.clear();
  50757. this.onSizeChangedObservable.clear();
  50758. };
  50759. return PostProcess;
  50760. }());
  50761. BABYLON.PostProcess = PostProcess;
  50762. })(BABYLON || (BABYLON = {}));
  50763. //# sourceMappingURL=babylon.postProcess.js.map
  50764. var BABYLON;
  50765. (function (BABYLON) {
  50766. var PassPostProcess = /** @class */ (function (_super) {
  50767. __extends(PassPostProcess, _super);
  50768. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50769. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50770. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  50771. }
  50772. return PassPostProcess;
  50773. }(BABYLON.PostProcess));
  50774. BABYLON.PassPostProcess = PassPostProcess;
  50775. })(BABYLON || (BABYLON = {}));
  50776. //# sourceMappingURL=babylon.passPostProcess.js.map
  50777. var BABYLON;
  50778. (function (BABYLON) {
  50779. var ShadowGenerator = /** @class */ (function () {
  50780. /**
  50781. * Creates a ShadowGenerator object.
  50782. * A ShadowGenerator is the required tool to use the shadows.
  50783. * Each light casting shadows needs to use its own ShadowGenerator.
  50784. * Required parameters :
  50785. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  50786. * - `light`: the light object generating the shadows.
  50787. * - `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.
  50788. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  50789. */
  50790. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  50791. // Members
  50792. this._bias = 0.00005;
  50793. this._blurBoxOffset = 1;
  50794. this._blurScale = 2;
  50795. this._blurKernel = 1;
  50796. this._useKernelBlur = false;
  50797. this._filter = ShadowGenerator.FILTER_NONE;
  50798. this._darkness = 0;
  50799. this._transparencyShadow = false;
  50800. /**
  50801. * Controls the extent to which the shadows fade out at the edge of the frustum
  50802. * Used only by directionals and spots
  50803. */
  50804. this.frustumEdgeFalloff = 0;
  50805. this.forceBackFacesOnly = false;
  50806. this._lightDirection = BABYLON.Vector3.Zero();
  50807. this._viewMatrix = BABYLON.Matrix.Zero();
  50808. this._projectionMatrix = BABYLON.Matrix.Zero();
  50809. this._transformMatrix = BABYLON.Matrix.Zero();
  50810. this._currentFaceIndex = 0;
  50811. this._currentFaceIndexCache = 0;
  50812. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  50813. this._mapSize = mapSize;
  50814. this._light = light;
  50815. this._scene = light.getScene();
  50816. light._shadowGenerator = this;
  50817. // Texture type fallback from float to int if not supported.
  50818. var caps = this._scene.getEngine().getCaps();
  50819. if (!useFullFloatFirst) {
  50820. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50821. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50822. }
  50823. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50824. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50825. }
  50826. else {
  50827. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50828. }
  50829. }
  50830. else {
  50831. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50832. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50833. }
  50834. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50835. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50836. }
  50837. else {
  50838. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50839. }
  50840. }
  50841. this._initializeGenerator();
  50842. }
  50843. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  50844. // Static
  50845. get: function () {
  50846. return ShadowGenerator._FILTER_NONE;
  50847. },
  50848. enumerable: true,
  50849. configurable: true
  50850. });
  50851. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  50852. get: function () {
  50853. return ShadowGenerator._FILTER_POISSONSAMPLING;
  50854. },
  50855. enumerable: true,
  50856. configurable: true
  50857. });
  50858. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  50859. get: function () {
  50860. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  50861. },
  50862. enumerable: true,
  50863. configurable: true
  50864. });
  50865. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  50866. get: function () {
  50867. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  50868. },
  50869. enumerable: true,
  50870. configurable: true
  50871. });
  50872. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  50873. get: function () {
  50874. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50875. },
  50876. enumerable: true,
  50877. configurable: true
  50878. });
  50879. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  50880. get: function () {
  50881. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50882. },
  50883. enumerable: true,
  50884. configurable: true
  50885. });
  50886. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  50887. get: function () {
  50888. return this._bias;
  50889. },
  50890. set: function (bias) {
  50891. this._bias = bias;
  50892. },
  50893. enumerable: true,
  50894. configurable: true
  50895. });
  50896. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  50897. get: function () {
  50898. return this._blurBoxOffset;
  50899. },
  50900. set: function (value) {
  50901. if (this._blurBoxOffset === value) {
  50902. return;
  50903. }
  50904. this._blurBoxOffset = value;
  50905. this._disposeBlurPostProcesses();
  50906. },
  50907. enumerable: true,
  50908. configurable: true
  50909. });
  50910. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  50911. get: function () {
  50912. return this._blurScale;
  50913. },
  50914. set: function (value) {
  50915. if (this._blurScale === value) {
  50916. return;
  50917. }
  50918. this._blurScale = value;
  50919. this._disposeBlurPostProcesses();
  50920. },
  50921. enumerable: true,
  50922. configurable: true
  50923. });
  50924. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  50925. get: function () {
  50926. return this._blurKernel;
  50927. },
  50928. set: function (value) {
  50929. if (this._blurKernel === value) {
  50930. return;
  50931. }
  50932. this._blurKernel = value;
  50933. this._disposeBlurPostProcesses();
  50934. },
  50935. enumerable: true,
  50936. configurable: true
  50937. });
  50938. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  50939. get: function () {
  50940. return this._useKernelBlur;
  50941. },
  50942. set: function (value) {
  50943. if (this._useKernelBlur === value) {
  50944. return;
  50945. }
  50946. this._useKernelBlur = value;
  50947. this._disposeBlurPostProcesses();
  50948. },
  50949. enumerable: true,
  50950. configurable: true
  50951. });
  50952. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  50953. get: function () {
  50954. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  50955. },
  50956. set: function (value) {
  50957. this._depthScale = value;
  50958. },
  50959. enumerable: true,
  50960. configurable: true
  50961. });
  50962. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  50963. get: function () {
  50964. return this._filter;
  50965. },
  50966. set: function (value) {
  50967. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  50968. if (this._light.needCube()) {
  50969. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50970. this.useExponentialShadowMap = true;
  50971. return;
  50972. }
  50973. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50974. this.useCloseExponentialShadowMap = true;
  50975. return;
  50976. }
  50977. }
  50978. if (this._filter === value) {
  50979. return;
  50980. }
  50981. this._filter = value;
  50982. this._disposeBlurPostProcesses();
  50983. this._applyFilterValues();
  50984. this._light._markMeshesAsLightDirty();
  50985. },
  50986. enumerable: true,
  50987. configurable: true
  50988. });
  50989. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  50990. get: function () {
  50991. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  50992. },
  50993. set: function (value) {
  50994. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  50995. return;
  50996. }
  50997. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  50998. },
  50999. enumerable: true,
  51000. configurable: true
  51001. });
  51002. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  51003. get: function () {
  51004. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51005. return this.useExponentialShadowMap;
  51006. },
  51007. set: function (value) {
  51008. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51009. this.useExponentialShadowMap = value;
  51010. },
  51011. enumerable: true,
  51012. configurable: true
  51013. });
  51014. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  51015. get: function () {
  51016. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51017. return this.useBlurExponentialShadowMap;
  51018. },
  51019. set: function (value) {
  51020. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51021. this.useBlurExponentialShadowMap = value;
  51022. },
  51023. enumerable: true,
  51024. configurable: true
  51025. });
  51026. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  51027. get: function () {
  51028. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  51029. },
  51030. set: function (value) {
  51031. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  51032. return;
  51033. }
  51034. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51035. },
  51036. enumerable: true,
  51037. configurable: true
  51038. });
  51039. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  51040. get: function () {
  51041. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  51042. },
  51043. set: function (value) {
  51044. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51045. return;
  51046. }
  51047. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51048. },
  51049. enumerable: true,
  51050. configurable: true
  51051. });
  51052. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  51053. get: function () {
  51054. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51055. },
  51056. set: function (value) {
  51057. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  51058. return;
  51059. }
  51060. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51061. },
  51062. enumerable: true,
  51063. configurable: true
  51064. });
  51065. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  51066. get: function () {
  51067. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51068. },
  51069. set: function (value) {
  51070. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51071. return;
  51072. }
  51073. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51074. },
  51075. enumerable: true,
  51076. configurable: true
  51077. });
  51078. /**
  51079. * Returns the darkness value (float).
  51080. */
  51081. ShadowGenerator.prototype.getDarkness = function () {
  51082. return this._darkness;
  51083. };
  51084. /**
  51085. * Sets the ShadowGenerator darkness value (float <= 1.0).
  51086. * Returns the ShadowGenerator.
  51087. */
  51088. ShadowGenerator.prototype.setDarkness = function (darkness) {
  51089. if (darkness >= 1.0)
  51090. this._darkness = 1.0;
  51091. else if (darkness <= 0.0)
  51092. this._darkness = 0.0;
  51093. else
  51094. this._darkness = darkness;
  51095. return this;
  51096. };
  51097. /**
  51098. * Sets the ability to have transparent shadow (boolean).
  51099. * Returns the ShadowGenerator.
  51100. */
  51101. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  51102. this._transparencyShadow = hasShadow;
  51103. return this;
  51104. };
  51105. /**
  51106. * Returns a RenderTargetTexture object : the shadow map texture.
  51107. */
  51108. ShadowGenerator.prototype.getShadowMap = function () {
  51109. return this._shadowMap;
  51110. };
  51111. /**
  51112. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  51113. */
  51114. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  51115. if (this._shadowMap2) {
  51116. return this._shadowMap2;
  51117. }
  51118. return this._shadowMap;
  51119. };
  51120. /**
  51121. * Helper function to add a mesh and its descendants to the list of shadow casters
  51122. * @param mesh Mesh to add
  51123. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  51124. */
  51125. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  51126. if (includeDescendants === void 0) { includeDescendants = true; }
  51127. if (!this._shadowMap) {
  51128. return this;
  51129. }
  51130. if (!this._shadowMap.renderList) {
  51131. this._shadowMap.renderList = [];
  51132. }
  51133. this._shadowMap.renderList.push(mesh);
  51134. if (includeDescendants) {
  51135. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  51136. }
  51137. return this;
  51138. var _a;
  51139. };
  51140. /**
  51141. * Helper function to remove a mesh and its descendants from the list of shadow casters
  51142. * @param mesh Mesh to remove
  51143. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  51144. */
  51145. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  51146. if (includeDescendants === void 0) { includeDescendants = true; }
  51147. if (!this._shadowMap || !this._shadowMap.renderList) {
  51148. return this;
  51149. }
  51150. var index = this._shadowMap.renderList.indexOf(mesh);
  51151. if (index !== -1) {
  51152. this._shadowMap.renderList.splice(index, 1);
  51153. }
  51154. if (includeDescendants) {
  51155. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  51156. var child = _a[_i];
  51157. this.removeShadowCaster(child);
  51158. }
  51159. }
  51160. return this;
  51161. };
  51162. /**
  51163. * Returns the associated light object.
  51164. */
  51165. ShadowGenerator.prototype.getLight = function () {
  51166. return this._light;
  51167. };
  51168. ShadowGenerator.prototype._initializeGenerator = function () {
  51169. this._light._markMeshesAsLightDirty();
  51170. this._initializeShadowMap();
  51171. };
  51172. ShadowGenerator.prototype._initializeShadowMap = function () {
  51173. var _this = this;
  51174. // Render target
  51175. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51176. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51177. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51178. this._shadowMap.anisotropicFilteringLevel = 1;
  51179. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51180. this._shadowMap.renderParticles = false;
  51181. this._shadowMap.ignoreCameraViewport = true;
  51182. // Record Face Index before render.
  51183. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51184. _this._currentFaceIndex = faceIndex;
  51185. });
  51186. // Custom render function.
  51187. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51188. // Blur if required afer render.
  51189. this._shadowMap.onAfterUnbindObservable.add(function () {
  51190. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51191. return;
  51192. }
  51193. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51194. _this._initializeBlurRTTAndPostProcesses();
  51195. }
  51196. var shadowMap = _this.getShadowMapForRendering();
  51197. if (shadowMap) {
  51198. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51199. }
  51200. });
  51201. // Clear according to the chosen filter.
  51202. this._shadowMap.onClearObservable.add(function (engine) {
  51203. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51204. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51205. }
  51206. else {
  51207. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51208. }
  51209. });
  51210. };
  51211. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51212. var _this = this;
  51213. var engine = this._scene.getEngine();
  51214. var targetSize = this._mapSize / this.blurScale;
  51215. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51216. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51217. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51218. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51219. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51220. }
  51221. if (this.useKernelBlur) {
  51222. 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);
  51223. this._kernelBlurXPostprocess.width = targetSize;
  51224. this._kernelBlurXPostprocess.height = targetSize;
  51225. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51226. effect.setTexture("textureSampler", _this._shadowMap);
  51227. });
  51228. 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);
  51229. this._kernelBlurXPostprocess.autoClear = false;
  51230. this._kernelBlurYPostprocess.autoClear = false;
  51231. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51232. this._kernelBlurXPostprocess.packedFloat = true;
  51233. this._kernelBlurYPostprocess.packedFloat = true;
  51234. }
  51235. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51236. }
  51237. else {
  51238. 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);
  51239. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51240. effect.setFloat2("screenSize", targetSize, targetSize);
  51241. effect.setTexture("textureSampler", _this._shadowMap);
  51242. });
  51243. this._boxBlurPostprocess.autoClear = false;
  51244. this._blurPostProcesses = [this._boxBlurPostprocess];
  51245. }
  51246. };
  51247. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  51248. var index;
  51249. var engine = this._scene.getEngine();
  51250. if (depthOnlySubMeshes.length) {
  51251. engine.setColorWrite(false);
  51252. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  51253. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  51254. }
  51255. engine.setColorWrite(true);
  51256. }
  51257. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51258. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  51259. }
  51260. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51261. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  51262. }
  51263. if (this._transparencyShadow) {
  51264. for (index = 0; index < transparentSubMeshes.length; index++) {
  51265. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  51266. }
  51267. }
  51268. };
  51269. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  51270. var _this = this;
  51271. var mesh = subMesh.getRenderingMesh();
  51272. var scene = this._scene;
  51273. var engine = scene.getEngine();
  51274. var material = subMesh.getMaterial();
  51275. if (!material) {
  51276. return;
  51277. }
  51278. // Culling
  51279. engine.setState(material.backFaceCulling);
  51280. // Managing instances
  51281. var batch = mesh._getInstancesRenderList(subMesh._id);
  51282. if (batch.mustReturn) {
  51283. return;
  51284. }
  51285. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  51286. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  51287. engine.enableEffect(this._effect);
  51288. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  51289. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  51290. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  51291. this._effect.setVector3("lightPosition", this.getLight().position);
  51292. if (scene.activeCamera) {
  51293. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  51294. }
  51295. // Alpha test
  51296. if (material && material.needAlphaTesting()) {
  51297. var alphaTexture = material.getAlphaTestTexture();
  51298. if (alphaTexture) {
  51299. this._effect.setTexture("diffuseSampler", alphaTexture);
  51300. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  51301. }
  51302. }
  51303. // Bones
  51304. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51305. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  51306. }
  51307. if (this.forceBackFacesOnly) {
  51308. engine.setState(true, 0, false, true);
  51309. }
  51310. // Draw
  51311. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51312. if (this.forceBackFacesOnly) {
  51313. engine.setState(true, 0, false, false);
  51314. }
  51315. }
  51316. else {
  51317. // Need to reset refresh rate of the shadowMap
  51318. if (this._shadowMap) {
  51319. this._shadowMap.resetRefreshCounter();
  51320. }
  51321. }
  51322. };
  51323. ShadowGenerator.prototype._applyFilterValues = function () {
  51324. if (!this._shadowMap) {
  51325. return;
  51326. }
  51327. if (this.filter === ShadowGenerator.FILTER_NONE) {
  51328. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  51329. }
  51330. else {
  51331. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51332. }
  51333. };
  51334. /**
  51335. * Force shader compilation including textures ready check
  51336. */
  51337. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  51338. var _this = this;
  51339. var shadowMap = this.getShadowMap();
  51340. if (!shadowMap) {
  51341. return;
  51342. }
  51343. var subMeshes = new Array();
  51344. var currentIndex = 0;
  51345. var renderList = shadowMap.renderList;
  51346. if (!renderList) {
  51347. return;
  51348. }
  51349. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  51350. var mesh = renderList_1[_i];
  51351. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  51352. }
  51353. var checkReady = function () {
  51354. if (!_this._scene || !_this._scene.getEngine()) {
  51355. return;
  51356. }
  51357. while (_this.isReady(subMeshes[currentIndex], options ? options.useInstances : false)) {
  51358. currentIndex++;
  51359. if (currentIndex >= subMeshes.length) {
  51360. if (onCompiled) {
  51361. onCompiled(_this);
  51362. }
  51363. return;
  51364. }
  51365. }
  51366. setTimeout(checkReady, 16);
  51367. };
  51368. if (subMeshes.length > 0) {
  51369. checkReady();
  51370. }
  51371. };
  51372. /**
  51373. * Boolean : true when the ShadowGenerator is finally computed.
  51374. */
  51375. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  51376. var defines = [];
  51377. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51378. defines.push("#define FLOAT");
  51379. }
  51380. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51381. defines.push("#define ESM");
  51382. }
  51383. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51384. var mesh = subMesh.getMesh();
  51385. var material = subMesh.getMaterial();
  51386. // Alpha test
  51387. if (material && material.needAlphaTesting()) {
  51388. var alphaTexture = material.getAlphaTestTexture();
  51389. if (alphaTexture) {
  51390. defines.push("#define ALPHATEST");
  51391. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51392. attribs.push(BABYLON.VertexBuffer.UVKind);
  51393. defines.push("#define UV1");
  51394. }
  51395. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51396. if (alphaTexture.coordinatesIndex === 1) {
  51397. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51398. defines.push("#define UV2");
  51399. }
  51400. }
  51401. }
  51402. }
  51403. // Bones
  51404. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51405. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51406. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51407. if (mesh.numBoneInfluencers > 4) {
  51408. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51409. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51410. }
  51411. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51412. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51413. }
  51414. else {
  51415. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51416. }
  51417. // Instances
  51418. if (useInstances) {
  51419. defines.push("#define INSTANCES");
  51420. attribs.push("world0");
  51421. attribs.push("world1");
  51422. attribs.push("world2");
  51423. attribs.push("world3");
  51424. }
  51425. // Get correct effect
  51426. var join = defines.join("\n");
  51427. if (this._cachedDefines !== join) {
  51428. this._cachedDefines = join;
  51429. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  51430. }
  51431. return this._effect.isReady();
  51432. };
  51433. /**
  51434. * This creates the defines related to the standard BJS materials.
  51435. */
  51436. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  51437. var scene = this._scene;
  51438. var light = this._light;
  51439. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51440. return;
  51441. }
  51442. defines["SHADOW" + lightIndex] = true;
  51443. if (this.usePoissonSampling) {
  51444. defines["SHADOWPCF" + lightIndex] = true;
  51445. }
  51446. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51447. defines["SHADOWESM" + lightIndex] = true;
  51448. }
  51449. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  51450. defines["SHADOWCLOSEESM" + lightIndex] = true;
  51451. }
  51452. if (light.needCube()) {
  51453. defines["SHADOWCUBE" + lightIndex] = true;
  51454. }
  51455. };
  51456. /**
  51457. * This binds shadow lights related to the standard BJS materials.
  51458. * It implies the unifroms available on the materials are the standard BJS ones.
  51459. */
  51460. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  51461. var light = this._light;
  51462. var scene = this._scene;
  51463. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51464. return;
  51465. }
  51466. var camera = scene.activeCamera;
  51467. if (!camera) {
  51468. return;
  51469. }
  51470. var shadowMap = this.getShadowMap();
  51471. if (!shadowMap) {
  51472. return;
  51473. }
  51474. if (!light.needCube()) {
  51475. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  51476. }
  51477. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  51478. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  51479. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  51480. };
  51481. // Methods
  51482. /**
  51483. * Returns a Matrix object : the updated transformation matrix.
  51484. */
  51485. ShadowGenerator.prototype.getTransformMatrix = function () {
  51486. var scene = this._scene;
  51487. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  51488. return this._transformMatrix;
  51489. }
  51490. this._currentRenderID = scene.getRenderId();
  51491. this._currentFaceIndexCache = this._currentFaceIndex;
  51492. var lightPosition = this._light.position;
  51493. if (this._light.computeTransformedInformation()) {
  51494. lightPosition = this._light.transformedPosition;
  51495. }
  51496. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  51497. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  51498. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  51499. }
  51500. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  51501. this._cachedPosition = lightPosition.clone();
  51502. this._cachedDirection = this._lightDirection.clone();
  51503. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  51504. var shadowMap = this.getShadowMap();
  51505. if (shadowMap) {
  51506. var renderList = shadowMap.renderList;
  51507. if (renderList) {
  51508. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  51509. }
  51510. }
  51511. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  51512. }
  51513. return this._transformMatrix;
  51514. };
  51515. ShadowGenerator.prototype.recreateShadowMap = function () {
  51516. var shadowMap = this._shadowMap;
  51517. if (!shadowMap) {
  51518. return;
  51519. }
  51520. // Track render list.
  51521. var renderList = shadowMap.renderList;
  51522. // Clean up existing data.
  51523. this._disposeRTTandPostProcesses();
  51524. // Reinitializes.
  51525. this._initializeGenerator();
  51526. // Reaffect the filter to ensure a correct fallback if necessary.
  51527. this.filter = this.filter;
  51528. // Reaffect the filter.
  51529. this._applyFilterValues();
  51530. // Reaffect Render List.
  51531. this._shadowMap.renderList = renderList;
  51532. };
  51533. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  51534. if (this._shadowMap2) {
  51535. this._shadowMap2.dispose();
  51536. this._shadowMap2 = null;
  51537. }
  51538. if (this._downSamplePostprocess) {
  51539. this._downSamplePostprocess.dispose();
  51540. this._downSamplePostprocess = null;
  51541. }
  51542. if (this._boxBlurPostprocess) {
  51543. this._boxBlurPostprocess.dispose();
  51544. this._boxBlurPostprocess = null;
  51545. }
  51546. if (this._kernelBlurXPostprocess) {
  51547. this._kernelBlurXPostprocess.dispose();
  51548. this._kernelBlurXPostprocess = null;
  51549. }
  51550. if (this._kernelBlurYPostprocess) {
  51551. this._kernelBlurYPostprocess.dispose();
  51552. this._kernelBlurYPostprocess = null;
  51553. }
  51554. this._blurPostProcesses = [];
  51555. };
  51556. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  51557. if (this._shadowMap) {
  51558. this._shadowMap.dispose();
  51559. this._shadowMap = null;
  51560. }
  51561. this._disposeBlurPostProcesses();
  51562. };
  51563. /**
  51564. * Disposes the ShadowGenerator.
  51565. * Returns nothing.
  51566. */
  51567. ShadowGenerator.prototype.dispose = function () {
  51568. this._disposeRTTandPostProcesses();
  51569. if (this._light) {
  51570. this._light._shadowGenerator = null;
  51571. this._light._markMeshesAsLightDirty();
  51572. }
  51573. };
  51574. /**
  51575. * Serializes the ShadowGenerator and returns a serializationObject.
  51576. */
  51577. ShadowGenerator.prototype.serialize = function () {
  51578. var serializationObject = {};
  51579. var shadowMap = this.getShadowMap();
  51580. if (!shadowMap) {
  51581. return serializationObject;
  51582. }
  51583. serializationObject.lightId = this._light.id;
  51584. serializationObject.mapSize = shadowMap.getRenderSize();
  51585. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  51586. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  51587. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51588. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51589. serializationObject.usePoissonSampling = this.usePoissonSampling;
  51590. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  51591. serializationObject.depthScale = this.depthScale;
  51592. serializationObject.darkness = this.getDarkness();
  51593. serializationObject.blurBoxOffset = this.blurBoxOffset;
  51594. serializationObject.blurKernel = this.blurKernel;
  51595. serializationObject.blurScale = this.blurScale;
  51596. serializationObject.useKernelBlur = this.useKernelBlur;
  51597. serializationObject.transparencyShadow = this._transparencyShadow;
  51598. serializationObject.renderList = [];
  51599. if (shadowMap.renderList) {
  51600. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  51601. var mesh = shadowMap.renderList[meshIndex];
  51602. serializationObject.renderList.push(mesh.id);
  51603. }
  51604. }
  51605. return serializationObject;
  51606. };
  51607. /**
  51608. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  51609. */
  51610. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  51611. //casting to point light, as light is missing the position attr and typescript complains.
  51612. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  51613. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  51614. var shadowMap = shadowGenerator.getShadowMap();
  51615. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  51616. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  51617. meshes.forEach(function (mesh) {
  51618. if (!shadowMap) {
  51619. return;
  51620. }
  51621. if (!shadowMap.renderList) {
  51622. shadowMap.renderList = [];
  51623. }
  51624. shadowMap.renderList.push(mesh);
  51625. });
  51626. }
  51627. if (parsedShadowGenerator.usePoissonSampling) {
  51628. shadowGenerator.usePoissonSampling = true;
  51629. }
  51630. else if (parsedShadowGenerator.useExponentialShadowMap) {
  51631. shadowGenerator.useExponentialShadowMap = true;
  51632. }
  51633. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  51634. shadowGenerator.useBlurExponentialShadowMap = true;
  51635. }
  51636. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  51637. shadowGenerator.useCloseExponentialShadowMap = true;
  51638. }
  51639. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  51640. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  51641. }
  51642. else if (parsedShadowGenerator.useVarianceShadowMap) {
  51643. shadowGenerator.useExponentialShadowMap = true;
  51644. }
  51645. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  51646. shadowGenerator.useBlurExponentialShadowMap = true;
  51647. }
  51648. if (parsedShadowGenerator.depthScale) {
  51649. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  51650. }
  51651. if (parsedShadowGenerator.blurScale) {
  51652. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  51653. }
  51654. if (parsedShadowGenerator.blurBoxOffset) {
  51655. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  51656. }
  51657. if (parsedShadowGenerator.useKernelBlur) {
  51658. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  51659. }
  51660. if (parsedShadowGenerator.blurKernel) {
  51661. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  51662. }
  51663. if (parsedShadowGenerator.bias !== undefined) {
  51664. shadowGenerator.bias = parsedShadowGenerator.bias;
  51665. }
  51666. if (parsedShadowGenerator.darkness) {
  51667. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  51668. }
  51669. if (parsedShadowGenerator.transparencyShadow) {
  51670. shadowGenerator.setTransparencyShadow(true);
  51671. }
  51672. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  51673. return shadowGenerator;
  51674. };
  51675. ShadowGenerator._FILTER_NONE = 0;
  51676. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  51677. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  51678. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  51679. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  51680. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  51681. return ShadowGenerator;
  51682. }());
  51683. BABYLON.ShadowGenerator = ShadowGenerator;
  51684. })(BABYLON || (BABYLON = {}));
  51685. //# sourceMappingURL=babylon.shadowGenerator.js.map
  51686. var BABYLON;
  51687. (function (BABYLON) {
  51688. var DefaultLoadingScreen = /** @class */ (function () {
  51689. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  51690. if (_loadingText === void 0) { _loadingText = ""; }
  51691. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  51692. var _this = this;
  51693. this._renderingCanvas = _renderingCanvas;
  51694. this._loadingText = _loadingText;
  51695. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  51696. // Resize
  51697. this._resizeLoadingUI = function () {
  51698. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  51699. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  51700. if (!_this._loadingDiv) {
  51701. return;
  51702. }
  51703. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  51704. _this._loadingDiv.style.left = canvasRect.left + "px";
  51705. _this._loadingDiv.style.top = canvasRect.top + "px";
  51706. _this._loadingDiv.style.width = canvasRect.width + "px";
  51707. _this._loadingDiv.style.height = canvasRect.height + "px";
  51708. };
  51709. }
  51710. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  51711. if (this._loadingDiv) {
  51712. // Do not add a loading screen if there is already one
  51713. return;
  51714. }
  51715. this._loadingDiv = document.createElement("div");
  51716. this._loadingDiv.id = "babylonjsLoadingDiv";
  51717. this._loadingDiv.style.opacity = "0";
  51718. this._loadingDiv.style.transition = "opacity 1.5s ease";
  51719. this._loadingDiv.style.pointerEvents = "none";
  51720. // Loading text
  51721. this._loadingTextDiv = document.createElement("div");
  51722. this._loadingTextDiv.style.position = "absolute";
  51723. this._loadingTextDiv.style.left = "0";
  51724. this._loadingTextDiv.style.top = "50%";
  51725. this._loadingTextDiv.style.marginTop = "80px";
  51726. this._loadingTextDiv.style.width = "100%";
  51727. this._loadingTextDiv.style.height = "20px";
  51728. this._loadingTextDiv.style.fontFamily = "Arial";
  51729. this._loadingTextDiv.style.fontSize = "14px";
  51730. this._loadingTextDiv.style.color = "white";
  51731. this._loadingTextDiv.style.textAlign = "center";
  51732. this._loadingTextDiv.innerHTML = "Loading";
  51733. this._loadingDiv.appendChild(this._loadingTextDiv);
  51734. //set the predefined text
  51735. this._loadingTextDiv.innerHTML = this._loadingText;
  51736. // Generating keyframes
  51737. var style = document.createElement('style');
  51738. style.type = 'text/css';
  51739. 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 }";
  51740. style.innerHTML = keyFrames;
  51741. document.getElementsByTagName('head')[0].appendChild(style);
  51742. // Loading img
  51743. var imgBack = new Image();
  51744. 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";
  51745. imgBack.style.position = "absolute";
  51746. imgBack.style.left = "50%";
  51747. imgBack.style.top = "50%";
  51748. imgBack.style.marginLeft = "-60px";
  51749. imgBack.style.marginTop = "-60px";
  51750. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  51751. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  51752. imgBack.style.transformOrigin = "50% 50%";
  51753. imgBack.style.webkitTransformOrigin = "50% 50%";
  51754. this._loadingDiv.appendChild(imgBack);
  51755. this._resizeLoadingUI();
  51756. window.addEventListener("resize", this._resizeLoadingUI);
  51757. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51758. document.body.appendChild(this._loadingDiv);
  51759. this._loadingDiv.style.opacity = "1";
  51760. };
  51761. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  51762. var _this = this;
  51763. if (!this._loadingDiv) {
  51764. return;
  51765. }
  51766. var onTransitionEnd = function () {
  51767. if (!_this._loadingDiv) {
  51768. return;
  51769. }
  51770. document.body.removeChild(_this._loadingDiv);
  51771. window.removeEventListener("resize", _this._resizeLoadingUI);
  51772. _this._loadingDiv = null;
  51773. };
  51774. this._loadingDiv.style.opacity = "0";
  51775. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  51776. };
  51777. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  51778. set: function (text) {
  51779. this._loadingText = text;
  51780. if (this._loadingTextDiv) {
  51781. this._loadingTextDiv.innerHTML = this._loadingText;
  51782. }
  51783. },
  51784. enumerable: true,
  51785. configurable: true
  51786. });
  51787. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  51788. get: function () {
  51789. return this._loadingDivBackgroundColor;
  51790. },
  51791. set: function (color) {
  51792. this._loadingDivBackgroundColor = color;
  51793. if (!this._loadingDiv) {
  51794. return;
  51795. }
  51796. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51797. },
  51798. enumerable: true,
  51799. configurable: true
  51800. });
  51801. return DefaultLoadingScreen;
  51802. }());
  51803. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  51804. })(BABYLON || (BABYLON = {}));
  51805. //# sourceMappingURL=babylon.loadingScreen.js.map
  51806. var BABYLON;
  51807. (function (BABYLON) {
  51808. var SceneLoader = /** @class */ (function () {
  51809. function SceneLoader() {
  51810. }
  51811. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  51812. get: function () {
  51813. return 0;
  51814. },
  51815. enumerable: true,
  51816. configurable: true
  51817. });
  51818. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  51819. get: function () {
  51820. return 1;
  51821. },
  51822. enumerable: true,
  51823. configurable: true
  51824. });
  51825. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  51826. get: function () {
  51827. return 2;
  51828. },
  51829. enumerable: true,
  51830. configurable: true
  51831. });
  51832. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  51833. get: function () {
  51834. return 3;
  51835. },
  51836. enumerable: true,
  51837. configurable: true
  51838. });
  51839. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  51840. get: function () {
  51841. return SceneLoader._ForceFullSceneLoadingForIncremental;
  51842. },
  51843. set: function (value) {
  51844. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  51845. },
  51846. enumerable: true,
  51847. configurable: true
  51848. });
  51849. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  51850. get: function () {
  51851. return SceneLoader._ShowLoadingScreen;
  51852. },
  51853. set: function (value) {
  51854. SceneLoader._ShowLoadingScreen = value;
  51855. },
  51856. enumerable: true,
  51857. configurable: true
  51858. });
  51859. Object.defineProperty(SceneLoader, "loggingLevel", {
  51860. get: function () {
  51861. return SceneLoader._loggingLevel;
  51862. },
  51863. set: function (value) {
  51864. SceneLoader._loggingLevel = value;
  51865. },
  51866. enumerable: true,
  51867. configurable: true
  51868. });
  51869. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  51870. get: function () {
  51871. return SceneLoader._CleanBoneMatrixWeights;
  51872. },
  51873. set: function (value) {
  51874. SceneLoader._CleanBoneMatrixWeights = value;
  51875. },
  51876. enumerable: true,
  51877. configurable: true
  51878. });
  51879. SceneLoader._getDefaultPlugin = function () {
  51880. return SceneLoader._registeredPlugins[".babylon"];
  51881. };
  51882. SceneLoader._getPluginForExtension = function (extension) {
  51883. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  51884. if (registeredPlugin) {
  51885. return registeredPlugin;
  51886. }
  51887. return SceneLoader._getDefaultPlugin();
  51888. };
  51889. SceneLoader._getPluginForDirectLoad = function (data) {
  51890. for (var extension in SceneLoader._registeredPlugins) {
  51891. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  51892. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  51893. return SceneLoader._registeredPlugins[extension];
  51894. }
  51895. }
  51896. return SceneLoader._getDefaultPlugin();
  51897. };
  51898. SceneLoader._getPluginForFilename = function (sceneFilename) {
  51899. if (sceneFilename.name) {
  51900. sceneFilename = sceneFilename.name;
  51901. }
  51902. var dotPosition = sceneFilename.lastIndexOf(".");
  51903. var queryStringPosition = sceneFilename.indexOf("?");
  51904. if (queryStringPosition === -1) {
  51905. queryStringPosition = sceneFilename.length;
  51906. }
  51907. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  51908. return SceneLoader._getPluginForExtension(extension);
  51909. };
  51910. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  51911. SceneLoader._getDirectLoad = function (sceneFilename) {
  51912. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  51913. return sceneFilename.substr(5);
  51914. }
  51915. return null;
  51916. };
  51917. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  51918. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  51919. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  51920. var plugin = registeredPlugin.plugin;
  51921. var useArrayBuffer = registeredPlugin.isBinary;
  51922. var database;
  51923. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  51924. var dataCallback = function (data) {
  51925. if (scene.isDisposed) {
  51926. onError("Scene has been disposed");
  51927. return;
  51928. }
  51929. scene.database = database;
  51930. try {
  51931. onSuccess(plugin, data);
  51932. }
  51933. catch (e) {
  51934. onError(null, e);
  51935. }
  51936. };
  51937. var manifestChecked = function (success) {
  51938. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  51939. if (request) {
  51940. onError(request.status + " " + request.statusText);
  51941. }
  51942. });
  51943. };
  51944. if (directLoad) {
  51945. dataCallback(directLoad);
  51946. return;
  51947. }
  51948. if (rootUrl.indexOf("file:") === -1) {
  51949. if (scene.getEngine().enableOfflineSupport) {
  51950. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  51951. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  51952. }
  51953. else {
  51954. manifestChecked(true);
  51955. }
  51956. }
  51957. else {
  51958. var fileOrString = sceneFilename;
  51959. if (fileOrString.name) {
  51960. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  51961. }
  51962. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  51963. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  51964. }
  51965. else {
  51966. onError("Unable to find file named " + sceneFilename);
  51967. return;
  51968. }
  51969. }
  51970. };
  51971. // Public functions
  51972. SceneLoader.GetPluginForExtension = function (extension) {
  51973. return SceneLoader._getPluginForExtension(extension).plugin;
  51974. };
  51975. SceneLoader.RegisterPlugin = function (plugin) {
  51976. if (typeof plugin.extensions === "string") {
  51977. var extension = plugin.extensions;
  51978. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51979. plugin: plugin,
  51980. isBinary: false
  51981. };
  51982. }
  51983. else {
  51984. var extensions = plugin.extensions;
  51985. Object.keys(extensions).forEach(function (extension) {
  51986. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51987. plugin: plugin,
  51988. isBinary: extensions[extension].isBinary
  51989. };
  51990. });
  51991. }
  51992. };
  51993. /**
  51994. * Import meshes into a scene
  51995. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  51996. * @param rootUrl a string that defines the root url for scene and resources
  51997. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51998. * @param scene the instance of BABYLON.Scene to append to
  51999. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  52000. * @param onProgress a callback with a progress event for each file being loaded
  52001. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52002. */
  52003. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52004. if (onSuccess === void 0) { onSuccess = null; }
  52005. if (onProgress === void 0) { onProgress = null; }
  52006. if (onError === void 0) { onError = null; }
  52007. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52008. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52009. return;
  52010. }
  52011. var loadingToken = {};
  52012. scene._addPendingData(loadingToken);
  52013. var errorHandler = function (message, exception) {
  52014. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52015. if (onError) {
  52016. onError(scene, errorMessage, exception);
  52017. }
  52018. else {
  52019. BABYLON.Tools.Error(errorMessage);
  52020. // should the exception be thrown?
  52021. }
  52022. scene._removePendingData(loadingToken);
  52023. };
  52024. var progressHandler = function (event) {
  52025. if (onProgress) {
  52026. onProgress(event);
  52027. }
  52028. };
  52029. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52030. if (plugin.importMesh) {
  52031. var syncedPlugin = plugin;
  52032. var meshes = new Array();
  52033. var particleSystems = new Array();
  52034. var skeletons = new Array();
  52035. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  52036. return;
  52037. }
  52038. if (onSuccess) {
  52039. // wrap onSuccess with try-catch to know if something went wrong.
  52040. try {
  52041. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52042. onSuccess(meshes, particleSystems, skeletons);
  52043. scene._removePendingData(loadingToken);
  52044. }
  52045. catch (e) {
  52046. var message = 'Error in onSuccess callback.';
  52047. errorHandler(message, e);
  52048. }
  52049. }
  52050. }
  52051. else {
  52052. var asyncedPlugin = plugin;
  52053. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  52054. if (onSuccess) {
  52055. try {
  52056. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52057. onSuccess(meshes, particleSystems, skeletons);
  52058. scene._removePendingData(loadingToken);
  52059. }
  52060. catch (e) {
  52061. var message = 'Error in onSuccess callback.';
  52062. errorHandler(message, e);
  52063. }
  52064. }
  52065. }, progressHandler, errorHandler);
  52066. }
  52067. }, progressHandler, errorHandler, pluginExtension);
  52068. };
  52069. /**
  52070. * Load a scene
  52071. * @param rootUrl a string that defines the root url for scene and resources
  52072. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52073. * @param engine is the instance of BABYLON.Engine to use to create the scene
  52074. * @param onSuccess a callback with the scene when import succeeds
  52075. * @param onProgress a callback with a progress event for each file being loaded
  52076. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52077. */
  52078. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  52079. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  52080. };
  52081. /**
  52082. * Append a scene
  52083. * @param rootUrl a string that defines the root url for scene and resources
  52084. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52085. * @param scene is the instance of BABYLON.Scene to append to
  52086. * @param onSuccess a callback with the scene when import succeeds
  52087. * @param onProgress a callback with a progress event for each file being loaded
  52088. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52089. */
  52090. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52091. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52092. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52093. return;
  52094. }
  52095. if (SceneLoader.ShowLoadingScreen) {
  52096. scene.getEngine().displayLoadingUI();
  52097. }
  52098. var loadingToken = {};
  52099. scene._addPendingData(loadingToken);
  52100. var errorHandler = function (message, exception) {
  52101. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52102. if (onError) {
  52103. onError(scene, errorMessage, exception);
  52104. }
  52105. else {
  52106. BABYLON.Tools.Error(errorMessage);
  52107. // should the exception be thrown?
  52108. }
  52109. scene._removePendingData(loadingToken);
  52110. scene.getEngine().hideLoadingUI();
  52111. };
  52112. var progressHandler = function (event) {
  52113. if (onProgress) {
  52114. onProgress(event);
  52115. }
  52116. };
  52117. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52118. if (plugin.load) {
  52119. var syncedPlugin = plugin;
  52120. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  52121. return;
  52122. }
  52123. if (onSuccess) {
  52124. try {
  52125. onSuccess(scene);
  52126. }
  52127. catch (e) {
  52128. errorHandler("Error in onSuccess callback", e);
  52129. }
  52130. }
  52131. scene.loadingPluginName = plugin.name;
  52132. scene._removePendingData(loadingToken);
  52133. }
  52134. else {
  52135. var asyncedPlugin = plugin;
  52136. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  52137. if (onSuccess) {
  52138. onSuccess(scene);
  52139. }
  52140. scene.loadingPluginName = plugin.name;
  52141. scene._removePendingData(loadingToken);
  52142. }, progressHandler, errorHandler);
  52143. }
  52144. if (SceneLoader.ShowLoadingScreen) {
  52145. scene.executeWhenReady(function () {
  52146. scene.getEngine().hideLoadingUI();
  52147. });
  52148. }
  52149. }, progressHandler, errorHandler, pluginExtension);
  52150. };
  52151. // Flags
  52152. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  52153. SceneLoader._ShowLoadingScreen = true;
  52154. SceneLoader._CleanBoneMatrixWeights = false;
  52155. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  52156. // Members
  52157. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  52158. SceneLoader._registeredPlugins = {};
  52159. return SceneLoader;
  52160. }());
  52161. BABYLON.SceneLoader = SceneLoader;
  52162. ;
  52163. })(BABYLON || (BABYLON = {}));
  52164. //# sourceMappingURL=babylon.sceneLoader.js.map
  52165. var BABYLON;
  52166. (function (BABYLON) {
  52167. var Internals;
  52168. (function (Internals) {
  52169. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52170. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52171. var parsedMaterial = parsedData.materials[index];
  52172. if (parsedMaterial.id === id) {
  52173. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52174. }
  52175. }
  52176. return null;
  52177. };
  52178. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52179. for (var i in names) {
  52180. if (mesh.name === names[i]) {
  52181. hierarchyIds.push(mesh.id);
  52182. return true;
  52183. }
  52184. }
  52185. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52186. hierarchyIds.push(mesh.id);
  52187. return true;
  52188. }
  52189. return false;
  52190. };
  52191. var logOperation = function (operation, producer) {
  52192. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52193. };
  52194. BABYLON.SceneLoader.RegisterPlugin({
  52195. name: "babylon.js",
  52196. extensions: ".babylon",
  52197. canDirectLoad: function (data) {
  52198. if (data.indexOf("babylon") !== -1) {
  52199. return true;
  52200. }
  52201. return false;
  52202. },
  52203. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52204. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52205. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52206. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52207. // and avoid problems with multiple concurrent .babylon loads.
  52208. var log = "importMesh has failed JSON parse";
  52209. try {
  52210. var parsedData = JSON.parse(data);
  52211. log = "";
  52212. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52213. if (!meshesNames) {
  52214. meshesNames = null;
  52215. }
  52216. else if (!Array.isArray(meshesNames)) {
  52217. meshesNames = [meshesNames];
  52218. }
  52219. var hierarchyIds = new Array();
  52220. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52221. var loadedSkeletonsIds = [];
  52222. var loadedMaterialsIds = [];
  52223. var index;
  52224. var cache;
  52225. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52226. var parsedMesh = parsedData.meshes[index];
  52227. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52228. if (meshesNames !== null) {
  52229. // Remove found mesh name from list.
  52230. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52231. }
  52232. //Geometry?
  52233. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  52234. //does the file contain geometries?
  52235. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  52236. //find the correct geometry and add it to the scene
  52237. var found = false;
  52238. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  52239. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  52240. return;
  52241. }
  52242. else {
  52243. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  52244. if (parsedGeometryData.id === parsedMesh.geometryId) {
  52245. switch (geometryType) {
  52246. case "boxes":
  52247. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  52248. break;
  52249. case "spheres":
  52250. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  52251. break;
  52252. case "cylinders":
  52253. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  52254. break;
  52255. case "toruses":
  52256. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  52257. break;
  52258. case "grounds":
  52259. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  52260. break;
  52261. case "planes":
  52262. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  52263. break;
  52264. case "torusKnots":
  52265. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  52266. break;
  52267. case "vertexData":
  52268. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  52269. break;
  52270. }
  52271. found = true;
  52272. }
  52273. });
  52274. }
  52275. });
  52276. if (found === false) {
  52277. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  52278. }
  52279. }
  52280. }
  52281. // Material ?
  52282. if (parsedMesh.materialId) {
  52283. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  52284. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52285. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  52286. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  52287. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  52288. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  52289. var subMatId = parsedMultiMaterial.materials[matIndex];
  52290. loadedMaterialsIds.push(subMatId);
  52291. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  52292. log += "\n\tMaterial " + mat.toString(fullDetails);
  52293. }
  52294. loadedMaterialsIds.push(parsedMultiMaterial.id);
  52295. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52296. materialFound = true;
  52297. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  52298. break;
  52299. }
  52300. }
  52301. }
  52302. if (materialFound === false) {
  52303. loadedMaterialsIds.push(parsedMesh.materialId);
  52304. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  52305. if (!mat) {
  52306. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  52307. }
  52308. else {
  52309. log += "\n\tMaterial " + mat.toString(fullDetails);
  52310. }
  52311. }
  52312. }
  52313. // Skeleton ?
  52314. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52315. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  52316. if (skeletonAlreadyLoaded === false) {
  52317. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  52318. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  52319. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  52320. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52321. skeletons.push(skeleton);
  52322. loadedSkeletonsIds.push(parsedSkeleton.id);
  52323. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  52324. }
  52325. }
  52326. }
  52327. }
  52328. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52329. meshes.push(mesh);
  52330. log += "\n\tMesh " + mesh.toString(fullDetails);
  52331. }
  52332. }
  52333. // Connecting parents
  52334. var currentMesh;
  52335. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52336. currentMesh = scene.meshes[index];
  52337. if (currentMesh._waitingParentId) {
  52338. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  52339. currentMesh._waitingParentId = null;
  52340. }
  52341. }
  52342. // freeze and compute world matrix application
  52343. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52344. currentMesh = scene.meshes[index];
  52345. if (currentMesh._waitingFreezeWorldMatrix) {
  52346. currentMesh.freezeWorldMatrix();
  52347. currentMesh._waitingFreezeWorldMatrix = null;
  52348. }
  52349. else {
  52350. currentMesh.computeWorldMatrix(true);
  52351. }
  52352. }
  52353. }
  52354. // Particles
  52355. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52356. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52357. var parsedParticleSystem = parsedData.particleSystems[index];
  52358. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  52359. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  52360. }
  52361. }
  52362. }
  52363. return true;
  52364. }
  52365. catch (err) {
  52366. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  52367. if (onError) {
  52368. onError(msg, err);
  52369. }
  52370. else {
  52371. BABYLON.Tools.Log(msg);
  52372. throw err;
  52373. }
  52374. }
  52375. finally {
  52376. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52377. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52378. }
  52379. }
  52380. return false;
  52381. },
  52382. load: function (scene, data, rootUrl, onError) {
  52383. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52384. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52385. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52386. // and avoid problems with multiple concurrent .babylon loads.
  52387. var log = "importScene has failed JSON parse";
  52388. try {
  52389. var parsedData = JSON.parse(data);
  52390. log = "";
  52391. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52392. // Scene
  52393. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  52394. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  52395. }
  52396. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  52397. scene.autoClear = parsedData.autoClear;
  52398. }
  52399. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  52400. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  52401. }
  52402. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  52403. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  52404. }
  52405. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  52406. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  52407. }
  52408. // Fog
  52409. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  52410. scene.fogMode = parsedData.fogMode;
  52411. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  52412. scene.fogStart = parsedData.fogStart;
  52413. scene.fogEnd = parsedData.fogEnd;
  52414. scene.fogDensity = parsedData.fogDensity;
  52415. log += "\tFog mode for scene: ";
  52416. switch (scene.fogMode) {
  52417. // getters not compiling, so using hardcoded
  52418. case 1:
  52419. log += "exp\n";
  52420. break;
  52421. case 2:
  52422. log += "exp2\n";
  52423. break;
  52424. case 3:
  52425. log += "linear\n";
  52426. break;
  52427. }
  52428. }
  52429. //Physics
  52430. if (parsedData.physicsEnabled) {
  52431. var physicsPlugin;
  52432. if (parsedData.physicsEngine === "cannon") {
  52433. physicsPlugin = new BABYLON.CannonJSPlugin();
  52434. }
  52435. else if (parsedData.physicsEngine === "oimo") {
  52436. physicsPlugin = new BABYLON.OimoJSPlugin();
  52437. }
  52438. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  52439. //else - default engine, which is currently oimo
  52440. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  52441. scene.enablePhysics(physicsGravity, physicsPlugin);
  52442. }
  52443. // Metadata
  52444. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  52445. scene.metadata = parsedData.metadata;
  52446. }
  52447. //collisions, if defined. otherwise, default is true
  52448. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  52449. scene.collisionsEnabled = parsedData.collisionsEnabled;
  52450. }
  52451. scene.workerCollisions = !!parsedData.workerCollisions;
  52452. var index;
  52453. var cache;
  52454. // Lights
  52455. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  52456. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  52457. var parsedLight = parsedData.lights[index];
  52458. var light = BABYLON.Light.Parse(parsedLight, scene);
  52459. if (light) {
  52460. log += (index === 0 ? "\n\tLights:" : "");
  52461. log += "\n\t\t" + light.toString(fullDetails);
  52462. }
  52463. }
  52464. }
  52465. // Animations
  52466. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  52467. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  52468. var parsedAnimation = parsedData.animations[index];
  52469. var animation = BABYLON.Animation.Parse(parsedAnimation);
  52470. scene.animations.push(animation);
  52471. log += (index === 0 ? "\n\tAnimations:" : "");
  52472. log += "\n\t\t" + animation.toString(fullDetails);
  52473. }
  52474. }
  52475. if (parsedData.autoAnimate) {
  52476. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  52477. }
  52478. // Materials
  52479. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  52480. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52481. var parsedMaterial = parsedData.materials[index];
  52482. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52483. log += (index === 0 ? "\n\tMaterials:" : "");
  52484. log += "\n\t\t" + mat.toString(fullDetails);
  52485. }
  52486. }
  52487. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52488. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  52489. var parsedMultiMaterial = parsedData.multiMaterials[index];
  52490. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52491. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  52492. log += "\n\t\t" + mmat.toString(fullDetails);
  52493. }
  52494. }
  52495. // Morph targets
  52496. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  52497. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  52498. var managerData = _a[_i];
  52499. BABYLON.MorphTargetManager.Parse(managerData, scene);
  52500. }
  52501. }
  52502. // Skeletons
  52503. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52504. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  52505. var parsedSkeleton = parsedData.skeletons[index];
  52506. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52507. log += (index === 0 ? "\n\tSkeletons:" : "");
  52508. log += "\n\t\t" + skeleton.toString(fullDetails);
  52509. }
  52510. }
  52511. // Geometries
  52512. var geometries = parsedData.geometries;
  52513. if (geometries !== undefined && geometries !== null) {
  52514. // Boxes
  52515. var boxes = geometries.boxes;
  52516. if (boxes !== undefined && boxes !== null) {
  52517. for (index = 0, cache = boxes.length; index < cache; index++) {
  52518. var parsedBox = boxes[index];
  52519. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  52520. }
  52521. }
  52522. // Spheres
  52523. var spheres = geometries.spheres;
  52524. if (spheres !== undefined && spheres !== null) {
  52525. for (index = 0, cache = spheres.length; index < cache; index++) {
  52526. var parsedSphere = spheres[index];
  52527. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  52528. }
  52529. }
  52530. // Cylinders
  52531. var cylinders = geometries.cylinders;
  52532. if (cylinders !== undefined && cylinders !== null) {
  52533. for (index = 0, cache = cylinders.length; index < cache; index++) {
  52534. var parsedCylinder = cylinders[index];
  52535. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  52536. }
  52537. }
  52538. // Toruses
  52539. var toruses = geometries.toruses;
  52540. if (toruses !== undefined && toruses !== null) {
  52541. for (index = 0, cache = toruses.length; index < cache; index++) {
  52542. var parsedTorus = toruses[index];
  52543. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  52544. }
  52545. }
  52546. // Grounds
  52547. var grounds = geometries.grounds;
  52548. if (grounds !== undefined && grounds !== null) {
  52549. for (index = 0, cache = grounds.length; index < cache; index++) {
  52550. var parsedGround = grounds[index];
  52551. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  52552. }
  52553. }
  52554. // Planes
  52555. var planes = geometries.planes;
  52556. if (planes !== undefined && planes !== null) {
  52557. for (index = 0, cache = planes.length; index < cache; index++) {
  52558. var parsedPlane = planes[index];
  52559. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  52560. }
  52561. }
  52562. // TorusKnots
  52563. var torusKnots = geometries.torusKnots;
  52564. if (torusKnots !== undefined && torusKnots !== null) {
  52565. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  52566. var parsedTorusKnot = torusKnots[index];
  52567. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  52568. }
  52569. }
  52570. // VertexData
  52571. var vertexData = geometries.vertexData;
  52572. if (vertexData !== undefined && vertexData !== null) {
  52573. for (index = 0, cache = vertexData.length; index < cache; index++) {
  52574. var parsedVertexData = vertexData[index];
  52575. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  52576. }
  52577. }
  52578. }
  52579. // Meshes
  52580. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52581. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52582. var parsedMesh = parsedData.meshes[index];
  52583. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52584. log += (index === 0 ? "\n\tMeshes:" : "");
  52585. log += "\n\t\t" + mesh.toString(fullDetails);
  52586. }
  52587. }
  52588. // Cameras
  52589. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  52590. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  52591. var parsedCamera = parsedData.cameras[index];
  52592. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  52593. log += (index === 0 ? "\n\tCameras:" : "");
  52594. log += "\n\t\t" + camera.toString(fullDetails);
  52595. }
  52596. }
  52597. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  52598. scene.setActiveCameraByID(parsedData.activeCameraID);
  52599. }
  52600. // Browsing all the graph to connect the dots
  52601. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  52602. var camera = scene.cameras[index];
  52603. if (camera._waitingParentId) {
  52604. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  52605. camera._waitingParentId = null;
  52606. }
  52607. }
  52608. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52609. var light_1 = scene.lights[index];
  52610. if (light_1 && light_1._waitingParentId) {
  52611. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  52612. light_1._waitingParentId = null;
  52613. }
  52614. }
  52615. // Sounds
  52616. var loadedSounds = [];
  52617. var loadedSound;
  52618. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  52619. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  52620. var parsedSound = parsedData.sounds[index];
  52621. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52622. if (!parsedSound.url)
  52623. parsedSound.url = parsedSound.name;
  52624. if (!loadedSounds[parsedSound.url]) {
  52625. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  52626. loadedSounds[parsedSound.url] = loadedSound;
  52627. }
  52628. else {
  52629. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  52630. }
  52631. }
  52632. else {
  52633. new BABYLON.Sound(parsedSound.name, null, scene);
  52634. }
  52635. }
  52636. }
  52637. loadedSounds = [];
  52638. // Connect parents & children and parse actions
  52639. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52640. var mesh = scene.meshes[index];
  52641. if (mesh._waitingParentId) {
  52642. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  52643. mesh._waitingParentId = null;
  52644. }
  52645. if (mesh._waitingActions) {
  52646. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  52647. mesh._waitingActions = null;
  52648. }
  52649. }
  52650. // freeze world matrix application
  52651. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52652. var currentMesh = scene.meshes[index];
  52653. if (currentMesh._waitingFreezeWorldMatrix) {
  52654. currentMesh.freezeWorldMatrix();
  52655. currentMesh._waitingFreezeWorldMatrix = null;
  52656. }
  52657. else {
  52658. currentMesh.computeWorldMatrix(true);
  52659. }
  52660. }
  52661. // Particles Systems
  52662. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52663. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52664. var parsedParticleSystem = parsedData.particleSystems[index];
  52665. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  52666. }
  52667. }
  52668. // Environment texture
  52669. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  52670. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  52671. if (parsedData.createDefaultSkybox === true) {
  52672. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  52673. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  52674. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  52675. }
  52676. }
  52677. // Lens flares
  52678. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  52679. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  52680. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  52681. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  52682. }
  52683. }
  52684. // Shadows
  52685. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  52686. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  52687. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  52688. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  52689. }
  52690. }
  52691. // Lights exclusions / inclusions
  52692. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52693. var light_2 = scene.lights[index];
  52694. // Excluded check
  52695. if (light_2._excludedMeshesIds.length > 0) {
  52696. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  52697. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  52698. if (excludedMesh) {
  52699. light_2.excludedMeshes.push(excludedMesh);
  52700. }
  52701. }
  52702. light_2._excludedMeshesIds = [];
  52703. }
  52704. // Included check
  52705. if (light_2._includedOnlyMeshesIds.length > 0) {
  52706. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  52707. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  52708. if (includedOnlyMesh) {
  52709. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  52710. }
  52711. }
  52712. light_2._includedOnlyMeshesIds = [];
  52713. }
  52714. }
  52715. // Actions (scene)
  52716. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  52717. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  52718. }
  52719. // Finish
  52720. return true;
  52721. }
  52722. catch (err) {
  52723. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  52724. if (onError) {
  52725. onError(msg, err);
  52726. }
  52727. else {
  52728. BABYLON.Tools.Log(msg);
  52729. throw err;
  52730. }
  52731. }
  52732. finally {
  52733. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52734. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52735. }
  52736. }
  52737. return false;
  52738. }
  52739. });
  52740. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52741. })(BABYLON || (BABYLON = {}));
  52742. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  52743. var BABYLON;
  52744. (function (BABYLON) {
  52745. var FilesInput = /** @class */ (function () {
  52746. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  52747. this.onProcessFileCallback = function () { return true; };
  52748. this._engine = engine;
  52749. this._currentScene = scene;
  52750. this._sceneLoadedCallback = sceneLoadedCallback;
  52751. this._progressCallback = progressCallback;
  52752. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  52753. this._textureLoadingCallback = textureLoadingCallback;
  52754. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  52755. this._onReloadCallback = onReloadCallback;
  52756. this._errorCallback = errorCallback;
  52757. }
  52758. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  52759. var _this = this;
  52760. if (elementToMonitor) {
  52761. this._elementToMonitor = elementToMonitor;
  52762. this._dragEnterHandler = function (e) { _this.drag(e); };
  52763. this._dragOverHandler = function (e) { _this.drag(e); };
  52764. this._dropHandler = function (e) { _this.drop(e); };
  52765. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  52766. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  52767. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  52768. }
  52769. };
  52770. FilesInput.prototype.dispose = function () {
  52771. if (!this._elementToMonitor) {
  52772. return;
  52773. }
  52774. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  52775. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  52776. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  52777. };
  52778. FilesInput.prototype.renderFunction = function () {
  52779. if (this._additionalRenderLoopLogicCallback) {
  52780. this._additionalRenderLoopLogicCallback();
  52781. }
  52782. if (this._currentScene) {
  52783. if (this._textureLoadingCallback) {
  52784. var remaining = this._currentScene.getWaitingItemsCount();
  52785. if (remaining > 0) {
  52786. this._textureLoadingCallback(remaining);
  52787. }
  52788. }
  52789. this._currentScene.render();
  52790. }
  52791. };
  52792. FilesInput.prototype.drag = function (e) {
  52793. e.stopPropagation();
  52794. e.preventDefault();
  52795. };
  52796. FilesInput.prototype.drop = function (eventDrop) {
  52797. eventDrop.stopPropagation();
  52798. eventDrop.preventDefault();
  52799. this.loadFiles(eventDrop);
  52800. };
  52801. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  52802. var _this = this;
  52803. var reader = folder.createReader();
  52804. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  52805. reader.readEntries(function (entries) {
  52806. remaining.count += entries.length;
  52807. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  52808. var entry = entries_1[_i];
  52809. if (entry.isFile) {
  52810. entry.file(function (file) {
  52811. file.correctName = relativePath + file.name;
  52812. files.push(file);
  52813. if (--remaining.count === 0) {
  52814. callback();
  52815. }
  52816. });
  52817. }
  52818. else if (entry.isDirectory) {
  52819. _this._traverseFolder(entry, files, remaining, callback);
  52820. }
  52821. }
  52822. if (--remaining.count) {
  52823. callback();
  52824. }
  52825. });
  52826. };
  52827. FilesInput.prototype._processFiles = function (files) {
  52828. var skippedFiles = 0;
  52829. for (var i = 0; i < files.length; i++) {
  52830. var name = files[i].correctName.toLowerCase();
  52831. var extension = name.split('.').pop();
  52832. if (!this.onProcessFileCallback(files[i], name, extension)) {
  52833. skippedFiles++;
  52834. continue;
  52835. }
  52836. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  52837. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  52838. this._sceneFileToLoad = files[i];
  52839. }
  52840. else {
  52841. FilesInput.FilesToLoad[name] = files[i];
  52842. }
  52843. }
  52844. if (this._onReloadCallback) {
  52845. this._onReloadCallback(this._sceneFileToLoad);
  52846. }
  52847. else if (skippedFiles < files.length) {
  52848. this.reload();
  52849. }
  52850. };
  52851. FilesInput.prototype.loadFiles = function (event) {
  52852. var _this = this;
  52853. if (this._startingProcessingFilesCallback)
  52854. this._startingProcessingFilesCallback();
  52855. // Handling data transfer via drag'n'drop
  52856. if (event && event.dataTransfer && event.dataTransfer.files) {
  52857. this._filesToLoad = event.dataTransfer.files;
  52858. }
  52859. // Handling files from input files
  52860. if (event && event.target && event.target.files) {
  52861. this._filesToLoad = event.target.files;
  52862. }
  52863. if (this._filesToLoad && this._filesToLoad.length > 0) {
  52864. var files_1 = new Array();
  52865. var folders = [];
  52866. var items = event.dataTransfer ? event.dataTransfer.items : null;
  52867. for (var i = 0; i < this._filesToLoad.length; i++) {
  52868. var fileToLoad = this._filesToLoad[i];
  52869. var name_1 = fileToLoad.name.toLowerCase();
  52870. var entry = void 0;
  52871. fileToLoad.correctName = name_1;
  52872. if (items) {
  52873. var item = items[i];
  52874. if (item.getAsEntry) {
  52875. entry = item.getAsEntry();
  52876. }
  52877. else if (item.webkitGetAsEntry) {
  52878. entry = item.webkitGetAsEntry();
  52879. }
  52880. }
  52881. if (!entry) {
  52882. files_1.push(fileToLoad);
  52883. }
  52884. else {
  52885. if (entry.isDirectory) {
  52886. folders.push(entry);
  52887. }
  52888. else {
  52889. files_1.push(fileToLoad);
  52890. }
  52891. }
  52892. }
  52893. if (folders.length === 0) {
  52894. this._processFiles(files_1);
  52895. }
  52896. else {
  52897. var remaining = { count: folders.length };
  52898. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  52899. var folder = folders_1[_i];
  52900. this._traverseFolder(folder, files_1, remaining, function () {
  52901. _this._processFiles(files_1);
  52902. });
  52903. }
  52904. }
  52905. }
  52906. };
  52907. FilesInput.prototype.reload = function () {
  52908. var _this = this;
  52909. // If a ".babylon" file has been provided
  52910. if (this._sceneFileToLoad) {
  52911. if (this._currentScene) {
  52912. if (BABYLON.Tools.errorsCount > 0) {
  52913. BABYLON.Tools.ClearLogCache();
  52914. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  52915. }
  52916. this._engine.stopRenderLoop();
  52917. this._currentScene.dispose();
  52918. }
  52919. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  52920. _this._currentScene = newScene;
  52921. if (_this._sceneLoadedCallback) {
  52922. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  52923. }
  52924. // Wait for textures and shaders to be ready
  52925. _this._currentScene.executeWhenReady(function () {
  52926. _this._engine.runRenderLoop(function () {
  52927. _this.renderFunction();
  52928. });
  52929. });
  52930. }, function (progress) {
  52931. if (_this._progressCallback) {
  52932. _this._progressCallback(progress);
  52933. }
  52934. }, function (scene, message) {
  52935. _this._currentScene = scene;
  52936. if (_this._errorCallback) {
  52937. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  52938. }
  52939. });
  52940. }
  52941. else {
  52942. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  52943. }
  52944. };
  52945. FilesInput.FilesToLoad = {};
  52946. return FilesInput;
  52947. }());
  52948. BABYLON.FilesInput = FilesInput;
  52949. })(BABYLON || (BABYLON = {}));
  52950. //# sourceMappingURL=babylon.filesInput.js.map
  52951. var BABYLON;
  52952. (function (BABYLON) {
  52953. /**
  52954. * This class implement a typical dictionary using a string as key and the generic type T as value.
  52955. * The underlying implementation relies on an associative array to ensure the best performances.
  52956. * The value can be anything including 'null' but except 'undefined'
  52957. */
  52958. var StringDictionary = /** @class */ (function () {
  52959. function StringDictionary() {
  52960. this._count = 0;
  52961. this._data = {};
  52962. }
  52963. /**
  52964. * This will clear this dictionary and copy the content from the 'source' one.
  52965. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  52966. * @param source the dictionary to take the content from and copy to this dictionary
  52967. */
  52968. StringDictionary.prototype.copyFrom = function (source) {
  52969. var _this = this;
  52970. this.clear();
  52971. source.forEach(function (t, v) { return _this.add(t, v); });
  52972. };
  52973. /**
  52974. * Get a value based from its key
  52975. * @param key the given key to get the matching value from
  52976. * @return the value if found, otherwise undefined is returned
  52977. */
  52978. StringDictionary.prototype.get = function (key) {
  52979. var val = this._data[key];
  52980. if (val !== undefined) {
  52981. return val;
  52982. }
  52983. return undefined;
  52984. };
  52985. /**
  52986. * Get a value from its key or add it if it doesn't exist.
  52987. * This method will ensure you that a given key/data will be present in the dictionary.
  52988. * @param key the given key to get the matching value from
  52989. * @param factory the factory that will create the value if the key is not present in the dictionary.
  52990. * The factory will only be invoked if there's no data for the given key.
  52991. * @return the value corresponding to the key.
  52992. */
  52993. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  52994. var val = this.get(key);
  52995. if (val !== undefined) {
  52996. return val;
  52997. }
  52998. val = factory(key);
  52999. if (val) {
  53000. this.add(key, val);
  53001. }
  53002. return val;
  53003. };
  53004. /**
  53005. * Get a value from its key if present in the dictionary otherwise add it
  53006. * @param key the key to get the value from
  53007. * @param val if there's no such key/value pair in the dictionary add it with this value
  53008. * @return the value corresponding to the key
  53009. */
  53010. StringDictionary.prototype.getOrAdd = function (key, val) {
  53011. var curVal = this.get(key);
  53012. if (curVal !== undefined) {
  53013. return curVal;
  53014. }
  53015. this.add(key, val);
  53016. return val;
  53017. };
  53018. /**
  53019. * Check if there's a given key in the dictionary
  53020. * @param key the key to check for
  53021. * @return true if the key is present, false otherwise
  53022. */
  53023. StringDictionary.prototype.contains = function (key) {
  53024. return this._data[key] !== undefined;
  53025. };
  53026. /**
  53027. * Add a new key and its corresponding value
  53028. * @param key the key to add
  53029. * @param value the value corresponding to the key
  53030. * @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
  53031. */
  53032. StringDictionary.prototype.add = function (key, value) {
  53033. if (this._data[key] !== undefined) {
  53034. return false;
  53035. }
  53036. this._data[key] = value;
  53037. ++this._count;
  53038. return true;
  53039. };
  53040. StringDictionary.prototype.set = function (key, value) {
  53041. if (this._data[key] === undefined) {
  53042. return false;
  53043. }
  53044. this._data[key] = value;
  53045. return true;
  53046. };
  53047. /**
  53048. * Get the element of the given key and remove it from the dictionary
  53049. * @param key
  53050. */
  53051. StringDictionary.prototype.getAndRemove = function (key) {
  53052. var val = this.get(key);
  53053. if (val !== undefined) {
  53054. delete this._data[key];
  53055. --this._count;
  53056. return val;
  53057. }
  53058. return null;
  53059. };
  53060. /**
  53061. * Remove a key/value from the dictionary.
  53062. * @param key the key to remove
  53063. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  53064. */
  53065. StringDictionary.prototype.remove = function (key) {
  53066. if (this.contains(key)) {
  53067. delete this._data[key];
  53068. --this._count;
  53069. return true;
  53070. }
  53071. return false;
  53072. };
  53073. /**
  53074. * Clear the whole content of the dictionary
  53075. */
  53076. StringDictionary.prototype.clear = function () {
  53077. this._data = {};
  53078. this._count = 0;
  53079. };
  53080. Object.defineProperty(StringDictionary.prototype, "count", {
  53081. get: function () {
  53082. return this._count;
  53083. },
  53084. enumerable: true,
  53085. configurable: true
  53086. });
  53087. /**
  53088. * Execute a callback on each key/val of the dictionary.
  53089. * Note that you can remove any element in this dictionary in the callback implementation
  53090. * @param callback the callback to execute on a given key/value pair
  53091. */
  53092. StringDictionary.prototype.forEach = function (callback) {
  53093. for (var cur in this._data) {
  53094. var val = this._data[cur];
  53095. callback(cur, val);
  53096. }
  53097. };
  53098. /**
  53099. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  53100. * If the callback returns null or undefined the method will iterate to the next key/value pair
  53101. * Note that you can remove any element in this dictionary in the callback implementation
  53102. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  53103. */
  53104. StringDictionary.prototype.first = function (callback) {
  53105. for (var cur in this._data) {
  53106. var val = this._data[cur];
  53107. var res = callback(cur, val);
  53108. if (res) {
  53109. return res;
  53110. }
  53111. }
  53112. return null;
  53113. };
  53114. return StringDictionary;
  53115. }());
  53116. BABYLON.StringDictionary = StringDictionary;
  53117. })(BABYLON || (BABYLON = {}));
  53118. //# sourceMappingURL=babylon.stringDictionary.js.map
  53119. var BABYLON;
  53120. (function (BABYLON) {
  53121. var Tags = /** @class */ (function () {
  53122. function Tags() {
  53123. }
  53124. Tags.EnableFor = function (obj) {
  53125. obj._tags = obj._tags || {};
  53126. obj.hasTags = function () {
  53127. return Tags.HasTags(obj);
  53128. };
  53129. obj.addTags = function (tagsString) {
  53130. return Tags.AddTagsTo(obj, tagsString);
  53131. };
  53132. obj.removeTags = function (tagsString) {
  53133. return Tags.RemoveTagsFrom(obj, tagsString);
  53134. };
  53135. obj.matchesTagsQuery = function (tagsQuery) {
  53136. return Tags.MatchesQuery(obj, tagsQuery);
  53137. };
  53138. };
  53139. Tags.DisableFor = function (obj) {
  53140. delete obj._tags;
  53141. delete obj.hasTags;
  53142. delete obj.addTags;
  53143. delete obj.removeTags;
  53144. delete obj.matchesTagsQuery;
  53145. };
  53146. Tags.HasTags = function (obj) {
  53147. if (!obj._tags) {
  53148. return false;
  53149. }
  53150. return !BABYLON.Tools.IsEmpty(obj._tags);
  53151. };
  53152. Tags.GetTags = function (obj, asString) {
  53153. if (asString === void 0) { asString = true; }
  53154. if (!obj._tags) {
  53155. return null;
  53156. }
  53157. if (asString) {
  53158. var tagsArray = [];
  53159. for (var tag in obj._tags) {
  53160. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53161. tagsArray.push(tag);
  53162. }
  53163. }
  53164. return tagsArray.join(" ");
  53165. }
  53166. else {
  53167. return obj._tags;
  53168. }
  53169. };
  53170. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53171. // a tag cannot start with '||', '&&', and '!'
  53172. // it cannot contain whitespaces
  53173. Tags.AddTagsTo = function (obj, tagsString) {
  53174. if (!tagsString) {
  53175. return;
  53176. }
  53177. if (typeof tagsString !== "string") {
  53178. return;
  53179. }
  53180. var tags = tagsString.split(" ");
  53181. tags.forEach(function (tag, index, array) {
  53182. Tags._AddTagTo(obj, tag);
  53183. });
  53184. };
  53185. Tags._AddTagTo = function (obj, tag) {
  53186. tag = tag.trim();
  53187. if (tag === "" || tag === "true" || tag === "false") {
  53188. return;
  53189. }
  53190. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53191. return;
  53192. }
  53193. Tags.EnableFor(obj);
  53194. obj._tags[tag] = true;
  53195. };
  53196. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53197. if (!Tags.HasTags(obj)) {
  53198. return;
  53199. }
  53200. var tags = tagsString.split(" ");
  53201. for (var t in tags) {
  53202. Tags._RemoveTagFrom(obj, tags[t]);
  53203. }
  53204. };
  53205. Tags._RemoveTagFrom = function (obj, tag) {
  53206. delete obj._tags[tag];
  53207. };
  53208. Tags.MatchesQuery = function (obj, tagsQuery) {
  53209. if (tagsQuery === undefined) {
  53210. return true;
  53211. }
  53212. if (tagsQuery === "") {
  53213. return Tags.HasTags(obj);
  53214. }
  53215. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53216. };
  53217. return Tags;
  53218. }());
  53219. BABYLON.Tags = Tags;
  53220. })(BABYLON || (BABYLON = {}));
  53221. //# sourceMappingURL=babylon.tags.js.map
  53222. var BABYLON;
  53223. (function (BABYLON) {
  53224. var Internals;
  53225. (function (Internals) {
  53226. var AndOrNotEvaluator = /** @class */ (function () {
  53227. function AndOrNotEvaluator() {
  53228. }
  53229. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  53230. if (!query.match(/\([^\(\)]*\)/g)) {
  53231. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  53232. }
  53233. else {
  53234. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  53235. // remove parenthesis
  53236. r = r.slice(1, r.length - 1);
  53237. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  53238. });
  53239. }
  53240. if (query === "true") {
  53241. return true;
  53242. }
  53243. if (query === "false") {
  53244. return false;
  53245. }
  53246. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  53247. };
  53248. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  53249. evaluateCallback = evaluateCallback || (function (r) {
  53250. return r === "true" ? true : false;
  53251. });
  53252. var result;
  53253. var or = parenthesisContent.split("||");
  53254. for (var i in or) {
  53255. if (or.hasOwnProperty(i)) {
  53256. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  53257. var and = ori.split("&&");
  53258. if (and.length > 1) {
  53259. for (var j = 0; j < and.length; ++j) {
  53260. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  53261. if (andj !== "true" && andj !== "false") {
  53262. if (andj[0] === "!") {
  53263. result = !evaluateCallback(andj.substring(1));
  53264. }
  53265. else {
  53266. result = evaluateCallback(andj);
  53267. }
  53268. }
  53269. else {
  53270. result = andj === "true" ? true : false;
  53271. }
  53272. if (!result) {
  53273. ori = "false";
  53274. break;
  53275. }
  53276. }
  53277. }
  53278. if (result || ori === "true") {
  53279. result = true;
  53280. break;
  53281. }
  53282. // result equals false (or undefined)
  53283. if (ori !== "true" && ori !== "false") {
  53284. if (ori[0] === "!") {
  53285. result = !evaluateCallback(ori.substring(1));
  53286. }
  53287. else {
  53288. result = evaluateCallback(ori);
  53289. }
  53290. }
  53291. else {
  53292. result = ori === "true" ? true : false;
  53293. }
  53294. }
  53295. }
  53296. // the whole parenthesis scope is replaced by 'true' or 'false'
  53297. return result ? "true" : "false";
  53298. };
  53299. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  53300. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  53301. // remove whitespaces
  53302. r = r.replace(/[\s]/g, function () { return ""; });
  53303. return r.length % 2 ? "!" : "";
  53304. });
  53305. booleanString = booleanString.trim();
  53306. if (booleanString === "!true") {
  53307. booleanString = "false";
  53308. }
  53309. else if (booleanString === "!false") {
  53310. booleanString = "true";
  53311. }
  53312. return booleanString;
  53313. };
  53314. return AndOrNotEvaluator;
  53315. }());
  53316. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  53317. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53318. })(BABYLON || (BABYLON = {}));
  53319. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  53320. var BABYLON;
  53321. (function (BABYLON) {
  53322. var Database = /** @class */ (function () {
  53323. function Database(urlToScene, callbackManifestChecked) {
  53324. // Handling various flavors of prefixed version of IndexedDB
  53325. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  53326. this.callbackManifestChecked = callbackManifestChecked;
  53327. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  53328. this.db = null;
  53329. this._enableSceneOffline = false;
  53330. this._enableTexturesOffline = false;
  53331. this.manifestVersionFound = 0;
  53332. this.mustUpdateRessources = false;
  53333. this.hasReachedQuota = false;
  53334. if (!Database.IDBStorageEnabled) {
  53335. this.callbackManifestChecked(true);
  53336. }
  53337. else {
  53338. this.checkManifestFile();
  53339. }
  53340. }
  53341. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  53342. get: function () {
  53343. return this._enableSceneOffline;
  53344. },
  53345. enumerable: true,
  53346. configurable: true
  53347. });
  53348. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  53349. get: function () {
  53350. return this._enableTexturesOffline;
  53351. },
  53352. enumerable: true,
  53353. configurable: true
  53354. });
  53355. Database.prototype.checkManifestFile = function () {
  53356. var _this = this;
  53357. var noManifestFile = function () {
  53358. _this._enableSceneOffline = false;
  53359. _this._enableTexturesOffline = false;
  53360. _this.callbackManifestChecked(false);
  53361. };
  53362. var timeStampUsed = false;
  53363. var manifestURL = this.currentSceneUrl + ".manifest";
  53364. var xhr = new XMLHttpRequest();
  53365. if (navigator.onLine) {
  53366. // Adding a timestamp to by-pass browsers' cache
  53367. timeStampUsed = true;
  53368. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  53369. }
  53370. xhr.open("GET", manifestURL, true);
  53371. xhr.addEventListener("load", function () {
  53372. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53373. try {
  53374. var manifestFile = JSON.parse(xhr.response);
  53375. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  53376. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  53377. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  53378. _this.manifestVersionFound = manifestFile.version;
  53379. }
  53380. if (_this.callbackManifestChecked) {
  53381. _this.callbackManifestChecked(true);
  53382. }
  53383. }
  53384. catch (ex) {
  53385. noManifestFile();
  53386. }
  53387. }
  53388. else {
  53389. noManifestFile();
  53390. }
  53391. }, false);
  53392. xhr.addEventListener("error", function (event) {
  53393. if (timeStampUsed) {
  53394. timeStampUsed = false;
  53395. // Let's retry without the timeStamp
  53396. // It could fail when coupled with HTML5 Offline API
  53397. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  53398. xhr.open("GET", retryManifestURL, true);
  53399. xhr.send();
  53400. }
  53401. else {
  53402. noManifestFile();
  53403. }
  53404. }, false);
  53405. try {
  53406. xhr.send();
  53407. }
  53408. catch (ex) {
  53409. BABYLON.Tools.Error("Error on XHR send request.");
  53410. this.callbackManifestChecked(false);
  53411. }
  53412. };
  53413. Database.prototype.openAsync = function (successCallback, errorCallback) {
  53414. var _this = this;
  53415. var handleError = function () {
  53416. _this.isSupported = false;
  53417. if (errorCallback)
  53418. errorCallback();
  53419. };
  53420. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  53421. // Your browser doesn't support IndexedDB
  53422. this.isSupported = false;
  53423. if (errorCallback)
  53424. errorCallback();
  53425. }
  53426. else {
  53427. // If the DB hasn't been opened or created yet
  53428. if (!this.db) {
  53429. this.hasReachedQuota = false;
  53430. this.isSupported = true;
  53431. var request = this.idbFactory.open("babylonjs", 1);
  53432. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  53433. request.onerror = function (event) {
  53434. handleError();
  53435. };
  53436. // executes when a version change transaction cannot complete due to other active transactions
  53437. request.onblocked = function (event) {
  53438. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  53439. handleError();
  53440. };
  53441. // DB has been opened successfully
  53442. request.onsuccess = function (event) {
  53443. _this.db = request.result;
  53444. successCallback();
  53445. };
  53446. // Initialization of the DB. Creating Scenes & Textures stores
  53447. request.onupgradeneeded = function (event) {
  53448. _this.db = (event.target).result;
  53449. if (_this.db) {
  53450. try {
  53451. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  53452. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  53453. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  53454. }
  53455. catch (ex) {
  53456. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  53457. handleError();
  53458. }
  53459. }
  53460. };
  53461. }
  53462. else {
  53463. if (successCallback)
  53464. successCallback();
  53465. }
  53466. }
  53467. };
  53468. Database.prototype.loadImageFromDB = function (url, image) {
  53469. var _this = this;
  53470. var completeURL = Database.ReturnFullUrlLocation(url);
  53471. var saveAndLoadImage = function () {
  53472. if (!_this.hasReachedQuota && _this.db !== null) {
  53473. // the texture is not yet in the DB, let's try to save it
  53474. _this._saveImageIntoDBAsync(completeURL, image);
  53475. }
  53476. else {
  53477. image.src = url;
  53478. }
  53479. };
  53480. if (!this.mustUpdateRessources) {
  53481. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  53482. }
  53483. else {
  53484. saveAndLoadImage();
  53485. }
  53486. };
  53487. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  53488. if (this.isSupported && this.db !== null) {
  53489. var texture;
  53490. var transaction = this.db.transaction(["textures"]);
  53491. transaction.onabort = function (event) {
  53492. image.src = url;
  53493. };
  53494. transaction.oncomplete = function (event) {
  53495. var blobTextureURL;
  53496. if (texture) {
  53497. var URL = window.URL || window.webkitURL;
  53498. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  53499. image.onerror = function () {
  53500. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  53501. image.src = url;
  53502. };
  53503. image.src = blobTextureURL;
  53504. }
  53505. else {
  53506. notInDBCallback();
  53507. }
  53508. };
  53509. var getRequest = transaction.objectStore("textures").get(url);
  53510. getRequest.onsuccess = function (event) {
  53511. texture = (event.target).result;
  53512. };
  53513. getRequest.onerror = function (event) {
  53514. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  53515. image.src = url;
  53516. };
  53517. }
  53518. else {
  53519. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53520. image.src = url;
  53521. }
  53522. };
  53523. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  53524. var _this = this;
  53525. if (this.isSupported) {
  53526. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  53527. var generateBlobUrl = function () {
  53528. var blobTextureURL;
  53529. if (blob) {
  53530. var URL = window.URL || window.webkitURL;
  53531. try {
  53532. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  53533. }
  53534. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  53535. catch (ex) {
  53536. blobTextureURL = URL.createObjectURL(blob);
  53537. }
  53538. }
  53539. if (blobTextureURL) {
  53540. image.src = blobTextureURL;
  53541. }
  53542. };
  53543. if (Database.IsUASupportingBlobStorage) {
  53544. var xhr = new XMLHttpRequest(), blob;
  53545. xhr.open("GET", url, true);
  53546. xhr.responseType = "blob";
  53547. xhr.addEventListener("load", function () {
  53548. if (xhr.status === 200 && _this.db) {
  53549. // Blob as response (XHR2)
  53550. blob = xhr.response;
  53551. var transaction = _this.db.transaction(["textures"], "readwrite");
  53552. // the transaction could abort because of a QuotaExceededError error
  53553. transaction.onabort = function (event) {
  53554. try {
  53555. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53556. var srcElement = (event.srcElement || event.target);
  53557. var error = srcElement.error;
  53558. if (error && error.name === "QuotaExceededError") {
  53559. _this.hasReachedQuota = true;
  53560. }
  53561. }
  53562. catch (ex) { }
  53563. generateBlobUrl();
  53564. };
  53565. transaction.oncomplete = function (event) {
  53566. generateBlobUrl();
  53567. };
  53568. var newTexture = { textureUrl: url, data: blob };
  53569. try {
  53570. // Put the blob into the dabase
  53571. var addRequest = transaction.objectStore("textures").put(newTexture);
  53572. addRequest.onsuccess = function (event) {
  53573. };
  53574. addRequest.onerror = function (event) {
  53575. generateBlobUrl();
  53576. };
  53577. }
  53578. catch (ex) {
  53579. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  53580. if (ex.code === 25) {
  53581. Database.IsUASupportingBlobStorage = false;
  53582. }
  53583. image.src = url;
  53584. }
  53585. }
  53586. else {
  53587. image.src = url;
  53588. }
  53589. }, false);
  53590. xhr.addEventListener("error", function (event) {
  53591. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  53592. image.src = url;
  53593. }, false);
  53594. xhr.send();
  53595. }
  53596. else {
  53597. image.src = url;
  53598. }
  53599. }
  53600. else {
  53601. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53602. image.src = url;
  53603. }
  53604. };
  53605. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  53606. var _this = this;
  53607. var updateVersion = function () {
  53608. // the version is not yet in the DB or we need to update it
  53609. _this._saveVersionIntoDBAsync(url, versionLoaded);
  53610. };
  53611. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  53612. };
  53613. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  53614. var _this = this;
  53615. if (this.isSupported && this.db) {
  53616. var version;
  53617. try {
  53618. var transaction = this.db.transaction(["versions"]);
  53619. transaction.oncomplete = function (event) {
  53620. if (version) {
  53621. // If the version in the JSON file is > than the version in DB
  53622. if (_this.manifestVersionFound > version.data) {
  53623. _this.mustUpdateRessources = true;
  53624. updateInDBCallback();
  53625. }
  53626. else {
  53627. callback(version.data);
  53628. }
  53629. }
  53630. else {
  53631. _this.mustUpdateRessources = true;
  53632. updateInDBCallback();
  53633. }
  53634. };
  53635. transaction.onabort = function (event) {
  53636. callback(-1);
  53637. };
  53638. var getRequest = transaction.objectStore("versions").get(url);
  53639. getRequest.onsuccess = function (event) {
  53640. version = (event.target).result;
  53641. };
  53642. getRequest.onerror = function (event) {
  53643. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  53644. callback(-1);
  53645. };
  53646. }
  53647. catch (ex) {
  53648. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  53649. callback(-1);
  53650. }
  53651. }
  53652. else {
  53653. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53654. callback(-1);
  53655. }
  53656. };
  53657. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  53658. var _this = this;
  53659. if (this.isSupported && !this.hasReachedQuota && this.db) {
  53660. try {
  53661. // Open a transaction to the database
  53662. var transaction = this.db.transaction(["versions"], "readwrite");
  53663. // the transaction could abort because of a QuotaExceededError error
  53664. transaction.onabort = function (event) {
  53665. try {
  53666. var error = event.srcElement['error'];
  53667. if (error && error.name === "QuotaExceededError") {
  53668. _this.hasReachedQuota = true;
  53669. }
  53670. }
  53671. catch (ex) { }
  53672. callback(-1);
  53673. };
  53674. transaction.oncomplete = function (event) {
  53675. callback(_this.manifestVersionFound);
  53676. };
  53677. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  53678. // Put the scene into the database
  53679. var addRequest = transaction.objectStore("versions").put(newVersion);
  53680. addRequest.onsuccess = function (event) {
  53681. };
  53682. addRequest.onerror = function (event) {
  53683. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  53684. };
  53685. }
  53686. catch (ex) {
  53687. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  53688. callback(-1);
  53689. }
  53690. }
  53691. else {
  53692. callback(-1);
  53693. }
  53694. };
  53695. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  53696. var _this = this;
  53697. var completeUrl = Database.ReturnFullUrlLocation(url);
  53698. var saveAndLoadFile = function () {
  53699. // the scene is not yet in the DB, let's try to save it
  53700. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  53701. };
  53702. this._checkVersionFromDB(completeUrl, function (version) {
  53703. if (version !== -1) {
  53704. if (!_this.mustUpdateRessources) {
  53705. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  53706. }
  53707. else {
  53708. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  53709. }
  53710. }
  53711. else {
  53712. if (errorCallback) {
  53713. errorCallback();
  53714. }
  53715. }
  53716. });
  53717. };
  53718. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  53719. if (this.isSupported && this.db) {
  53720. var targetStore;
  53721. if (url.indexOf(".babylon") !== -1) {
  53722. targetStore = "scenes";
  53723. }
  53724. else {
  53725. targetStore = "textures";
  53726. }
  53727. var file;
  53728. var transaction = this.db.transaction([targetStore]);
  53729. transaction.oncomplete = function (event) {
  53730. if (file) {
  53731. callback(file.data);
  53732. }
  53733. else {
  53734. notInDBCallback();
  53735. }
  53736. };
  53737. transaction.onabort = function (event) {
  53738. notInDBCallback();
  53739. };
  53740. var getRequest = transaction.objectStore(targetStore).get(url);
  53741. getRequest.onsuccess = function (event) {
  53742. file = (event.target).result;
  53743. };
  53744. getRequest.onerror = function (event) {
  53745. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  53746. notInDBCallback();
  53747. };
  53748. }
  53749. else {
  53750. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53751. callback();
  53752. }
  53753. };
  53754. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  53755. var _this = this;
  53756. if (this.isSupported) {
  53757. var targetStore;
  53758. if (url.indexOf(".babylon") !== -1) {
  53759. targetStore = "scenes";
  53760. }
  53761. else {
  53762. targetStore = "textures";
  53763. }
  53764. // Create XHR
  53765. var xhr = new XMLHttpRequest();
  53766. var fileData;
  53767. xhr.open("GET", url, true);
  53768. if (useArrayBuffer) {
  53769. xhr.responseType = "arraybuffer";
  53770. }
  53771. if (progressCallback) {
  53772. xhr.onprogress = progressCallback;
  53773. }
  53774. xhr.addEventListener("load", function () {
  53775. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  53776. // Blob as response (XHR2)
  53777. //fileData = xhr.responseText;
  53778. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  53779. if (!_this.hasReachedQuota && _this.db) {
  53780. // Open a transaction to the database
  53781. var transaction = _this.db.transaction([targetStore], "readwrite");
  53782. // the transaction could abort because of a QuotaExceededError error
  53783. transaction.onabort = function (event) {
  53784. try {
  53785. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53786. var error = event.srcElement['error'];
  53787. if (error && error.name === "QuotaExceededError") {
  53788. _this.hasReachedQuota = true;
  53789. }
  53790. }
  53791. catch (ex) { }
  53792. callback(fileData);
  53793. };
  53794. transaction.oncomplete = function (event) {
  53795. callback(fileData);
  53796. };
  53797. var newFile;
  53798. if (targetStore === "scenes") {
  53799. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  53800. }
  53801. else {
  53802. newFile = { textureUrl: url, data: fileData };
  53803. }
  53804. try {
  53805. // Put the scene into the database
  53806. var addRequest = transaction.objectStore(targetStore).put(newFile);
  53807. addRequest.onsuccess = function (event) {
  53808. };
  53809. addRequest.onerror = function (event) {
  53810. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  53811. };
  53812. }
  53813. catch (ex) {
  53814. callback(fileData);
  53815. }
  53816. }
  53817. else {
  53818. callback(fileData);
  53819. }
  53820. }
  53821. else {
  53822. callback();
  53823. }
  53824. }, false);
  53825. xhr.addEventListener("error", function (event) {
  53826. BABYLON.Tools.Error("error on XHR request.");
  53827. callback();
  53828. }, false);
  53829. xhr.send();
  53830. }
  53831. else {
  53832. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53833. callback();
  53834. }
  53835. };
  53836. Database.IsUASupportingBlobStorage = true;
  53837. Database.IDBStorageEnabled = true;
  53838. Database.parseURL = function (url) {
  53839. var a = document.createElement('a');
  53840. a.href = url;
  53841. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  53842. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  53843. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  53844. return absLocation;
  53845. };
  53846. Database.ReturnFullUrlLocation = function (url) {
  53847. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  53848. return (Database.parseURL(window.location.href) + url);
  53849. }
  53850. else {
  53851. return url;
  53852. }
  53853. };
  53854. return Database;
  53855. }());
  53856. BABYLON.Database = Database;
  53857. })(BABYLON || (BABYLON = {}));
  53858. //# sourceMappingURL=babylon.database.js.map
  53859. var BABYLON;
  53860. (function (BABYLON) {
  53861. var FresnelParameters = /** @class */ (function () {
  53862. function FresnelParameters() {
  53863. this._isEnabled = true;
  53864. this.leftColor = BABYLON.Color3.White();
  53865. this.rightColor = BABYLON.Color3.Black();
  53866. this.bias = 0;
  53867. this.power = 1;
  53868. }
  53869. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  53870. get: function () {
  53871. return this._isEnabled;
  53872. },
  53873. set: function (value) {
  53874. if (this._isEnabled === value) {
  53875. return;
  53876. }
  53877. this._isEnabled = value;
  53878. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  53879. },
  53880. enumerable: true,
  53881. configurable: true
  53882. });
  53883. FresnelParameters.prototype.clone = function () {
  53884. var newFresnelParameters = new FresnelParameters();
  53885. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  53886. return newFresnelParameters;
  53887. };
  53888. FresnelParameters.prototype.serialize = function () {
  53889. var serializationObject = {};
  53890. serializationObject.isEnabled = this.isEnabled;
  53891. serializationObject.leftColor = this.leftColor;
  53892. serializationObject.rightColor = this.rightColor;
  53893. serializationObject.bias = this.bias;
  53894. serializationObject.power = this.power;
  53895. return serializationObject;
  53896. };
  53897. FresnelParameters.Parse = function (parsedFresnelParameters) {
  53898. var fresnelParameters = new FresnelParameters();
  53899. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  53900. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  53901. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  53902. fresnelParameters.bias = parsedFresnelParameters.bias;
  53903. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  53904. return fresnelParameters;
  53905. };
  53906. return FresnelParameters;
  53907. }());
  53908. BABYLON.FresnelParameters = FresnelParameters;
  53909. })(BABYLON || (BABYLON = {}));
  53910. //# sourceMappingURL=babylon.fresnelParameters.js.map
  53911. var BABYLON;
  53912. (function (BABYLON) {
  53913. var MultiMaterial = /** @class */ (function (_super) {
  53914. __extends(MultiMaterial, _super);
  53915. function MultiMaterial(name, scene) {
  53916. var _this = _super.call(this, name, scene, true) || this;
  53917. scene.multiMaterials.push(_this);
  53918. _this.subMaterials = new Array();
  53919. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  53920. return _this;
  53921. }
  53922. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  53923. get: function () {
  53924. return this._subMaterials;
  53925. },
  53926. set: function (value) {
  53927. this._subMaterials = value;
  53928. this._hookArray(value);
  53929. },
  53930. enumerable: true,
  53931. configurable: true
  53932. });
  53933. MultiMaterial.prototype._hookArray = function (array) {
  53934. var _this = this;
  53935. var oldPush = array.push;
  53936. array.push = function () {
  53937. var items = [];
  53938. for (var _i = 0; _i < arguments.length; _i++) {
  53939. items[_i] = arguments[_i];
  53940. }
  53941. var result = oldPush.apply(array, items);
  53942. _this._markAllSubMeshesAsTexturesDirty();
  53943. return result;
  53944. };
  53945. var oldSplice = array.splice;
  53946. array.splice = function (index, deleteCount) {
  53947. var deleted = oldSplice.apply(array, [index, deleteCount]);
  53948. _this._markAllSubMeshesAsTexturesDirty();
  53949. return deleted;
  53950. };
  53951. };
  53952. // Properties
  53953. MultiMaterial.prototype.getSubMaterial = function (index) {
  53954. if (index < 0 || index >= this.subMaterials.length) {
  53955. return this.getScene().defaultMaterial;
  53956. }
  53957. return this.subMaterials[index];
  53958. };
  53959. MultiMaterial.prototype.getActiveTextures = function () {
  53960. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  53961. if (subMaterial) {
  53962. return subMaterial.getActiveTextures();
  53963. }
  53964. else {
  53965. return [];
  53966. }
  53967. }));
  53968. var _a;
  53969. };
  53970. // Methods
  53971. MultiMaterial.prototype.getClassName = function () {
  53972. return "MultiMaterial";
  53973. };
  53974. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  53975. for (var index = 0; index < this.subMaterials.length; index++) {
  53976. var subMaterial = this.subMaterials[index];
  53977. if (subMaterial) {
  53978. if (subMaterial.storeEffectOnSubMeshes) {
  53979. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  53980. return false;
  53981. }
  53982. continue;
  53983. }
  53984. if (!subMaterial.isReady(mesh)) {
  53985. return false;
  53986. }
  53987. }
  53988. }
  53989. return true;
  53990. };
  53991. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  53992. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  53993. for (var index = 0; index < this.subMaterials.length; index++) {
  53994. var subMaterial = null;
  53995. var current = this.subMaterials[index];
  53996. if (cloneChildren && current) {
  53997. subMaterial = current.clone(name + "-" + current.name);
  53998. }
  53999. else {
  54000. subMaterial = this.subMaterials[index];
  54001. }
  54002. newMultiMaterial.subMaterials.push(subMaterial);
  54003. }
  54004. return newMultiMaterial;
  54005. };
  54006. MultiMaterial.prototype.serialize = function () {
  54007. var serializationObject = {};
  54008. serializationObject.name = this.name;
  54009. serializationObject.id = this.id;
  54010. serializationObject.tags = BABYLON.Tags.GetTags(this);
  54011. serializationObject.materials = [];
  54012. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  54013. var subMat = this.subMaterials[matIndex];
  54014. if (subMat) {
  54015. serializationObject.materials.push(subMat.id);
  54016. }
  54017. else {
  54018. serializationObject.materials.push(null);
  54019. }
  54020. }
  54021. return serializationObject;
  54022. };
  54023. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54024. var scene = this.getScene();
  54025. if (!scene) {
  54026. return;
  54027. }
  54028. var index = scene.multiMaterials.indexOf(this);
  54029. if (index >= 0) {
  54030. scene.multiMaterials.splice(index, 1);
  54031. }
  54032. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54033. };
  54034. return MultiMaterial;
  54035. }(BABYLON.Material));
  54036. BABYLON.MultiMaterial = MultiMaterial;
  54037. })(BABYLON || (BABYLON = {}));
  54038. //# sourceMappingURL=babylon.multiMaterial.js.map
  54039. var BABYLON;
  54040. (function (BABYLON) {
  54041. var FreeCameraTouchInput = /** @class */ (function () {
  54042. function FreeCameraTouchInput() {
  54043. this._offsetX = null;
  54044. this._offsetY = null;
  54045. this._pointerCount = 0;
  54046. this._pointerPressed = new Array();
  54047. this.touchAngularSensibility = 200000.0;
  54048. this.touchMoveSensibility = 250.0;
  54049. }
  54050. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  54051. var _this = this;
  54052. var previousPosition = null;
  54053. if (this._pointerInput === undefined) {
  54054. this._onLostFocus = function (evt) {
  54055. _this._offsetX = null;
  54056. _this._offsetY = null;
  54057. };
  54058. this._pointerInput = function (p, s) {
  54059. var evt = p.event;
  54060. if (evt.pointerType === "mouse") {
  54061. return;
  54062. }
  54063. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  54064. if (!noPreventDefault) {
  54065. evt.preventDefault();
  54066. }
  54067. _this._pointerPressed.push(evt.pointerId);
  54068. if (_this._pointerPressed.length !== 1) {
  54069. return;
  54070. }
  54071. previousPosition = {
  54072. x: evt.clientX,
  54073. y: evt.clientY
  54074. };
  54075. }
  54076. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  54077. if (!noPreventDefault) {
  54078. evt.preventDefault();
  54079. }
  54080. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54081. if (index === -1) {
  54082. return;
  54083. }
  54084. _this._pointerPressed.splice(index, 1);
  54085. if (index != 0) {
  54086. return;
  54087. }
  54088. previousPosition = null;
  54089. _this._offsetX = null;
  54090. _this._offsetY = null;
  54091. }
  54092. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  54093. if (!noPreventDefault) {
  54094. evt.preventDefault();
  54095. }
  54096. if (!previousPosition) {
  54097. return;
  54098. }
  54099. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54100. if (index != 0) {
  54101. return;
  54102. }
  54103. _this._offsetX = evt.clientX - previousPosition.x;
  54104. _this._offsetY = -(evt.clientY - previousPosition.y);
  54105. }
  54106. };
  54107. }
  54108. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  54109. if (this._onLostFocus) {
  54110. element.addEventListener("blur", this._onLostFocus);
  54111. }
  54112. };
  54113. FreeCameraTouchInput.prototype.detachControl = function (element) {
  54114. if (this._pointerInput && element) {
  54115. if (this._observer) {
  54116. this.camera.getScene().onPointerObservable.remove(this._observer);
  54117. this._observer = null;
  54118. }
  54119. if (this._onLostFocus) {
  54120. element.removeEventListener("blur", this._onLostFocus);
  54121. this._onLostFocus = null;
  54122. }
  54123. this._pointerPressed = [];
  54124. this._offsetX = null;
  54125. this._offsetY = null;
  54126. this._pointerCount = 0;
  54127. }
  54128. };
  54129. FreeCameraTouchInput.prototype.checkInputs = function () {
  54130. if (this._offsetX && this._offsetY) {
  54131. var camera = this.camera;
  54132. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  54133. if (this._pointerPressed.length > 1) {
  54134. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  54135. }
  54136. else {
  54137. var speed = camera._computeLocalCameraSpeed();
  54138. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  54139. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  54140. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  54141. }
  54142. }
  54143. };
  54144. FreeCameraTouchInput.prototype.getClassName = function () {
  54145. return "FreeCameraTouchInput";
  54146. };
  54147. FreeCameraTouchInput.prototype.getSimpleName = function () {
  54148. return "touch";
  54149. };
  54150. __decorate([
  54151. BABYLON.serialize()
  54152. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  54153. __decorate([
  54154. BABYLON.serialize()
  54155. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  54156. return FreeCameraTouchInput;
  54157. }());
  54158. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  54159. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54160. })(BABYLON || (BABYLON = {}));
  54161. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54162. var BABYLON;
  54163. (function (BABYLON) {
  54164. // We're mainly based on the logic defined into the FreeCamera code
  54165. var TouchCamera = /** @class */ (function (_super) {
  54166. __extends(TouchCamera, _super);
  54167. //-- end properties for backward compatibility for inputs
  54168. function TouchCamera(name, position, scene) {
  54169. var _this = _super.call(this, name, position, scene) || this;
  54170. _this.inputs.addTouch();
  54171. _this._setupInputs();
  54172. return _this;
  54173. }
  54174. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54175. //-- Begin properties for backward compatibility for inputs
  54176. get: function () {
  54177. var touch = this.inputs.attached["touch"];
  54178. if (touch)
  54179. return touch.touchAngularSensibility;
  54180. return 0;
  54181. },
  54182. set: function (value) {
  54183. var touch = this.inputs.attached["touch"];
  54184. if (touch)
  54185. touch.touchAngularSensibility = value;
  54186. },
  54187. enumerable: true,
  54188. configurable: true
  54189. });
  54190. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54191. get: function () {
  54192. var touch = this.inputs.attached["touch"];
  54193. if (touch)
  54194. return touch.touchMoveSensibility;
  54195. return 0;
  54196. },
  54197. set: function (value) {
  54198. var touch = this.inputs.attached["touch"];
  54199. if (touch)
  54200. touch.touchMoveSensibility = value;
  54201. },
  54202. enumerable: true,
  54203. configurable: true
  54204. });
  54205. TouchCamera.prototype.getClassName = function () {
  54206. return "TouchCamera";
  54207. };
  54208. TouchCamera.prototype._setupInputs = function () {
  54209. var mouse = this.inputs.attached["mouse"];
  54210. if (mouse) {
  54211. mouse.touchEnabled = false;
  54212. }
  54213. };
  54214. return TouchCamera;
  54215. }(BABYLON.FreeCamera));
  54216. BABYLON.TouchCamera = TouchCamera;
  54217. })(BABYLON || (BABYLON = {}));
  54218. //# sourceMappingURL=babylon.touchCamera.js.map
  54219. var BABYLON;
  54220. (function (BABYLON) {
  54221. var ProceduralTexture = /** @class */ (function (_super) {
  54222. __extends(ProceduralTexture, _super);
  54223. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  54224. if (fallbackTexture === void 0) { fallbackTexture = null; }
  54225. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54226. if (isCube === void 0) { isCube = false; }
  54227. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54228. _this.isCube = isCube;
  54229. _this.isEnabled = true;
  54230. _this._currentRefreshId = -1;
  54231. _this._refreshRate = 1;
  54232. _this._vertexBuffers = {};
  54233. _this._uniforms = new Array();
  54234. _this._samplers = new Array();
  54235. _this._textures = {};
  54236. _this._floats = {};
  54237. _this._floatsArrays = {};
  54238. _this._colors3 = {};
  54239. _this._colors4 = {};
  54240. _this._vectors2 = {};
  54241. _this._vectors3 = {};
  54242. _this._matrices = {};
  54243. _this._fallbackTextureUsed = false;
  54244. scene._proceduralTextures.push(_this);
  54245. _this._engine = scene.getEngine();
  54246. _this.name = name;
  54247. _this.isRenderTarget = true;
  54248. _this._size = size;
  54249. _this._generateMipMaps = generateMipMaps;
  54250. _this.setFragment(fragment);
  54251. _this._fallbackTexture = fallbackTexture;
  54252. if (isCube) {
  54253. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  54254. _this.setFloat("face", 0);
  54255. }
  54256. else {
  54257. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  54258. }
  54259. // VBO
  54260. var vertices = [];
  54261. vertices.push(1, 1);
  54262. vertices.push(-1, 1);
  54263. vertices.push(-1, -1);
  54264. vertices.push(1, -1);
  54265. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54266. _this._createIndexBuffer();
  54267. return _this;
  54268. }
  54269. ProceduralTexture.prototype._createIndexBuffer = function () {
  54270. var engine = this._engine;
  54271. // Indices
  54272. var indices = [];
  54273. indices.push(0);
  54274. indices.push(1);
  54275. indices.push(2);
  54276. indices.push(0);
  54277. indices.push(2);
  54278. indices.push(3);
  54279. this._indexBuffer = engine.createIndexBuffer(indices);
  54280. };
  54281. ProceduralTexture.prototype._rebuild = function () {
  54282. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54283. if (vb) {
  54284. vb._rebuild();
  54285. }
  54286. this._createIndexBuffer();
  54287. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54288. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54289. }
  54290. };
  54291. ProceduralTexture.prototype.reset = function () {
  54292. if (this._effect === undefined) {
  54293. return;
  54294. }
  54295. var engine = this._engine;
  54296. engine._releaseEffect(this._effect);
  54297. };
  54298. ProceduralTexture.prototype.isReady = function () {
  54299. var _this = this;
  54300. var engine = this._engine;
  54301. var shaders;
  54302. if (!this._fragment) {
  54303. return false;
  54304. }
  54305. if (this._fallbackTextureUsed) {
  54306. return true;
  54307. }
  54308. if (this._fragment.fragmentElement !== undefined) {
  54309. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  54310. }
  54311. else {
  54312. shaders = { vertex: "procedural", fragment: this._fragment };
  54313. }
  54314. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  54315. _this.releaseInternalTexture();
  54316. if (_this._fallbackTexture) {
  54317. _this._texture = _this._fallbackTexture._texture;
  54318. if (_this._texture) {
  54319. _this._texture.incrementReferences();
  54320. }
  54321. }
  54322. _this._fallbackTextureUsed = true;
  54323. });
  54324. return this._effect.isReady();
  54325. };
  54326. ProceduralTexture.prototype.resetRefreshCounter = function () {
  54327. this._currentRefreshId = -1;
  54328. };
  54329. ProceduralTexture.prototype.setFragment = function (fragment) {
  54330. this._fragment = fragment;
  54331. };
  54332. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  54333. get: function () {
  54334. return this._refreshRate;
  54335. },
  54336. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54337. set: function (value) {
  54338. this._refreshRate = value;
  54339. this.resetRefreshCounter();
  54340. },
  54341. enumerable: true,
  54342. configurable: true
  54343. });
  54344. ProceduralTexture.prototype._shouldRender = function () {
  54345. if (!this.isEnabled || !this.isReady() || !this._texture) {
  54346. return false;
  54347. }
  54348. if (this._fallbackTextureUsed) {
  54349. return false;
  54350. }
  54351. if (this._currentRefreshId === -1) {
  54352. this._currentRefreshId = 1;
  54353. return true;
  54354. }
  54355. if (this.refreshRate === this._currentRefreshId) {
  54356. this._currentRefreshId = 1;
  54357. return true;
  54358. }
  54359. this._currentRefreshId++;
  54360. return false;
  54361. };
  54362. ProceduralTexture.prototype.getRenderSize = function () {
  54363. return this._size;
  54364. };
  54365. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  54366. if (this._fallbackTextureUsed) {
  54367. return;
  54368. }
  54369. this.releaseInternalTexture();
  54370. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  54371. };
  54372. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  54373. if (this._uniforms.indexOf(uniformName) === -1) {
  54374. this._uniforms.push(uniformName);
  54375. }
  54376. };
  54377. ProceduralTexture.prototype.setTexture = function (name, texture) {
  54378. if (this._samplers.indexOf(name) === -1) {
  54379. this._samplers.push(name);
  54380. }
  54381. this._textures[name] = texture;
  54382. return this;
  54383. };
  54384. ProceduralTexture.prototype.setFloat = function (name, value) {
  54385. this._checkUniform(name);
  54386. this._floats[name] = value;
  54387. return this;
  54388. };
  54389. ProceduralTexture.prototype.setFloats = function (name, value) {
  54390. this._checkUniform(name);
  54391. this._floatsArrays[name] = value;
  54392. return this;
  54393. };
  54394. ProceduralTexture.prototype.setColor3 = function (name, value) {
  54395. this._checkUniform(name);
  54396. this._colors3[name] = value;
  54397. return this;
  54398. };
  54399. ProceduralTexture.prototype.setColor4 = function (name, value) {
  54400. this._checkUniform(name);
  54401. this._colors4[name] = value;
  54402. return this;
  54403. };
  54404. ProceduralTexture.prototype.setVector2 = function (name, value) {
  54405. this._checkUniform(name);
  54406. this._vectors2[name] = value;
  54407. return this;
  54408. };
  54409. ProceduralTexture.prototype.setVector3 = function (name, value) {
  54410. this._checkUniform(name);
  54411. this._vectors3[name] = value;
  54412. return this;
  54413. };
  54414. ProceduralTexture.prototype.setMatrix = function (name, value) {
  54415. this._checkUniform(name);
  54416. this._matrices[name] = value;
  54417. return this;
  54418. };
  54419. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54420. var scene = this.getScene();
  54421. if (!scene) {
  54422. return;
  54423. }
  54424. var engine = this._engine;
  54425. // Render
  54426. engine.enableEffect(this._effect);
  54427. engine.setState(false);
  54428. // Texture
  54429. for (var name in this._textures) {
  54430. this._effect.setTexture(name, this._textures[name]);
  54431. }
  54432. // Float
  54433. for (name in this._floats) {
  54434. this._effect.setFloat(name, this._floats[name]);
  54435. }
  54436. // Floats
  54437. for (name in this._floatsArrays) {
  54438. this._effect.setArray(name, this._floatsArrays[name]);
  54439. }
  54440. // Color3
  54441. for (name in this._colors3) {
  54442. this._effect.setColor3(name, this._colors3[name]);
  54443. }
  54444. // Color4
  54445. for (name in this._colors4) {
  54446. var color = this._colors4[name];
  54447. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54448. }
  54449. // Vector2
  54450. for (name in this._vectors2) {
  54451. this._effect.setVector2(name, this._vectors2[name]);
  54452. }
  54453. // Vector3
  54454. for (name in this._vectors3) {
  54455. this._effect.setVector3(name, this._vectors3[name]);
  54456. }
  54457. // Matrix
  54458. for (name in this._matrices) {
  54459. this._effect.setMatrix(name, this._matrices[name]);
  54460. }
  54461. if (!this._texture) {
  54462. return;
  54463. }
  54464. if (this.isCube) {
  54465. for (var face = 0; face < 6; face++) {
  54466. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  54467. // VBOs
  54468. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54469. this._effect.setFloat("face", face);
  54470. // Clear
  54471. engine.clear(scene.clearColor, true, true, true);
  54472. // Draw order
  54473. engine.draw(true, 0, 6);
  54474. // Mipmaps
  54475. if (face === 5) {
  54476. engine.generateMipMapsForCubemap(this._texture);
  54477. }
  54478. }
  54479. }
  54480. else {
  54481. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  54482. // VBOs
  54483. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54484. // Clear
  54485. engine.clear(scene.clearColor, true, true, true);
  54486. // Draw order
  54487. engine.draw(true, 0, 6);
  54488. }
  54489. // Unbind
  54490. engine.unBindFramebuffer(this._texture, this.isCube);
  54491. if (this.onGenerated) {
  54492. this.onGenerated();
  54493. }
  54494. };
  54495. ProceduralTexture.prototype.clone = function () {
  54496. var textureSize = this.getSize();
  54497. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  54498. // Base texture
  54499. newTexture.hasAlpha = this.hasAlpha;
  54500. newTexture.level = this.level;
  54501. // RenderTarget Texture
  54502. newTexture.coordinatesMode = this.coordinatesMode;
  54503. return newTexture;
  54504. };
  54505. ProceduralTexture.prototype.dispose = function () {
  54506. var scene = this.getScene();
  54507. if (!scene) {
  54508. return;
  54509. }
  54510. var index = scene._proceduralTextures.indexOf(this);
  54511. if (index >= 0) {
  54512. scene._proceduralTextures.splice(index, 1);
  54513. }
  54514. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54515. if (vertexBuffer) {
  54516. vertexBuffer.dispose();
  54517. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54518. }
  54519. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  54520. this._indexBuffer = null;
  54521. }
  54522. _super.prototype.dispose.call(this);
  54523. };
  54524. return ProceduralTexture;
  54525. }(BABYLON.Texture));
  54526. BABYLON.ProceduralTexture = ProceduralTexture;
  54527. })(BABYLON || (BABYLON = {}));
  54528. //# sourceMappingURL=babylon.proceduralTexture.js.map
  54529. var BABYLON;
  54530. (function (BABYLON) {
  54531. var CustomProceduralTexture = /** @class */ (function (_super) {
  54532. __extends(CustomProceduralTexture, _super);
  54533. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  54534. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  54535. _this._animate = true;
  54536. _this._time = 0;
  54537. _this._texturePath = texturePath;
  54538. //Try to load json
  54539. _this.loadJson(texturePath);
  54540. _this.refreshRate = 1;
  54541. return _this;
  54542. }
  54543. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  54544. var _this = this;
  54545. var noConfigFile = function () {
  54546. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  54547. try {
  54548. _this.setFragment(_this._texturePath);
  54549. }
  54550. catch (ex) {
  54551. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  54552. }
  54553. };
  54554. var configFileUrl = jsonUrl + "/config.json";
  54555. var xhr = new XMLHttpRequest();
  54556. xhr.open("GET", configFileUrl, true);
  54557. xhr.addEventListener("load", function () {
  54558. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54559. try {
  54560. _this._config = JSON.parse(xhr.response);
  54561. _this.updateShaderUniforms();
  54562. _this.updateTextures();
  54563. _this.setFragment(_this._texturePath + "/custom");
  54564. _this._animate = _this._config.animate;
  54565. _this.refreshRate = _this._config.refreshrate;
  54566. }
  54567. catch (ex) {
  54568. noConfigFile();
  54569. }
  54570. }
  54571. else {
  54572. noConfigFile();
  54573. }
  54574. }, false);
  54575. xhr.addEventListener("error", function () {
  54576. noConfigFile();
  54577. }, false);
  54578. try {
  54579. xhr.send();
  54580. }
  54581. catch (ex) {
  54582. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  54583. }
  54584. };
  54585. CustomProceduralTexture.prototype.isReady = function () {
  54586. if (!_super.prototype.isReady.call(this)) {
  54587. return false;
  54588. }
  54589. for (var name in this._textures) {
  54590. var texture = this._textures[name];
  54591. if (!texture.isReady()) {
  54592. return false;
  54593. }
  54594. }
  54595. return true;
  54596. };
  54597. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54598. var scene = this.getScene();
  54599. if (this._animate && scene) {
  54600. this._time += scene.getAnimationRatio() * 0.03;
  54601. this.updateShaderUniforms();
  54602. }
  54603. _super.prototype.render.call(this, useCameraPostProcess);
  54604. };
  54605. CustomProceduralTexture.prototype.updateTextures = function () {
  54606. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  54607. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  54608. }
  54609. };
  54610. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  54611. if (this._config) {
  54612. for (var j = 0; j < this._config.uniforms.length; j++) {
  54613. var uniform = this._config.uniforms[j];
  54614. switch (uniform.type) {
  54615. case "float":
  54616. this.setFloat(uniform.name, uniform.value);
  54617. break;
  54618. case "color3":
  54619. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  54620. break;
  54621. case "color4":
  54622. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  54623. break;
  54624. case "vector2":
  54625. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  54626. break;
  54627. case "vector3":
  54628. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  54629. break;
  54630. }
  54631. }
  54632. }
  54633. this.setFloat("time", this._time);
  54634. };
  54635. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  54636. get: function () {
  54637. return this._animate;
  54638. },
  54639. set: function (value) {
  54640. this._animate = value;
  54641. },
  54642. enumerable: true,
  54643. configurable: true
  54644. });
  54645. return CustomProceduralTexture;
  54646. }(BABYLON.ProceduralTexture));
  54647. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  54648. })(BABYLON || (BABYLON = {}));
  54649. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  54650. var BABYLON;
  54651. (function (BABYLON) {
  54652. var FreeCameraGamepadInput = /** @class */ (function () {
  54653. function FreeCameraGamepadInput() {
  54654. this.gamepadAngularSensibility = 200;
  54655. this.gamepadMoveSensibility = 40;
  54656. // private members
  54657. this._cameraTransform = BABYLON.Matrix.Identity();
  54658. this._deltaTransform = BABYLON.Vector3.Zero();
  54659. this._vector3 = BABYLON.Vector3.Zero();
  54660. this._vector2 = BABYLON.Vector2.Zero();
  54661. }
  54662. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54663. var _this = this;
  54664. var manager = this.camera.getScene().gamepadManager;
  54665. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54666. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54667. // prioritize XBOX gamepads.
  54668. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54669. _this.gamepad = gamepad;
  54670. }
  54671. }
  54672. });
  54673. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54674. if (_this.gamepad === gamepad) {
  54675. _this.gamepad = null;
  54676. }
  54677. });
  54678. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54679. };
  54680. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  54681. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54682. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54683. this.gamepad = null;
  54684. };
  54685. FreeCameraGamepadInput.prototype.checkInputs = function () {
  54686. if (this.gamepad && this.gamepad.leftStick) {
  54687. var camera = this.camera;
  54688. var LSValues = this.gamepad.leftStick;
  54689. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  54690. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54691. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  54692. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  54693. var RSValues = this.gamepad.rightStick;
  54694. if (RSValues) {
  54695. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  54696. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  54697. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  54698. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  54699. }
  54700. else {
  54701. RSValues = { x: 0, y: 0 };
  54702. }
  54703. if (!camera.rotationQuaternion) {
  54704. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  54705. }
  54706. else {
  54707. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  54708. }
  54709. var speed = camera._computeLocalCameraSpeed() * 50.0;
  54710. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  54711. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  54712. camera.cameraDirection.addInPlace(this._deltaTransform);
  54713. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  54714. camera.cameraRotation.addInPlace(this._vector2);
  54715. }
  54716. };
  54717. FreeCameraGamepadInput.prototype.getClassName = function () {
  54718. return "FreeCameraGamepadInput";
  54719. };
  54720. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  54721. return "gamepad";
  54722. };
  54723. __decorate([
  54724. BABYLON.serialize()
  54725. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  54726. __decorate([
  54727. BABYLON.serialize()
  54728. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54729. return FreeCameraGamepadInput;
  54730. }());
  54731. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  54732. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  54733. })(BABYLON || (BABYLON = {}));
  54734. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  54735. var BABYLON;
  54736. (function (BABYLON) {
  54737. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  54738. function ArcRotateCameraGamepadInput() {
  54739. this.gamepadRotationSensibility = 80;
  54740. this.gamepadMoveSensibility = 40;
  54741. }
  54742. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54743. var _this = this;
  54744. var manager = this.camera.getScene().gamepadManager;
  54745. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54746. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54747. // prioritize XBOX gamepads.
  54748. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54749. _this.gamepad = gamepad;
  54750. }
  54751. }
  54752. });
  54753. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54754. if (_this.gamepad === gamepad) {
  54755. _this.gamepad = null;
  54756. }
  54757. });
  54758. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54759. };
  54760. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  54761. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54762. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54763. this.gamepad = null;
  54764. };
  54765. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  54766. if (this.gamepad) {
  54767. var camera = this.camera;
  54768. var RSValues = this.gamepad.rightStick;
  54769. if (RSValues) {
  54770. if (RSValues.x != 0) {
  54771. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  54772. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  54773. camera.inertialAlphaOffset += normalizedRX;
  54774. }
  54775. }
  54776. if (RSValues.y != 0) {
  54777. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  54778. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  54779. camera.inertialBetaOffset += normalizedRY;
  54780. }
  54781. }
  54782. }
  54783. var LSValues = this.gamepad.leftStick;
  54784. if (LSValues && LSValues.y != 0) {
  54785. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54786. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  54787. this.camera.inertialRadiusOffset -= normalizedLY;
  54788. }
  54789. }
  54790. }
  54791. };
  54792. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  54793. return "ArcRotateCameraGamepadInput";
  54794. };
  54795. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  54796. return "gamepad";
  54797. };
  54798. __decorate([
  54799. BABYLON.serialize()
  54800. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  54801. __decorate([
  54802. BABYLON.serialize()
  54803. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54804. return ArcRotateCameraGamepadInput;
  54805. }());
  54806. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  54807. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  54808. })(BABYLON || (BABYLON = {}));
  54809. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  54810. var BABYLON;
  54811. (function (BABYLON) {
  54812. var GamepadManager = /** @class */ (function () {
  54813. function GamepadManager() {
  54814. var _this = this;
  54815. this._babylonGamepads = [];
  54816. this._oneGamepadConnected = false;
  54817. this._isMonitoring = false;
  54818. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  54819. if (!BABYLON.Tools.IsWindowObjectExist()) {
  54820. this._gamepadEventSupported = false;
  54821. }
  54822. else {
  54823. this._gamepadEventSupported = 'GamepadEvent' in window;
  54824. this._gamepadSupport = (navigator.getGamepads ||
  54825. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  54826. }
  54827. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  54828. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  54829. for (var i in _this._babylonGamepads) {
  54830. var gamepad = _this._babylonGamepads[i];
  54831. if (gamepad && gamepad._isConnected) {
  54832. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  54833. }
  54834. }
  54835. });
  54836. this._onGamepadConnectedEvent = function (evt) {
  54837. var gamepad = evt.gamepad;
  54838. if (gamepad.index in _this._babylonGamepads) {
  54839. if (_this._babylonGamepads[gamepad.index].isConnected) {
  54840. return;
  54841. }
  54842. }
  54843. var newGamepad;
  54844. if (_this._babylonGamepads[gamepad.index]) {
  54845. newGamepad = _this._babylonGamepads[gamepad.index];
  54846. newGamepad.browserGamepad = gamepad;
  54847. newGamepad._isConnected = true;
  54848. }
  54849. else {
  54850. newGamepad = _this._addNewGamepad(gamepad);
  54851. }
  54852. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54853. _this._startMonitoringGamepads();
  54854. };
  54855. this._onGamepadDisconnectedEvent = function (evt) {
  54856. var gamepad = evt.gamepad;
  54857. // Remove the gamepad from the list of gamepads to monitor.
  54858. for (var i in _this._babylonGamepads) {
  54859. if (_this._babylonGamepads[i].index === gamepad.index) {
  54860. var disconnectedGamepad = _this._babylonGamepads[i];
  54861. disconnectedGamepad._isConnected = false;
  54862. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  54863. break;
  54864. }
  54865. }
  54866. };
  54867. if (this._gamepadSupport) {
  54868. //first add already-connected gamepads
  54869. this._updateGamepadObjects();
  54870. if (this._babylonGamepads.length) {
  54871. this._startMonitoringGamepads();
  54872. }
  54873. // Checking if the gamepad connected event is supported (like in Firefox)
  54874. if (this._gamepadEventSupported) {
  54875. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54876. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  54877. }
  54878. else {
  54879. this._startMonitoringGamepads();
  54880. }
  54881. }
  54882. }
  54883. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  54884. get: function () {
  54885. return this._babylonGamepads;
  54886. },
  54887. enumerable: true,
  54888. configurable: true
  54889. });
  54890. GamepadManager.prototype.getGamepadByType = function (type) {
  54891. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  54892. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  54893. var gamepad = _a[_i];
  54894. if (gamepad && gamepad.type === type) {
  54895. return gamepad;
  54896. }
  54897. }
  54898. return null;
  54899. };
  54900. GamepadManager.prototype.dispose = function () {
  54901. if (this._gamepadEventSupported) {
  54902. if (this._onGamepadConnectedEvent) {
  54903. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  54904. }
  54905. if (this._onGamepadDisconnectedEvent) {
  54906. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  54907. }
  54908. this._onGamepadConnectedEvent = null;
  54909. this._onGamepadDisconnectedEvent = null;
  54910. }
  54911. this._babylonGamepads.forEach(function (gamepad) {
  54912. gamepad.dispose();
  54913. });
  54914. this.onGamepadConnectedObservable.clear();
  54915. this.onGamepadDisconnectedObservable.clear();
  54916. this._oneGamepadConnected = false;
  54917. this._stopMonitoringGamepads();
  54918. this._babylonGamepads = [];
  54919. };
  54920. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  54921. if (!this._oneGamepadConnected) {
  54922. this._oneGamepadConnected = true;
  54923. }
  54924. var newGamepad;
  54925. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  54926. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54927. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  54928. }
  54929. else if (gamepad.pose) {
  54930. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  54931. }
  54932. else {
  54933. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  54934. }
  54935. this._babylonGamepads[newGamepad.index] = newGamepad;
  54936. return newGamepad;
  54937. };
  54938. GamepadManager.prototype._startMonitoringGamepads = function () {
  54939. if (!this._isMonitoring) {
  54940. this._isMonitoring = true;
  54941. this._checkGamepadsStatus();
  54942. }
  54943. };
  54944. GamepadManager.prototype._stopMonitoringGamepads = function () {
  54945. this._isMonitoring = false;
  54946. };
  54947. GamepadManager.prototype._checkGamepadsStatus = function () {
  54948. var _this = this;
  54949. // Hack to be compatible Chrome
  54950. this._updateGamepadObjects();
  54951. for (var i in this._babylonGamepads) {
  54952. var gamepad = this._babylonGamepads[i];
  54953. if (!gamepad || !gamepad.isConnected) {
  54954. continue;
  54955. }
  54956. gamepad.update();
  54957. }
  54958. if (this._isMonitoring) {
  54959. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  54960. }
  54961. };
  54962. // This function is called only on Chrome, which does not properly support
  54963. // connection/disconnection events and forces you to recopy again the gamepad object
  54964. GamepadManager.prototype._updateGamepadObjects = function () {
  54965. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54966. for (var i = 0; i < gamepads.length; i++) {
  54967. if (gamepads[i]) {
  54968. if (!this._babylonGamepads[gamepads[i].index]) {
  54969. var newGamepad = this._addNewGamepad(gamepads[i]);
  54970. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54971. }
  54972. else {
  54973. // Forced to copy again this object for Chrome for unknown reason
  54974. this._babylonGamepads[i].browserGamepad = gamepads[i];
  54975. if (!this._babylonGamepads[i].isConnected) {
  54976. this._babylonGamepads[i]._isConnected = true;
  54977. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  54978. }
  54979. }
  54980. }
  54981. }
  54982. };
  54983. return GamepadManager;
  54984. }());
  54985. BABYLON.GamepadManager = GamepadManager;
  54986. })(BABYLON || (BABYLON = {}));
  54987. //# sourceMappingURL=babylon.gamepadManager.js.map
  54988. var BABYLON;
  54989. (function (BABYLON) {
  54990. var StickValues = /** @class */ (function () {
  54991. function StickValues(x, y) {
  54992. this.x = x;
  54993. this.y = y;
  54994. }
  54995. return StickValues;
  54996. }());
  54997. BABYLON.StickValues = StickValues;
  54998. var Gamepad = /** @class */ (function () {
  54999. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  55000. if (leftStickX === void 0) { leftStickX = 0; }
  55001. if (leftStickY === void 0) { leftStickY = 1; }
  55002. if (rightStickX === void 0) { rightStickX = 2; }
  55003. if (rightStickY === void 0) { rightStickY = 3; }
  55004. this.id = id;
  55005. this.index = index;
  55006. this.browserGamepad = browserGamepad;
  55007. this._isConnected = true;
  55008. this.type = Gamepad.GAMEPAD;
  55009. this._leftStickAxisX = leftStickX;
  55010. this._leftStickAxisY = leftStickY;
  55011. this._rightStickAxisX = rightStickX;
  55012. this._rightStickAxisY = rightStickY;
  55013. if (this.browserGamepad.axes.length >= 2) {
  55014. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55015. }
  55016. if (this.browserGamepad.axes.length >= 4) {
  55017. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55018. }
  55019. }
  55020. Object.defineProperty(Gamepad.prototype, "isConnected", {
  55021. get: function () {
  55022. return this._isConnected;
  55023. },
  55024. enumerable: true,
  55025. configurable: true
  55026. });
  55027. Gamepad.prototype.onleftstickchanged = function (callback) {
  55028. this._onleftstickchanged = callback;
  55029. };
  55030. Gamepad.prototype.onrightstickchanged = function (callback) {
  55031. this._onrightstickchanged = callback;
  55032. };
  55033. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55034. get: function () {
  55035. return this._leftStick;
  55036. },
  55037. set: function (newValues) {
  55038. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55039. this._onleftstickchanged(newValues);
  55040. }
  55041. this._leftStick = newValues;
  55042. },
  55043. enumerable: true,
  55044. configurable: true
  55045. });
  55046. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55047. get: function () {
  55048. return this._rightStick;
  55049. },
  55050. set: function (newValues) {
  55051. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55052. this._onrightstickchanged(newValues);
  55053. }
  55054. this._rightStick = newValues;
  55055. },
  55056. enumerable: true,
  55057. configurable: true
  55058. });
  55059. Gamepad.prototype.update = function () {
  55060. if (this._leftStick) {
  55061. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55062. }
  55063. if (this._rightStick) {
  55064. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55065. }
  55066. };
  55067. Gamepad.prototype.dispose = function () {
  55068. };
  55069. Gamepad.GAMEPAD = 0;
  55070. Gamepad.GENERIC = 1;
  55071. Gamepad.XBOX = 2;
  55072. Gamepad.POSE_ENABLED = 3;
  55073. return Gamepad;
  55074. }());
  55075. BABYLON.Gamepad = Gamepad;
  55076. var GenericPad = /** @class */ (function (_super) {
  55077. __extends(GenericPad, _super);
  55078. function GenericPad(id, index, browserGamepad) {
  55079. var _this = _super.call(this, id, index, browserGamepad) || this;
  55080. _this.onButtonDownObservable = new BABYLON.Observable();
  55081. _this.onButtonUpObservable = new BABYLON.Observable();
  55082. _this.type = Gamepad.GENERIC;
  55083. _this._buttons = new Array(browserGamepad.buttons.length);
  55084. return _this;
  55085. }
  55086. GenericPad.prototype.onbuttondown = function (callback) {
  55087. this._onbuttondown = callback;
  55088. };
  55089. GenericPad.prototype.onbuttonup = function (callback) {
  55090. this._onbuttonup = callback;
  55091. };
  55092. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55093. if (newValue !== currentValue) {
  55094. if (newValue === 1) {
  55095. if (this._onbuttondown) {
  55096. this._onbuttondown(buttonIndex);
  55097. }
  55098. this.onButtonDownObservable.notifyObservers(buttonIndex);
  55099. }
  55100. if (newValue === 0) {
  55101. if (this._onbuttonup) {
  55102. this._onbuttonup(buttonIndex);
  55103. }
  55104. this.onButtonUpObservable.notifyObservers(buttonIndex);
  55105. }
  55106. }
  55107. return newValue;
  55108. };
  55109. GenericPad.prototype.update = function () {
  55110. _super.prototype.update.call(this);
  55111. for (var index = 0; index < this._buttons.length; index++) {
  55112. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  55113. }
  55114. };
  55115. return GenericPad;
  55116. }(Gamepad));
  55117. BABYLON.GenericPad = GenericPad;
  55118. })(BABYLON || (BABYLON = {}));
  55119. //# sourceMappingURL=babylon.gamepad.js.map
  55120. var BABYLON;
  55121. (function (BABYLON) {
  55122. var Xbox360Button;
  55123. (function (Xbox360Button) {
  55124. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55125. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55126. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55127. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55128. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55129. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55130. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55131. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55132. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55133. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55134. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55135. var Xbox360Dpad;
  55136. (function (Xbox360Dpad) {
  55137. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55138. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55139. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55140. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55141. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55142. var Xbox360Pad = /** @class */ (function (_super) {
  55143. __extends(Xbox360Pad, _super);
  55144. function Xbox360Pad(id, index, gamepad, xboxOne) {
  55145. if (xboxOne === void 0) { xboxOne = false; }
  55146. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  55147. _this._leftTrigger = 0;
  55148. _this._rightTrigger = 0;
  55149. _this.onButtonDownObservable = new BABYLON.Observable();
  55150. _this.onButtonUpObservable = new BABYLON.Observable();
  55151. _this.onPadDownObservable = new BABYLON.Observable();
  55152. _this.onPadUpObservable = new BABYLON.Observable();
  55153. _this._buttonA = 0;
  55154. _this._buttonB = 0;
  55155. _this._buttonX = 0;
  55156. _this._buttonY = 0;
  55157. _this._buttonBack = 0;
  55158. _this._buttonStart = 0;
  55159. _this._buttonLB = 0;
  55160. _this._buttonRB = 0;
  55161. _this._buttonLeftStick = 0;
  55162. _this._buttonRightStick = 0;
  55163. _this._dPadUp = 0;
  55164. _this._dPadDown = 0;
  55165. _this._dPadLeft = 0;
  55166. _this._dPadRight = 0;
  55167. _this._isXboxOnePad = false;
  55168. _this.type = BABYLON.Gamepad.XBOX;
  55169. _this._isXboxOnePad = xboxOne;
  55170. return _this;
  55171. }
  55172. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55173. this._onlefttriggerchanged = callback;
  55174. };
  55175. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55176. this._onrighttriggerchanged = callback;
  55177. };
  55178. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55179. get: function () {
  55180. return this._leftTrigger;
  55181. },
  55182. set: function (newValue) {
  55183. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55184. this._onlefttriggerchanged(newValue);
  55185. }
  55186. this._leftTrigger = newValue;
  55187. },
  55188. enumerable: true,
  55189. configurable: true
  55190. });
  55191. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55192. get: function () {
  55193. return this._rightTrigger;
  55194. },
  55195. set: function (newValue) {
  55196. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55197. this._onrighttriggerchanged(newValue);
  55198. }
  55199. this._rightTrigger = newValue;
  55200. },
  55201. enumerable: true,
  55202. configurable: true
  55203. });
  55204. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55205. this._onbuttondown = callback;
  55206. };
  55207. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55208. this._onbuttonup = callback;
  55209. };
  55210. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55211. this._ondpaddown = callback;
  55212. };
  55213. Xbox360Pad.prototype.ondpadup = function (callback) {
  55214. this._ondpadup = callback;
  55215. };
  55216. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55217. if (newValue !== currentValue) {
  55218. if (newValue === 1) {
  55219. if (this._onbuttondown) {
  55220. this._onbuttondown(buttonType);
  55221. }
  55222. this.onButtonDownObservable.notifyObservers(buttonType);
  55223. }
  55224. if (newValue === 0) {
  55225. if (this._onbuttonup) {
  55226. this._onbuttonup(buttonType);
  55227. }
  55228. this.onButtonUpObservable.notifyObservers(buttonType);
  55229. }
  55230. }
  55231. return newValue;
  55232. };
  55233. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55234. if (newValue !== currentValue) {
  55235. if (newValue === 1) {
  55236. if (this._ondpaddown) {
  55237. this._ondpaddown(buttonType);
  55238. }
  55239. this.onPadDownObservable.notifyObservers(buttonType);
  55240. }
  55241. if (newValue === 0) {
  55242. if (this._ondpadup) {
  55243. this._ondpadup(buttonType);
  55244. }
  55245. this.onPadUpObservable.notifyObservers(buttonType);
  55246. }
  55247. }
  55248. return newValue;
  55249. };
  55250. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55251. get: function () {
  55252. return this._buttonA;
  55253. },
  55254. set: function (value) {
  55255. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55256. },
  55257. enumerable: true,
  55258. configurable: true
  55259. });
  55260. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55261. get: function () {
  55262. return this._buttonB;
  55263. },
  55264. set: function (value) {
  55265. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55266. },
  55267. enumerable: true,
  55268. configurable: true
  55269. });
  55270. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55271. get: function () {
  55272. return this._buttonX;
  55273. },
  55274. set: function (value) {
  55275. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55276. },
  55277. enumerable: true,
  55278. configurable: true
  55279. });
  55280. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55281. get: function () {
  55282. return this._buttonY;
  55283. },
  55284. set: function (value) {
  55285. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55286. },
  55287. enumerable: true,
  55288. configurable: true
  55289. });
  55290. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55291. get: function () {
  55292. return this._buttonStart;
  55293. },
  55294. set: function (value) {
  55295. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55296. },
  55297. enumerable: true,
  55298. configurable: true
  55299. });
  55300. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55301. get: function () {
  55302. return this._buttonBack;
  55303. },
  55304. set: function (value) {
  55305. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55306. },
  55307. enumerable: true,
  55308. configurable: true
  55309. });
  55310. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55311. get: function () {
  55312. return this._buttonLB;
  55313. },
  55314. set: function (value) {
  55315. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55316. },
  55317. enumerable: true,
  55318. configurable: true
  55319. });
  55320. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55321. get: function () {
  55322. return this._buttonRB;
  55323. },
  55324. set: function (value) {
  55325. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55326. },
  55327. enumerable: true,
  55328. configurable: true
  55329. });
  55330. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55331. get: function () {
  55332. return this._buttonLeftStick;
  55333. },
  55334. set: function (value) {
  55335. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55336. },
  55337. enumerable: true,
  55338. configurable: true
  55339. });
  55340. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55341. get: function () {
  55342. return this._buttonRightStick;
  55343. },
  55344. set: function (value) {
  55345. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55346. },
  55347. enumerable: true,
  55348. configurable: true
  55349. });
  55350. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55351. get: function () {
  55352. return this._dPadUp;
  55353. },
  55354. set: function (value) {
  55355. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55356. },
  55357. enumerable: true,
  55358. configurable: true
  55359. });
  55360. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55361. get: function () {
  55362. return this._dPadDown;
  55363. },
  55364. set: function (value) {
  55365. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55366. },
  55367. enumerable: true,
  55368. configurable: true
  55369. });
  55370. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55371. get: function () {
  55372. return this._dPadLeft;
  55373. },
  55374. set: function (value) {
  55375. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55376. },
  55377. enumerable: true,
  55378. configurable: true
  55379. });
  55380. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55381. get: function () {
  55382. return this._dPadRight;
  55383. },
  55384. set: function (value) {
  55385. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55386. },
  55387. enumerable: true,
  55388. configurable: true
  55389. });
  55390. Xbox360Pad.prototype.update = function () {
  55391. _super.prototype.update.call(this);
  55392. if (this._isXboxOnePad) {
  55393. this.buttonA = this.browserGamepad.buttons[0].value;
  55394. this.buttonB = this.browserGamepad.buttons[1].value;
  55395. this.buttonX = this.browserGamepad.buttons[2].value;
  55396. this.buttonY = this.browserGamepad.buttons[3].value;
  55397. this.buttonLB = this.browserGamepad.buttons[4].value;
  55398. this.buttonRB = this.browserGamepad.buttons[5].value;
  55399. this.leftTrigger = this.browserGamepad.axes[2];
  55400. this.rightTrigger = this.browserGamepad.axes[5];
  55401. this.buttonBack = this.browserGamepad.buttons[9].value;
  55402. this.buttonStart = this.browserGamepad.buttons[8].value;
  55403. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  55404. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  55405. this.dPadUp = this.browserGamepad.buttons[11].value;
  55406. this.dPadDown = this.browserGamepad.buttons[12].value;
  55407. this.dPadLeft = this.browserGamepad.buttons[13].value;
  55408. this.dPadRight = this.browserGamepad.buttons[14].value;
  55409. }
  55410. else {
  55411. this.buttonA = this.browserGamepad.buttons[0].value;
  55412. this.buttonB = this.browserGamepad.buttons[1].value;
  55413. this.buttonX = this.browserGamepad.buttons[2].value;
  55414. this.buttonY = this.browserGamepad.buttons[3].value;
  55415. this.buttonLB = this.browserGamepad.buttons[4].value;
  55416. this.buttonRB = this.browserGamepad.buttons[5].value;
  55417. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55418. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55419. this.buttonBack = this.browserGamepad.buttons[8].value;
  55420. this.buttonStart = this.browserGamepad.buttons[9].value;
  55421. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55422. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55423. this.dPadUp = this.browserGamepad.buttons[12].value;
  55424. this.dPadDown = this.browserGamepad.buttons[13].value;
  55425. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55426. this.dPadRight = this.browserGamepad.buttons[15].value;
  55427. }
  55428. };
  55429. return Xbox360Pad;
  55430. }(BABYLON.Gamepad));
  55431. BABYLON.Xbox360Pad = Xbox360Pad;
  55432. })(BABYLON || (BABYLON = {}));
  55433. //# sourceMappingURL=babylon.xboxGamepad.js.map
  55434. var BABYLON;
  55435. (function (BABYLON) {
  55436. var PoseEnabledControllerType;
  55437. (function (PoseEnabledControllerType) {
  55438. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  55439. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  55440. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  55441. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  55442. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  55443. var PoseEnabledControllerHelper = /** @class */ (function () {
  55444. function PoseEnabledControllerHelper() {
  55445. }
  55446. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  55447. // Oculus Touch
  55448. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  55449. return new BABYLON.OculusTouchController(vrGamepad);
  55450. }
  55451. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  55452. return new BABYLON.WindowsMotionController(vrGamepad);
  55453. }
  55454. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  55455. return new BABYLON.ViveController(vrGamepad);
  55456. }
  55457. else {
  55458. return new BABYLON.GenericController(vrGamepad);
  55459. }
  55460. };
  55461. return PoseEnabledControllerHelper;
  55462. }());
  55463. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  55464. var PoseEnabledController = /** @class */ (function (_super) {
  55465. __extends(PoseEnabledController, _super);
  55466. function PoseEnabledController(browserGamepad) {
  55467. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  55468. _this.deviceScaleFactor = 1;
  55469. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  55470. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  55471. _this.controllerType = PoseEnabledControllerType.GENERIC;
  55472. _this.position = BABYLON.Vector3.Zero();
  55473. _this.rotationQuaternion = new BABYLON.Quaternion();
  55474. _this.devicePosition = BABYLON.Vector3.Zero();
  55475. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  55476. _this._calculatedPosition = BABYLON.Vector3.Zero();
  55477. _this._calculatedRotation = new BABYLON.Quaternion();
  55478. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  55479. return _this;
  55480. }
  55481. PoseEnabledController.prototype.update = function () {
  55482. _super.prototype.update.call(this);
  55483. var pose = this.browserGamepad.pose;
  55484. this.updateFromDevice(pose);
  55485. if (this._mesh) {
  55486. this._mesh.position.copyFrom(this._calculatedPosition);
  55487. if (this._mesh.rotationQuaternion) {
  55488. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  55489. }
  55490. }
  55491. };
  55492. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  55493. if (poseData) {
  55494. this.rawPose = poseData;
  55495. if (poseData.position) {
  55496. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  55497. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  55498. this.devicePosition.z *= -1;
  55499. }
  55500. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  55501. this._calculatedPosition.addInPlace(this.position);
  55502. }
  55503. var pose = this.rawPose;
  55504. if (poseData.orientation && pose.orientation) {
  55505. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  55506. if (this._mesh) {
  55507. if (this._mesh.getScene().useRightHandedSystem) {
  55508. this.deviceRotationQuaternion.z *= -1;
  55509. this.deviceRotationQuaternion.w *= -1;
  55510. }
  55511. else {
  55512. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  55513. }
  55514. }
  55515. // if the camera is set, rotate to the camera's rotation
  55516. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  55517. }
  55518. }
  55519. };
  55520. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  55521. if (this._mesh) {
  55522. this._mesh.parent = null;
  55523. }
  55524. this._mesh = mesh;
  55525. if (this._poseControlledCamera) {
  55526. this._mesh.parent = this._poseControlledCamera;
  55527. }
  55528. if (!this._mesh.rotationQuaternion) {
  55529. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  55530. }
  55531. };
  55532. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  55533. this._poseControlledCamera = camera;
  55534. if (this._mesh) {
  55535. this._mesh.parent = this._poseControlledCamera;
  55536. }
  55537. };
  55538. PoseEnabledController.prototype.dispose = function () {
  55539. if (this._mesh) {
  55540. this._mesh.dispose();
  55541. }
  55542. this._mesh = null;
  55543. _super.prototype.dispose.call(this);
  55544. };
  55545. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  55546. get: function () {
  55547. return this._mesh;
  55548. },
  55549. enumerable: true,
  55550. configurable: true
  55551. });
  55552. PoseEnabledController.prototype.getForwardRay = function (length) {
  55553. if (length === void 0) { length = 100; }
  55554. if (!this.mesh) {
  55555. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  55556. }
  55557. var m = this.mesh.getWorldMatrix();
  55558. var origin = m.getTranslation();
  55559. var forward = new BABYLON.Vector3(0, 0, -1);
  55560. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55561. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55562. return new BABYLON.Ray(origin, direction, length);
  55563. };
  55564. return PoseEnabledController;
  55565. }(BABYLON.Gamepad));
  55566. BABYLON.PoseEnabledController = PoseEnabledController;
  55567. })(BABYLON || (BABYLON = {}));
  55568. //# sourceMappingURL=babylon.poseEnabledController.js.map
  55569. var BABYLON;
  55570. (function (BABYLON) {
  55571. var WebVRController = /** @class */ (function (_super) {
  55572. __extends(WebVRController, _super);
  55573. function WebVRController(vrGamepad) {
  55574. var _this = _super.call(this, vrGamepad) || this;
  55575. // Observables
  55576. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  55577. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  55578. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  55579. _this.onPadStateChangedObservable = new BABYLON.Observable();
  55580. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  55581. _this.pad = { x: 0, y: 0 };
  55582. // avoid GC, store state in a tmp object
  55583. _this._changes = {
  55584. pressChanged: false,
  55585. touchChanged: false,
  55586. valueChanged: false,
  55587. changed: false
  55588. };
  55589. _this._buttons = new Array(vrGamepad.buttons.length);
  55590. _this.hand = vrGamepad.hand;
  55591. return _this;
  55592. }
  55593. WebVRController.prototype.onButtonStateChange = function (callback) {
  55594. this._onButtonStateChange = callback;
  55595. };
  55596. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  55597. get: function () {
  55598. return this._defaultModel;
  55599. },
  55600. enumerable: true,
  55601. configurable: true
  55602. });
  55603. WebVRController.prototype.update = function () {
  55604. _super.prototype.update.call(this);
  55605. for (var index = 0; index < this._buttons.length; index++) {
  55606. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  55607. }
  55608. ;
  55609. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  55610. this.pad.x = this.leftStick.x;
  55611. this.pad.y = this.leftStick.y;
  55612. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  55613. }
  55614. };
  55615. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  55616. if (!newState) {
  55617. newState = {
  55618. pressed: false,
  55619. touched: false,
  55620. value: 0
  55621. };
  55622. }
  55623. if (!currentState) {
  55624. this._buttons[buttonIndex] = {
  55625. pressed: newState.pressed,
  55626. touched: newState.touched,
  55627. value: newState.value
  55628. };
  55629. return;
  55630. }
  55631. this._checkChanges(newState, currentState);
  55632. if (this._changes.changed) {
  55633. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  55634. this.handleButtonChange(buttonIndex, newState, this._changes);
  55635. }
  55636. this._buttons[buttonIndex].pressed = newState.pressed;
  55637. this._buttons[buttonIndex].touched = newState.touched;
  55638. // oculus triggers are never 0, thou not touched.
  55639. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  55640. };
  55641. WebVRController.prototype._checkChanges = function (newState, currentState) {
  55642. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  55643. this._changes.touchChanged = newState.touched !== currentState.touched;
  55644. this._changes.valueChanged = newState.value !== currentState.value;
  55645. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  55646. return this._changes;
  55647. };
  55648. WebVRController.prototype.dispose = function () {
  55649. _super.prototype.dispose.call(this);
  55650. this.onTriggerStateChangedObservable.clear();
  55651. this.onMainButtonStateChangedObservable.clear();
  55652. this.onSecondaryButtonStateChangedObservable.clear();
  55653. this.onPadStateChangedObservable.clear();
  55654. this.onPadValuesChangedObservable.clear();
  55655. };
  55656. return WebVRController;
  55657. }(BABYLON.PoseEnabledController));
  55658. BABYLON.WebVRController = WebVRController;
  55659. })(BABYLON || (BABYLON = {}));
  55660. //# sourceMappingURL=babylon.webVRController.js.map
  55661. var BABYLON;
  55662. (function (BABYLON) {
  55663. var OculusTouchController = /** @class */ (function (_super) {
  55664. __extends(OculusTouchController, _super);
  55665. function OculusTouchController(vrGamepad) {
  55666. var _this = _super.call(this, vrGamepad) || this;
  55667. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  55668. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  55669. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  55670. return _this;
  55671. }
  55672. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55673. var _this = this;
  55674. var meshName;
  55675. // Hand
  55676. if (this.hand === 'left') {
  55677. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  55678. }
  55679. else {
  55680. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  55681. }
  55682. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  55683. /*
  55684. Parent Mesh name: oculus_touch_left
  55685. - body
  55686. - trigger
  55687. - thumbstick
  55688. - grip
  55689. - button_y
  55690. - button_x
  55691. - button_enter
  55692. */
  55693. _this._defaultModel = newMeshes[1];
  55694. _this.attachToMesh(_this._defaultModel);
  55695. if (meshLoaded) {
  55696. meshLoaded(_this._defaultModel);
  55697. }
  55698. });
  55699. };
  55700. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  55701. // helper getters for left and right hand.
  55702. get: function () {
  55703. if (this.hand === 'right') {
  55704. return this.onMainButtonStateChangedObservable;
  55705. }
  55706. else {
  55707. throw new Error('No A button on left hand');
  55708. }
  55709. },
  55710. enumerable: true,
  55711. configurable: true
  55712. });
  55713. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  55714. get: function () {
  55715. if (this.hand === 'right') {
  55716. return this.onSecondaryButtonStateChangedObservable;
  55717. }
  55718. else {
  55719. throw new Error('No B button on left hand');
  55720. }
  55721. },
  55722. enumerable: true,
  55723. configurable: true
  55724. });
  55725. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  55726. get: function () {
  55727. if (this.hand === 'left') {
  55728. return this.onMainButtonStateChangedObservable;
  55729. }
  55730. else {
  55731. throw new Error('No X button on right hand');
  55732. }
  55733. },
  55734. enumerable: true,
  55735. configurable: true
  55736. });
  55737. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  55738. get: function () {
  55739. if (this.hand === 'left') {
  55740. return this.onSecondaryButtonStateChangedObservable;
  55741. }
  55742. else {
  55743. throw new Error('No Y button on right hand');
  55744. }
  55745. },
  55746. enumerable: true,
  55747. configurable: true
  55748. });
  55749. /*
  55750. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  55751. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  55752. 2) secondary trigger (same)
  55753. 3) A (right) X (left), touch, pressed = value
  55754. 4) B / Y
  55755. 5) thumb rest
  55756. */
  55757. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55758. var notifyObject = state; //{ state: state, changes: changes };
  55759. var triggerDirection = this.hand === 'right' ? -1 : 1;
  55760. switch (buttonIdx) {
  55761. case 0:
  55762. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55763. return;
  55764. case 1:// index trigger
  55765. if (this._defaultModel) {
  55766. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  55767. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  55768. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  55769. }
  55770. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55771. return;
  55772. case 2:// secondary trigger
  55773. if (this._defaultModel) {
  55774. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  55775. }
  55776. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  55777. return;
  55778. case 3:
  55779. if (this._defaultModel) {
  55780. if (notifyObject.pressed) {
  55781. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  55782. }
  55783. else {
  55784. (this._defaultModel.getChildren()[1]).position.y = 0;
  55785. }
  55786. }
  55787. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55788. return;
  55789. case 4:
  55790. if (this._defaultModel) {
  55791. if (notifyObject.pressed) {
  55792. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55793. }
  55794. else {
  55795. (this._defaultModel.getChildren()[2]).position.y = 0;
  55796. }
  55797. }
  55798. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55799. return;
  55800. case 5:
  55801. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  55802. return;
  55803. }
  55804. };
  55805. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  55806. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  55807. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  55808. return OculusTouchController;
  55809. }(BABYLON.WebVRController));
  55810. BABYLON.OculusTouchController = OculusTouchController;
  55811. })(BABYLON || (BABYLON = {}));
  55812. //# sourceMappingURL=babylon.oculusTouchController.js.map
  55813. var BABYLON;
  55814. (function (BABYLON) {
  55815. var ViveController = /** @class */ (function (_super) {
  55816. __extends(ViveController, _super);
  55817. function ViveController(vrGamepad) {
  55818. var _this = _super.call(this, vrGamepad) || this;
  55819. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  55820. return _this;
  55821. }
  55822. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55823. var _this = this;
  55824. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  55825. /*
  55826. Parent Mesh name: ViveWand
  55827. - body
  55828. - r_gripper
  55829. - l_gripper
  55830. - menu_button
  55831. - system_button
  55832. - trackpad
  55833. - trigger
  55834. - LED
  55835. */
  55836. _this._defaultModel = newMeshes[1];
  55837. _this.attachToMesh(_this._defaultModel);
  55838. if (meshLoaded) {
  55839. meshLoaded(_this._defaultModel);
  55840. }
  55841. });
  55842. };
  55843. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  55844. get: function () {
  55845. return this.onMainButtonStateChangedObservable;
  55846. },
  55847. enumerable: true,
  55848. configurable: true
  55849. });
  55850. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  55851. get: function () {
  55852. return this.onMainButtonStateChangedObservable;
  55853. },
  55854. enumerable: true,
  55855. configurable: true
  55856. });
  55857. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  55858. get: function () {
  55859. return this.onSecondaryButtonStateChangedObservable;
  55860. },
  55861. enumerable: true,
  55862. configurable: true
  55863. });
  55864. /**
  55865. * Vive mapping:
  55866. * 0: touchpad
  55867. * 1: trigger
  55868. * 2: left AND right buttons
  55869. * 3: menu button
  55870. */
  55871. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55872. var notifyObject = state; //{ state: state, changes: changes };
  55873. switch (buttonIdx) {
  55874. case 0:
  55875. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55876. return;
  55877. case 1:// index trigger
  55878. if (this._defaultModel) {
  55879. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  55880. }
  55881. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55882. return;
  55883. case 2:// left AND right button
  55884. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55885. return;
  55886. case 3:
  55887. if (this._defaultModel) {
  55888. if (notifyObject.pressed) {
  55889. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55890. }
  55891. else {
  55892. (this._defaultModel.getChildren()[2]).position.y = 0;
  55893. }
  55894. }
  55895. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55896. return;
  55897. }
  55898. };
  55899. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  55900. ViveController.MODEL_FILENAME = 'wand.babylon';
  55901. return ViveController;
  55902. }(BABYLON.WebVRController));
  55903. BABYLON.ViveController = ViveController;
  55904. })(BABYLON || (BABYLON = {}));
  55905. //# sourceMappingURL=babylon.viveController.js.map
  55906. var BABYLON;
  55907. (function (BABYLON) {
  55908. var GenericController = /** @class */ (function (_super) {
  55909. __extends(GenericController, _super);
  55910. function GenericController(vrGamepad) {
  55911. return _super.call(this, vrGamepad) || this;
  55912. }
  55913. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55914. var _this = this;
  55915. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  55916. _this._defaultModel = newMeshes[1];
  55917. _this.attachToMesh(_this._defaultModel);
  55918. if (meshLoaded) {
  55919. meshLoaded(_this._defaultModel);
  55920. }
  55921. });
  55922. };
  55923. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55924. console.log("Button id: " + buttonIdx + "state: ");
  55925. console.dir(state);
  55926. };
  55927. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  55928. GenericController.MODEL_FILENAME = 'generic.babylon';
  55929. return GenericController;
  55930. }(BABYLON.WebVRController));
  55931. BABYLON.GenericController = GenericController;
  55932. })(BABYLON || (BABYLON = {}));
  55933. //# sourceMappingURL=babylon.genericController.js.map
  55934. var BABYLON;
  55935. (function (BABYLON) {
  55936. var LoadedMeshInfo = /** @class */ (function () {
  55937. function LoadedMeshInfo() {
  55938. this.buttonMeshes = {};
  55939. this.axisMeshes = {};
  55940. }
  55941. return LoadedMeshInfo;
  55942. }());
  55943. var WindowsMotionController = /** @class */ (function (_super) {
  55944. __extends(WindowsMotionController, _super);
  55945. function WindowsMotionController(vrGamepad) {
  55946. var _this = _super.call(this, vrGamepad) || this;
  55947. _this._mapping = {
  55948. // Semantic button names
  55949. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  55950. // A mapping of the button name to glTF model node name
  55951. // that should be transformed by button value.
  55952. buttonMeshNames: {
  55953. 'trigger': 'SELECT',
  55954. 'menu': 'MENU',
  55955. 'grip': 'GRASP',
  55956. 'thumbstick': 'THUMBSTICK_PRESS',
  55957. 'trackpad': 'TOUCHPAD_PRESS'
  55958. },
  55959. // This mapping is used to translate from the Motion Controller to Babylon semantics
  55960. buttonObservableNames: {
  55961. 'trigger': 'onTriggerStateChangedObservable',
  55962. 'menu': 'onSecondaryButtonStateChangedObservable',
  55963. 'grip': 'onMainButtonStateChangedObservable',
  55964. 'thumbstick': 'onPadStateChangedObservable',
  55965. 'trackpad': 'onTrackpadChangedObservable'
  55966. },
  55967. // A mapping of the axis name to glTF model node name
  55968. // that should be transformed by axis value.
  55969. // This array mirrors the browserGamepad.axes array, such that
  55970. // the mesh corresponding to axis 0 is in this array index 0.
  55971. axisMeshNames: [
  55972. 'THUMBSTICK_X',
  55973. 'THUMBSTICK_Y',
  55974. 'TOUCHPAD_TOUCH_X',
  55975. 'TOUCHPAD_TOUCH_Y'
  55976. ],
  55977. pointingPoseMeshName: 'POINTING_POSE'
  55978. };
  55979. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  55980. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  55981. _this._loadedMeshInfo = null;
  55982. return _this;
  55983. }
  55984. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  55985. get: function () {
  55986. return this.onTriggerStateChangedObservable;
  55987. },
  55988. enumerable: true,
  55989. configurable: true
  55990. });
  55991. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  55992. get: function () {
  55993. return this.onSecondaryButtonStateChangedObservable;
  55994. },
  55995. enumerable: true,
  55996. configurable: true
  55997. });
  55998. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  55999. get: function () {
  56000. return this.onMainButtonStateChangedObservable;
  56001. },
  56002. enumerable: true,
  56003. configurable: true
  56004. });
  56005. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  56006. get: function () {
  56007. return this.onPadStateChangedObservable;
  56008. },
  56009. enumerable: true,
  56010. configurable: true
  56011. });
  56012. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  56013. get: function () {
  56014. return this.onTrackpadChangedObservable;
  56015. },
  56016. enumerable: true,
  56017. configurable: true
  56018. });
  56019. /**
  56020. * Called once per frame by the engine.
  56021. */
  56022. WindowsMotionController.prototype.update = function () {
  56023. _super.prototype.update.call(this);
  56024. // Only need to animate axes if there is a loaded mesh
  56025. if (this._loadedMeshInfo) {
  56026. if (this.browserGamepad.axes) {
  56027. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  56028. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  56029. }
  56030. }
  56031. }
  56032. };
  56033. /**
  56034. * Called once for each button that changed state since the last frame
  56035. * @param buttonIdx Which button index changed
  56036. * @param state New state of the button
  56037. * @param changes Which properties on the state changed since last frame
  56038. */
  56039. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56040. var buttonName = this._mapping.buttons[buttonIdx];
  56041. if (!buttonName) {
  56042. return;
  56043. }
  56044. // Only emit events for buttons that we know how to map from index to name
  56045. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  56046. if (observable) {
  56047. observable.notifyObservers(state);
  56048. }
  56049. this.lerpButtonTransform(buttonName, state.value);
  56050. };
  56051. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  56052. // If there is no loaded mesh, there is nothing to transform.
  56053. if (!this._loadedMeshInfo) {
  56054. return;
  56055. }
  56056. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  56057. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56058. return;
  56059. }
  56060. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  56061. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  56062. };
  56063. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  56064. if (!this._loadedMeshInfo) {
  56065. return;
  56066. }
  56067. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  56068. if (!meshInfo) {
  56069. return;
  56070. }
  56071. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56072. return;
  56073. }
  56074. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  56075. var lerpValue = axisValue * 0.5 + 0.5;
  56076. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  56077. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  56078. };
  56079. /**
  56080. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  56081. * @param scene scene in which to add meshes
  56082. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  56083. */
  56084. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  56085. var _this = this;
  56086. if (forceDefault === void 0) { forceDefault = false; }
  56087. var path;
  56088. var filename;
  56089. // Checking if GLB loader is present
  56090. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  56091. // Determine the device specific folder based on the ID suffix
  56092. var device = 'default';
  56093. if (this.id && !forceDefault) {
  56094. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  56095. device = ((match && match[0]) || device);
  56096. }
  56097. // Hand
  56098. if (this.hand === 'left') {
  56099. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  56100. }
  56101. else {
  56102. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  56103. }
  56104. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  56105. }
  56106. else {
  56107. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  56108. path = BABYLON.GenericController.MODEL_BASE_URL;
  56109. filename = BABYLON.GenericController.MODEL_FILENAME;
  56110. }
  56111. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  56112. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  56113. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  56114. if (!_this._loadedMeshInfo) {
  56115. return;
  56116. }
  56117. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  56118. _this.attachToMesh(_this._defaultModel);
  56119. if (meshLoaded) {
  56120. meshLoaded(_this._defaultModel);
  56121. }
  56122. }, null, function (scene, message) {
  56123. BABYLON.Tools.Log(message);
  56124. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  56125. if (!forceDefault) {
  56126. _this.initControllerMesh(scene, meshLoaded, true);
  56127. }
  56128. });
  56129. };
  56130. /**
  56131. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  56132. * can be transformed by button presses and axes values, based on this._mapping.
  56133. *
  56134. * @param scene scene in which the meshes exist
  56135. * @param meshes list of meshes that make up the controller model to process
  56136. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  56137. */
  56138. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  56139. var loadedMeshInfo = null;
  56140. // Create a new mesh to contain the glTF hierarchy
  56141. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  56142. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  56143. var childMesh = null;
  56144. for (var i = 0; i < meshes.length; i++) {
  56145. var mesh = meshes[i];
  56146. if (!mesh.parent) {
  56147. // Exclude controller meshes from picking results
  56148. mesh.isPickable = false;
  56149. // Handle root node, attach to the new parentMesh
  56150. childMesh = mesh;
  56151. break;
  56152. }
  56153. }
  56154. if (childMesh) {
  56155. childMesh.setParent(parentMesh);
  56156. // Create our mesh info. Note that this method will always return non-null.
  56157. loadedMeshInfo = this.createMeshInfo(parentMesh);
  56158. }
  56159. else {
  56160. BABYLON.Tools.Warn('Could not find root node in model file.');
  56161. }
  56162. return loadedMeshInfo;
  56163. };
  56164. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  56165. var loadedMeshInfo = new LoadedMeshInfo();
  56166. var i;
  56167. loadedMeshInfo.rootNode = rootNode;
  56168. // Reset the caches
  56169. loadedMeshInfo.buttonMeshes = {};
  56170. loadedMeshInfo.axisMeshes = {};
  56171. // Button Meshes
  56172. for (i = 0; i < this._mapping.buttons.length; i++) {
  56173. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56174. if (!buttonMeshName) {
  56175. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56176. continue;
  56177. }
  56178. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56179. if (!buttonMesh) {
  56180. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56181. continue;
  56182. }
  56183. var buttonMeshInfo = {
  56184. index: i,
  56185. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56186. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56187. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56188. };
  56189. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56190. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56191. }
  56192. else {
  56193. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56194. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56195. '(VALUE: ' + !!buttonMeshInfo.value +
  56196. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56197. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56198. ')');
  56199. }
  56200. }
  56201. // Axis Meshes
  56202. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56203. var axisMeshName = this._mapping.axisMeshNames[i];
  56204. if (!axisMeshName) {
  56205. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56206. continue;
  56207. }
  56208. var axisMesh = getChildByName(rootNode, axisMeshName);
  56209. if (!axisMesh) {
  56210. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56211. continue;
  56212. }
  56213. var axisMeshInfo = {
  56214. index: i,
  56215. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56216. min: getImmediateChildByName(axisMesh, 'MIN'),
  56217. max: getImmediateChildByName(axisMesh, 'MAX')
  56218. };
  56219. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  56220. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  56221. }
  56222. else {
  56223. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  56224. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  56225. '(VALUE: ' + !!axisMeshInfo.value +
  56226. ', MIN: ' + !!axisMeshInfo.min +
  56227. ', MAX:' + !!axisMeshInfo.max +
  56228. ')');
  56229. }
  56230. }
  56231. // Pointing Ray
  56232. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  56233. if (!loadedMeshInfo.pointingPoseNode) {
  56234. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  56235. }
  56236. return loadedMeshInfo;
  56237. // Look through all children recursively. This will return null if no mesh exists with the given name.
  56238. function getChildByName(node, name) {
  56239. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  56240. }
  56241. // Look through only immediate children. This will return null if no mesh exists with the given name.
  56242. function getImmediateChildByName(node, name) {
  56243. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  56244. }
  56245. };
  56246. WindowsMotionController.prototype.getForwardRay = function (length) {
  56247. if (length === void 0) { length = 100; }
  56248. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  56249. return _super.prototype.getForwardRay.call(this, length);
  56250. }
  56251. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  56252. var origin = m.getTranslation();
  56253. var forward = new BABYLON.Vector3(0, 0, -1);
  56254. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56255. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56256. return new BABYLON.Ray(origin, direction, length);
  56257. };
  56258. WindowsMotionController.prototype.dispose = function () {
  56259. _super.prototype.dispose.call(this);
  56260. this.onTrackpadChangedObservable.clear();
  56261. };
  56262. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  56263. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  56264. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  56265. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  56266. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  56267. return WindowsMotionController;
  56268. }(BABYLON.WebVRController));
  56269. BABYLON.WindowsMotionController = WindowsMotionController;
  56270. })(BABYLON || (BABYLON = {}));
  56271. //# sourceMappingURL=babylon.windowsMotionController.js.map
  56272. var BABYLON;
  56273. (function (BABYLON) {
  56274. var FollowCamera = /** @class */ (function (_super) {
  56275. __extends(FollowCamera, _super);
  56276. function FollowCamera(name, position, scene, lockedTarget) {
  56277. if (lockedTarget === void 0) { lockedTarget = null; }
  56278. var _this = _super.call(this, name, position, scene) || this;
  56279. _this.radius = 12;
  56280. _this.rotationOffset = 0;
  56281. _this.heightOffset = 4;
  56282. _this.cameraAcceleration = 0.05;
  56283. _this.maxCameraSpeed = 20;
  56284. _this.lockedTarget = lockedTarget;
  56285. return _this;
  56286. }
  56287. FollowCamera.prototype.getRadians = function (degrees) {
  56288. return degrees * Math.PI / 180;
  56289. };
  56290. FollowCamera.prototype.follow = function (cameraTarget) {
  56291. if (!cameraTarget)
  56292. return;
  56293. var yRotation;
  56294. if (cameraTarget.rotationQuaternion) {
  56295. var rotMatrix = new BABYLON.Matrix();
  56296. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  56297. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  56298. }
  56299. else {
  56300. yRotation = cameraTarget.rotation.y;
  56301. }
  56302. var radians = this.getRadians(this.rotationOffset) + yRotation;
  56303. var targetPosition = cameraTarget.getAbsolutePosition();
  56304. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  56305. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  56306. var dx = targetX - this.position.x;
  56307. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  56308. var dz = (targetZ) - this.position.z;
  56309. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  56310. var vy = dy * this.cameraAcceleration;
  56311. var vz = dz * this.cameraAcceleration * 2;
  56312. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  56313. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56314. }
  56315. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  56316. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56317. }
  56318. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  56319. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56320. }
  56321. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  56322. this.setTarget(targetPosition);
  56323. };
  56324. FollowCamera.prototype._checkInputs = function () {
  56325. _super.prototype._checkInputs.call(this);
  56326. if (this.lockedTarget) {
  56327. this.follow(this.lockedTarget);
  56328. }
  56329. };
  56330. FollowCamera.prototype.getClassName = function () {
  56331. return "FollowCamera";
  56332. };
  56333. __decorate([
  56334. BABYLON.serialize()
  56335. ], FollowCamera.prototype, "radius", void 0);
  56336. __decorate([
  56337. BABYLON.serialize()
  56338. ], FollowCamera.prototype, "rotationOffset", void 0);
  56339. __decorate([
  56340. BABYLON.serialize()
  56341. ], FollowCamera.prototype, "heightOffset", void 0);
  56342. __decorate([
  56343. BABYLON.serialize()
  56344. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  56345. __decorate([
  56346. BABYLON.serialize()
  56347. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  56348. __decorate([
  56349. BABYLON.serializeAsMeshReference("lockedTargetId")
  56350. ], FollowCamera.prototype, "lockedTarget", void 0);
  56351. return FollowCamera;
  56352. }(BABYLON.TargetCamera));
  56353. BABYLON.FollowCamera = FollowCamera;
  56354. var ArcFollowCamera = /** @class */ (function (_super) {
  56355. __extends(ArcFollowCamera, _super);
  56356. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  56357. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  56358. _this.alpha = alpha;
  56359. _this.beta = beta;
  56360. _this.radius = radius;
  56361. _this.target = target;
  56362. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  56363. _this.follow();
  56364. return _this;
  56365. }
  56366. ArcFollowCamera.prototype.follow = function () {
  56367. if (!this.target) {
  56368. return;
  56369. }
  56370. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  56371. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  56372. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  56373. var targetPosition = this.target.getAbsolutePosition();
  56374. this.position = targetPosition.add(this._cartesianCoordinates);
  56375. this.setTarget(targetPosition);
  56376. };
  56377. ArcFollowCamera.prototype._checkInputs = function () {
  56378. _super.prototype._checkInputs.call(this);
  56379. this.follow();
  56380. };
  56381. ArcFollowCamera.prototype.getClassName = function () {
  56382. return "ArcFollowCamera";
  56383. };
  56384. return ArcFollowCamera;
  56385. }(BABYLON.TargetCamera));
  56386. BABYLON.ArcFollowCamera = ArcFollowCamera;
  56387. })(BABYLON || (BABYLON = {}));
  56388. //# sourceMappingURL=babylon.followCamera.js.map
  56389. var BABYLON;
  56390. (function (BABYLON) {
  56391. // We're mainly based on the logic defined into the FreeCamera code
  56392. var UniversalCamera = /** @class */ (function (_super) {
  56393. __extends(UniversalCamera, _super);
  56394. //-- end properties for backward compatibility for inputs
  56395. function UniversalCamera(name, position, scene) {
  56396. var _this = _super.call(this, name, position, scene) || this;
  56397. _this.inputs.addGamepad();
  56398. return _this;
  56399. }
  56400. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  56401. //-- Begin properties for backward compatibility for inputs
  56402. get: function () {
  56403. var gamepad = this.inputs.attached["gamepad"];
  56404. if (gamepad)
  56405. return gamepad.gamepadAngularSensibility;
  56406. return 0;
  56407. },
  56408. set: function (value) {
  56409. var gamepad = this.inputs.attached["gamepad"];
  56410. if (gamepad)
  56411. gamepad.gamepadAngularSensibility = value;
  56412. },
  56413. enumerable: true,
  56414. configurable: true
  56415. });
  56416. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  56417. get: function () {
  56418. var gamepad = this.inputs.attached["gamepad"];
  56419. if (gamepad)
  56420. return gamepad.gamepadMoveSensibility;
  56421. return 0;
  56422. },
  56423. set: function (value) {
  56424. var gamepad = this.inputs.attached["gamepad"];
  56425. if (gamepad)
  56426. gamepad.gamepadMoveSensibility = value;
  56427. },
  56428. enumerable: true,
  56429. configurable: true
  56430. });
  56431. UniversalCamera.prototype.getClassName = function () {
  56432. return "UniversalCamera";
  56433. };
  56434. return UniversalCamera;
  56435. }(BABYLON.TouchCamera));
  56436. BABYLON.UniversalCamera = UniversalCamera;
  56437. })(BABYLON || (BABYLON = {}));
  56438. //# sourceMappingURL=babylon.universalCamera.js.map
  56439. var BABYLON;
  56440. (function (BABYLON) {
  56441. // We're mainly based on the logic defined into the FreeCamera code
  56442. var GamepadCamera = /** @class */ (function (_super) {
  56443. __extends(GamepadCamera, _super);
  56444. //-- end properties for backward compatibility for inputs
  56445. function GamepadCamera(name, position, scene) {
  56446. return _super.call(this, name, position, scene) || this;
  56447. }
  56448. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  56449. //-- Begin properties for backward compatibility for inputs
  56450. get: function () {
  56451. var gamepad = this.inputs.attached["gamepad"];
  56452. if (gamepad)
  56453. return gamepad.gamepadAngularSensibility;
  56454. return 0;
  56455. },
  56456. set: function (value) {
  56457. var gamepad = this.inputs.attached["gamepad"];
  56458. if (gamepad)
  56459. gamepad.gamepadAngularSensibility = value;
  56460. },
  56461. enumerable: true,
  56462. configurable: true
  56463. });
  56464. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  56465. get: function () {
  56466. var gamepad = this.inputs.attached["gamepad"];
  56467. if (gamepad)
  56468. return gamepad.gamepadMoveSensibility;
  56469. return 0;
  56470. },
  56471. set: function (value) {
  56472. var gamepad = this.inputs.attached["gamepad"];
  56473. if (gamepad)
  56474. gamepad.gamepadMoveSensibility = value;
  56475. },
  56476. enumerable: true,
  56477. configurable: true
  56478. });
  56479. GamepadCamera.prototype.getClassName = function () {
  56480. return "GamepadCamera";
  56481. };
  56482. return GamepadCamera;
  56483. }(BABYLON.UniversalCamera));
  56484. BABYLON.GamepadCamera = GamepadCamera;
  56485. })(BABYLON || (BABYLON = {}));
  56486. //# sourceMappingURL=babylon.gamepadCamera.js.map
  56487. var BABYLON;
  56488. (function (BABYLON) {
  56489. var PostProcessRenderPipelineManager = /** @class */ (function () {
  56490. function PostProcessRenderPipelineManager() {
  56491. this._renderPipelines = {};
  56492. }
  56493. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  56494. this._renderPipelines[renderPipeline._name] = renderPipeline;
  56495. };
  56496. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  56497. if (unique === void 0) { unique = false; }
  56498. var renderPipeline = this._renderPipelines[renderPipelineName];
  56499. if (!renderPipeline) {
  56500. return;
  56501. }
  56502. renderPipeline._attachCameras(cameras, unique);
  56503. };
  56504. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  56505. var renderPipeline = this._renderPipelines[renderPipelineName];
  56506. if (!renderPipeline) {
  56507. return;
  56508. }
  56509. renderPipeline._detachCameras(cameras);
  56510. };
  56511. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56512. var renderPipeline = this._renderPipelines[renderPipelineName];
  56513. if (!renderPipeline) {
  56514. return;
  56515. }
  56516. renderPipeline._enableEffect(renderEffectName, cameras);
  56517. };
  56518. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56519. var renderPipeline = this._renderPipelines[renderPipelineName];
  56520. if (!renderPipeline) {
  56521. return;
  56522. }
  56523. renderPipeline._disableEffect(renderEffectName, cameras);
  56524. };
  56525. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  56526. var renderPipeline = this._renderPipelines[renderPipelineName];
  56527. if (!renderPipeline) {
  56528. return;
  56529. }
  56530. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  56531. };
  56532. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  56533. var renderPipeline = this._renderPipelines[renderPipelineName];
  56534. if (!renderPipeline) {
  56535. return;
  56536. }
  56537. renderPipeline._disableDisplayOnlyPass(cameras);
  56538. };
  56539. PostProcessRenderPipelineManager.prototype.update = function () {
  56540. for (var renderPipelineName in this._renderPipelines) {
  56541. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56542. var pipeline = this._renderPipelines[renderPipelineName];
  56543. if (!pipeline.isSupported) {
  56544. pipeline.dispose();
  56545. delete this._renderPipelines[renderPipelineName];
  56546. }
  56547. else {
  56548. pipeline._update();
  56549. }
  56550. }
  56551. }
  56552. };
  56553. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  56554. for (var renderPipelineName in this._renderPipelines) {
  56555. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56556. var pipeline = this._renderPipelines[renderPipelineName];
  56557. pipeline._rebuild();
  56558. }
  56559. }
  56560. };
  56561. PostProcessRenderPipelineManager.prototype.dispose = function () {
  56562. for (var renderPipelineName in this._renderPipelines) {
  56563. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56564. var pipeline = this._renderPipelines[renderPipelineName];
  56565. pipeline.dispose();
  56566. }
  56567. }
  56568. };
  56569. return PostProcessRenderPipelineManager;
  56570. }());
  56571. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  56572. })(BABYLON || (BABYLON = {}));
  56573. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  56574. var BABYLON;
  56575. (function (BABYLON) {
  56576. var PostProcessRenderPass = /** @class */ (function () {
  56577. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  56578. this._refCount = 0;
  56579. this._name = name;
  56580. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  56581. this.setRenderList(renderList);
  56582. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  56583. this._renderTexture.onAfterRenderObservable.add(afterRender);
  56584. this._scene = scene;
  56585. this._renderList = renderList;
  56586. }
  56587. // private
  56588. PostProcessRenderPass.prototype._incRefCount = function () {
  56589. if (this._refCount === 0) {
  56590. this._scene.customRenderTargets.push(this._renderTexture);
  56591. }
  56592. return ++this._refCount;
  56593. };
  56594. PostProcessRenderPass.prototype._decRefCount = function () {
  56595. this._refCount--;
  56596. if (this._refCount <= 0) {
  56597. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  56598. }
  56599. return this._refCount;
  56600. };
  56601. PostProcessRenderPass.prototype._update = function () {
  56602. this.setRenderList(this._renderList);
  56603. };
  56604. // public
  56605. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  56606. this._renderTexture.renderList = renderList;
  56607. };
  56608. PostProcessRenderPass.prototype.getRenderTexture = function () {
  56609. return this._renderTexture;
  56610. };
  56611. return PostProcessRenderPass;
  56612. }());
  56613. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  56614. })(BABYLON || (BABYLON = {}));
  56615. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  56616. var BABYLON;
  56617. (function (BABYLON) {
  56618. var PostProcessRenderEffect = /** @class */ (function () {
  56619. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  56620. this._engine = engine;
  56621. this._name = name;
  56622. this._singleInstance = singleInstance || true;
  56623. this._getPostProcess = getPostProcess;
  56624. this._cameras = {};
  56625. this._indicesForCamera = {};
  56626. this._postProcesses = {};
  56627. this._renderPasses = {};
  56628. this._renderEffectAsPasses = {};
  56629. }
  56630. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  56631. get: function () {
  56632. for (var index in this._postProcesses) {
  56633. if (!this._postProcesses[index].isSupported) {
  56634. return false;
  56635. }
  56636. }
  56637. return true;
  56638. },
  56639. enumerable: true,
  56640. configurable: true
  56641. });
  56642. PostProcessRenderEffect.prototype._update = function () {
  56643. for (var renderPassName in this._renderPasses) {
  56644. this._renderPasses[renderPassName]._update();
  56645. }
  56646. };
  56647. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  56648. this._renderPasses[renderPass._name] = renderPass;
  56649. this._linkParameters();
  56650. };
  56651. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  56652. delete this._renderPasses[renderPass._name];
  56653. this._linkParameters();
  56654. };
  56655. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  56656. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  56657. this._linkParameters();
  56658. };
  56659. PostProcessRenderEffect.prototype.getPass = function (passName) {
  56660. for (var renderPassName in this._renderPasses) {
  56661. if (renderPassName === passName) {
  56662. return this._renderPasses[passName];
  56663. }
  56664. }
  56665. return null;
  56666. };
  56667. PostProcessRenderEffect.prototype.emptyPasses = function () {
  56668. this._renderPasses = {};
  56669. this._linkParameters();
  56670. };
  56671. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  56672. var cameraKey;
  56673. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56674. if (!cams) {
  56675. return;
  56676. }
  56677. for (var i = 0; i < cams.length; i++) {
  56678. var camera = cams[i];
  56679. var cameraName = camera.name;
  56680. if (this._singleInstance) {
  56681. cameraKey = 0;
  56682. }
  56683. else {
  56684. cameraKey = cameraName;
  56685. }
  56686. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  56687. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  56688. if (!this._indicesForCamera[cameraName]) {
  56689. this._indicesForCamera[cameraName] = [];
  56690. }
  56691. this._indicesForCamera[cameraName].push(index);
  56692. if (!this._cameras[cameraName]) {
  56693. this._cameras[cameraName] = camera;
  56694. }
  56695. for (var passName in this._renderPasses) {
  56696. this._renderPasses[passName]._incRefCount();
  56697. }
  56698. }
  56699. this._linkParameters();
  56700. };
  56701. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  56702. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56703. if (!cams) {
  56704. return;
  56705. }
  56706. for (var i = 0; i < cams.length; i++) {
  56707. var camera = cams[i];
  56708. var cameraName = camera.name;
  56709. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56710. if (this._cameras[cameraName]) {
  56711. //this._indicesForCamera.splice(index, 1);
  56712. this._cameras[cameraName] = null;
  56713. }
  56714. for (var passName in this._renderPasses) {
  56715. this._renderPasses[passName]._decRefCount();
  56716. }
  56717. }
  56718. };
  56719. PostProcessRenderEffect.prototype._enable = function (cameras) {
  56720. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56721. if (!cams) {
  56722. return;
  56723. }
  56724. for (var i = 0; i < cams.length; i++) {
  56725. var camera = cams[i];
  56726. var cameraName = camera.name;
  56727. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  56728. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  56729. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  56730. }
  56731. }
  56732. for (var passName in this._renderPasses) {
  56733. this._renderPasses[passName]._incRefCount();
  56734. }
  56735. }
  56736. };
  56737. PostProcessRenderEffect.prototype._disable = function (cameras) {
  56738. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56739. if (!cams) {
  56740. return;
  56741. }
  56742. for (var i = 0; i < cams.length; i++) {
  56743. var camera = cams[i];
  56744. var cameraName = camera.Name;
  56745. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56746. for (var passName in this._renderPasses) {
  56747. this._renderPasses[passName]._decRefCount();
  56748. }
  56749. }
  56750. };
  56751. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  56752. if (this._singleInstance) {
  56753. return this._postProcesses[0];
  56754. }
  56755. else {
  56756. if (!camera) {
  56757. return null;
  56758. }
  56759. return this._postProcesses[camera.name];
  56760. }
  56761. };
  56762. PostProcessRenderEffect.prototype._linkParameters = function () {
  56763. var _this = this;
  56764. for (var index in this._postProcesses) {
  56765. if (this.applyParameters) {
  56766. this.applyParameters(this._postProcesses[index]);
  56767. }
  56768. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  56769. _this._linkTextures(effect);
  56770. });
  56771. }
  56772. };
  56773. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  56774. for (var renderPassName in this._renderPasses) {
  56775. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  56776. }
  56777. for (var renderEffectName in this._renderEffectAsPasses) {
  56778. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  56779. }
  56780. };
  56781. return PostProcessRenderEffect;
  56782. }());
  56783. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  56784. })(BABYLON || (BABYLON = {}));
  56785. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  56786. var BABYLON;
  56787. (function (BABYLON) {
  56788. var PostProcessRenderPipeline = /** @class */ (function () {
  56789. function PostProcessRenderPipeline(engine, name) {
  56790. this._engine = engine;
  56791. this._name = name;
  56792. this._renderEffects = {};
  56793. this._renderEffectsForIsolatedPass = new Array();
  56794. this._cameras = [];
  56795. }
  56796. PostProcessRenderPipeline.prototype.getClassName = function () {
  56797. return "PostProcessRenderPipeline";
  56798. };
  56799. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  56800. get: function () {
  56801. for (var renderEffectName in this._renderEffects) {
  56802. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56803. if (!this._renderEffects[renderEffectName].isSupported) {
  56804. return false;
  56805. }
  56806. }
  56807. }
  56808. return true;
  56809. },
  56810. enumerable: true,
  56811. configurable: true
  56812. });
  56813. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  56814. this._renderEffects[renderEffect._name] = renderEffect;
  56815. };
  56816. // private
  56817. PostProcessRenderPipeline.prototype._rebuild = function () {
  56818. };
  56819. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  56820. var renderEffects = this._renderEffects[renderEffectName];
  56821. if (!renderEffects) {
  56822. return;
  56823. }
  56824. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56825. };
  56826. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  56827. var renderEffects = this._renderEffects[renderEffectName];
  56828. if (!renderEffects) {
  56829. return;
  56830. }
  56831. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56832. };
  56833. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  56834. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56835. if (!cams) {
  56836. return;
  56837. }
  56838. var indicesToDelete = [];
  56839. var i;
  56840. for (i = 0; i < cams.length; i++) {
  56841. var camera = cams[i];
  56842. var cameraName = camera.name;
  56843. if (this._cameras.indexOf(camera) === -1) {
  56844. this._cameras[cameraName] = camera;
  56845. }
  56846. else if (unique) {
  56847. indicesToDelete.push(i);
  56848. }
  56849. }
  56850. for (i = 0; i < indicesToDelete.length; i++) {
  56851. cameras.splice(indicesToDelete[i], 1);
  56852. }
  56853. for (var renderEffectName in this._renderEffects) {
  56854. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56855. this._renderEffects[renderEffectName]._attachCameras(cams);
  56856. }
  56857. }
  56858. };
  56859. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  56860. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56861. if (!cams) {
  56862. return;
  56863. }
  56864. for (var renderEffectName in this._renderEffects) {
  56865. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56866. this._renderEffects[renderEffectName]._detachCameras(cams);
  56867. }
  56868. }
  56869. for (var i = 0; i < cams.length; i++) {
  56870. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  56871. }
  56872. };
  56873. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  56874. var _this = this;
  56875. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56876. if (!cams) {
  56877. return;
  56878. }
  56879. var pass = null;
  56880. var renderEffectName;
  56881. for (renderEffectName in this._renderEffects) {
  56882. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56883. pass = this._renderEffects[renderEffectName].getPass(passName);
  56884. if (pass != null) {
  56885. break;
  56886. }
  56887. }
  56888. }
  56889. if (pass === null) {
  56890. return;
  56891. }
  56892. for (renderEffectName in this._renderEffects) {
  56893. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56894. this._renderEffects[renderEffectName]._disable(cams);
  56895. }
  56896. }
  56897. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  56898. for (var i = 0; i < cams.length; i++) {
  56899. var camera = cams[i];
  56900. var cameraName = camera.name;
  56901. 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); });
  56902. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  56903. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  56904. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  56905. }
  56906. };
  56907. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  56908. var _this = this;
  56909. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56910. if (!cams) {
  56911. return;
  56912. }
  56913. for (var i = 0; i < cams.length; i++) {
  56914. var camera = cams[i];
  56915. var cameraName = camera.name;
  56916. 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); });
  56917. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  56918. }
  56919. for (var renderEffectName in this._renderEffects) {
  56920. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56921. this._renderEffects[renderEffectName]._enable(cams);
  56922. }
  56923. }
  56924. };
  56925. PostProcessRenderPipeline.prototype._update = function () {
  56926. for (var renderEffectName in this._renderEffects) {
  56927. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56928. this._renderEffects[renderEffectName]._update();
  56929. }
  56930. }
  56931. for (var i = 0; i < this._cameras.length; i++) {
  56932. var cameraName = this._cameras[i].name;
  56933. if (this._renderEffectsForIsolatedPass[cameraName]) {
  56934. this._renderEffectsForIsolatedPass[cameraName]._update();
  56935. }
  56936. }
  56937. };
  56938. PostProcessRenderPipeline.prototype._reset = function () {
  56939. this._renderEffects = {};
  56940. this._renderEffectsForIsolatedPass = new Array();
  56941. };
  56942. PostProcessRenderPipeline.prototype.dispose = function () {
  56943. // Must be implemented by children
  56944. };
  56945. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  56946. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  56947. __decorate([
  56948. BABYLON.serialize()
  56949. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  56950. return PostProcessRenderPipeline;
  56951. }());
  56952. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  56953. })(BABYLON || (BABYLON = {}));
  56954. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  56955. var BABYLON;
  56956. (function (BABYLON) {
  56957. var DepthRenderer = /** @class */ (function () {
  56958. function DepthRenderer(scene, type) {
  56959. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  56960. var _this = this;
  56961. this._scene = scene;
  56962. var engine = scene.getEngine();
  56963. // Render target
  56964. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  56965. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56966. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56967. this._depthMap.refreshRate = 1;
  56968. this._depthMap.renderParticles = false;
  56969. this._depthMap.renderList = null;
  56970. // set default depth value to 1.0 (far away)
  56971. this._depthMap.onClearObservable.add(function (engine) {
  56972. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56973. });
  56974. // Custom render function
  56975. var renderSubMesh = function (subMesh) {
  56976. var mesh = subMesh.getRenderingMesh();
  56977. var scene = _this._scene;
  56978. var engine = scene.getEngine();
  56979. var material = subMesh.getMaterial();
  56980. if (!material) {
  56981. return;
  56982. }
  56983. // Culling
  56984. engine.setState(material.backFaceCulling);
  56985. // Managing instances
  56986. var batch = mesh._getInstancesRenderList(subMesh._id);
  56987. if (batch.mustReturn) {
  56988. return;
  56989. }
  56990. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  56991. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  56992. engine.enableEffect(_this._effect);
  56993. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  56994. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  56995. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  56996. // Alpha test
  56997. if (material && material.needAlphaTesting()) {
  56998. var alphaTexture = material.getAlphaTestTexture();
  56999. if (alphaTexture) {
  57000. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57001. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57002. }
  57003. }
  57004. // Bones
  57005. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57006. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57007. }
  57008. // Draw
  57009. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57010. }
  57011. };
  57012. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57013. var index;
  57014. if (depthOnlySubMeshes.length) {
  57015. engine.setColorWrite(false);
  57016. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57017. renderSubMesh(depthOnlySubMeshes.data[index]);
  57018. }
  57019. engine.setColorWrite(true);
  57020. }
  57021. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57022. renderSubMesh(opaqueSubMeshes.data[index]);
  57023. }
  57024. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57025. renderSubMesh(alphaTestSubMeshes.data[index]);
  57026. }
  57027. };
  57028. }
  57029. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  57030. var material = subMesh.getMaterial();
  57031. if (material.disableDepthWrite) {
  57032. return false;
  57033. }
  57034. var defines = [];
  57035. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57036. var mesh = subMesh.getMesh();
  57037. // Alpha test
  57038. if (material && material.needAlphaTesting()) {
  57039. defines.push("#define ALPHATEST");
  57040. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57041. attribs.push(BABYLON.VertexBuffer.UVKind);
  57042. defines.push("#define UV1");
  57043. }
  57044. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57045. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57046. defines.push("#define UV2");
  57047. }
  57048. }
  57049. // Bones
  57050. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57051. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57052. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57053. if (mesh.numBoneInfluencers > 4) {
  57054. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57055. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57056. }
  57057. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57058. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  57059. }
  57060. else {
  57061. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57062. }
  57063. // Instances
  57064. if (useInstances) {
  57065. defines.push("#define INSTANCES");
  57066. attribs.push("world0");
  57067. attribs.push("world1");
  57068. attribs.push("world2");
  57069. attribs.push("world3");
  57070. }
  57071. // Get correct effect
  57072. var join = defines.join("\n");
  57073. if (this._cachedDefines !== join) {
  57074. this._cachedDefines = join;
  57075. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  57076. }
  57077. return this._effect.isReady();
  57078. };
  57079. DepthRenderer.prototype.getDepthMap = function () {
  57080. return this._depthMap;
  57081. };
  57082. // Methods
  57083. DepthRenderer.prototype.dispose = function () {
  57084. this._depthMap.dispose();
  57085. };
  57086. return DepthRenderer;
  57087. }());
  57088. BABYLON.DepthRenderer = DepthRenderer;
  57089. })(BABYLON || (BABYLON = {}));
  57090. //# sourceMappingURL=babylon.depthRenderer.js.map
  57091. var BABYLON;
  57092. (function (BABYLON) {
  57093. var SSAORenderingPipeline = /** @class */ (function (_super) {
  57094. __extends(SSAORenderingPipeline, _super);
  57095. /**
  57096. * @constructor
  57097. * @param {string} name - The rendering pipeline name
  57098. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57099. * @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 }
  57100. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57101. */
  57102. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  57103. var _this = _super.call(this, scene.getEngine(), name) || this;
  57104. // Members
  57105. /**
  57106. * The PassPostProcess id in the pipeline that contains the original scene color
  57107. * @type {string}
  57108. */
  57109. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57110. /**
  57111. * The SSAO PostProcess id in the pipeline
  57112. * @type {string}
  57113. */
  57114. _this.SSAORenderEffect = "SSAORenderEffect";
  57115. /**
  57116. * The horizontal blur PostProcess id in the pipeline
  57117. * @type {string}
  57118. */
  57119. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57120. /**
  57121. * The vertical blur PostProcess id in the pipeline
  57122. * @type {string}
  57123. */
  57124. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57125. /**
  57126. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57127. * @type {string}
  57128. */
  57129. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57130. /**
  57131. * The output strength of the SSAO post-process. Default value is 1.0.
  57132. * @type {number}
  57133. */
  57134. _this.totalStrength = 1.0;
  57135. /**
  57136. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  57137. * @type {number}
  57138. */
  57139. _this.radius = 0.0001;
  57140. /**
  57141. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  57142. * Must not be equal to fallOff and superior to fallOff.
  57143. * Default value is 0.975
  57144. * @type {number}
  57145. */
  57146. _this.area = 0.0075;
  57147. /**
  57148. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  57149. * Must not be equal to area and inferior to area.
  57150. * Default value is 0.0
  57151. * @type {number}
  57152. */
  57153. _this.fallOff = 0.000001;
  57154. /**
  57155. * The base color of the SSAO post-process
  57156. * The final result is "base + ssao" between [0, 1]
  57157. * @type {number}
  57158. */
  57159. _this.base = 0.5;
  57160. _this._firstUpdate = true;
  57161. _this._scene = scene;
  57162. // Set up assets
  57163. _this._createRandomTexture();
  57164. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57165. var ssaoRatio = ratio.ssaoRatio || ratio;
  57166. var combineRatio = ratio.combineRatio || ratio;
  57167. _this._ratio = {
  57168. ssaoRatio: ssaoRatio,
  57169. combineRatio: combineRatio
  57170. };
  57171. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57172. _this._createSSAOPostProcess(ssaoRatio);
  57173. _this._createBlurPostProcess(ssaoRatio);
  57174. _this._createSSAOCombinePostProcess(combineRatio);
  57175. // Set up pipeline
  57176. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57177. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57178. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57179. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57180. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57181. // Finish
  57182. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57183. if (cameras)
  57184. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57185. return _this;
  57186. }
  57187. // Public Methods
  57188. /**
  57189. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57190. */
  57191. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57192. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57193. for (var i = 0; i < this._scene.cameras.length; i++) {
  57194. var camera = this._scene.cameras[i];
  57195. this._originalColorPostProcess.dispose(camera);
  57196. this._ssaoPostProcess.dispose(camera);
  57197. this._blurHPostProcess.dispose(camera);
  57198. this._blurVPostProcess.dispose(camera);
  57199. this._ssaoCombinePostProcess.dispose(camera);
  57200. }
  57201. this._randomTexture.dispose();
  57202. if (disableDepthRender)
  57203. this._scene.disableDepthRenderer();
  57204. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57205. _super.prototype.dispose.call(this);
  57206. };
  57207. // Private Methods
  57208. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57209. var _this = this;
  57210. /*
  57211. var samplerOffsets = [
  57212. -8.0, -6.0, -4.0, -2.0,
  57213. 0.0,
  57214. 2.0, 4.0, 6.0, 8.0
  57215. ];
  57216. */
  57217. var samplerOffsets = new Array();
  57218. for (var i = -8; i < 8; i++) {
  57219. samplerOffsets.push(i * 2);
  57220. }
  57221. 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");
  57222. this._blurHPostProcess.onApply = function (effect) {
  57223. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57224. effect.setTexture("depthSampler", _this._depthTexture);
  57225. if (_this._firstUpdate) {
  57226. effect.setArray("samplerOffsets", samplerOffsets);
  57227. }
  57228. };
  57229. 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");
  57230. this._blurVPostProcess.onApply = function (effect) {
  57231. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57232. effect.setTexture("depthSampler", _this._depthTexture);
  57233. if (_this._firstUpdate) {
  57234. effect.setArray("samplerOffsets", samplerOffsets);
  57235. _this._firstUpdate = false;
  57236. }
  57237. };
  57238. };
  57239. SSAORenderingPipeline.prototype._rebuild = function () {
  57240. this._firstUpdate = true;
  57241. _super.prototype._rebuild.call(this);
  57242. };
  57243. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57244. var _this = this;
  57245. var numSamples = 16;
  57246. var sampleSphere = [
  57247. 0.5381, 0.1856, -0.4319,
  57248. 0.1379, 0.2486, 0.4430,
  57249. 0.3371, 0.5679, -0.0057,
  57250. -0.6999, -0.0451, -0.0019,
  57251. 0.0689, -0.1598, -0.8547,
  57252. 0.0560, 0.0069, -0.1843,
  57253. -0.0146, 0.1402, 0.0762,
  57254. 0.0100, -0.1924, -0.0344,
  57255. -0.3577, -0.5301, -0.4358,
  57256. -0.3169, 0.1063, 0.0158,
  57257. 0.0103, -0.5869, 0.0046,
  57258. -0.0897, -0.4940, 0.3287,
  57259. 0.7119, -0.0154, -0.0918,
  57260. -0.0533, 0.0596, -0.5411,
  57261. 0.0352, -0.0631, 0.5460,
  57262. -0.4776, 0.2847, -0.0271
  57263. ];
  57264. var samplesFactor = 1.0 / numSamples;
  57265. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  57266. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57267. "area", "fallOff", "base", "range", "viewport"
  57268. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57269. this._ssaoPostProcess.onApply = function (effect) {
  57270. if (_this._firstUpdate) {
  57271. effect.setArray3("sampleSphere", sampleSphere);
  57272. effect.setFloat("samplesFactor", samplesFactor);
  57273. effect.setFloat("randTextureTiles", 4.0);
  57274. }
  57275. effect.setFloat("totalStrength", _this.totalStrength);
  57276. effect.setFloat("radius", _this.radius);
  57277. effect.setFloat("area", _this.area);
  57278. effect.setFloat("fallOff", _this.fallOff);
  57279. effect.setFloat("base", _this.base);
  57280. effect.setTexture("textureSampler", _this._depthTexture);
  57281. effect.setTexture("randomSampler", _this._randomTexture);
  57282. };
  57283. };
  57284. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57285. var _this = this;
  57286. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57287. this._ssaoCombinePostProcess.onApply = function (effect) {
  57288. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57289. };
  57290. };
  57291. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  57292. var size = 512;
  57293. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57294. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57295. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57296. var context = this._randomTexture.getContext();
  57297. var rand = function (min, max) {
  57298. return Math.random() * (max - min) + min;
  57299. };
  57300. var randVector = BABYLON.Vector3.Zero();
  57301. for (var x = 0; x < size; x++) {
  57302. for (var y = 0; y < size; y++) {
  57303. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  57304. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  57305. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  57306. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57307. context.fillRect(x, y, 1, 1);
  57308. }
  57309. }
  57310. this._randomTexture.update(false);
  57311. };
  57312. __decorate([
  57313. BABYLON.serialize()
  57314. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  57315. __decorate([
  57316. BABYLON.serialize()
  57317. ], SSAORenderingPipeline.prototype, "radius", void 0);
  57318. __decorate([
  57319. BABYLON.serialize()
  57320. ], SSAORenderingPipeline.prototype, "area", void 0);
  57321. __decorate([
  57322. BABYLON.serialize()
  57323. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  57324. __decorate([
  57325. BABYLON.serialize()
  57326. ], SSAORenderingPipeline.prototype, "base", void 0);
  57327. __decorate([
  57328. BABYLON.serialize()
  57329. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  57330. return SSAORenderingPipeline;
  57331. }(BABYLON.PostProcessRenderPipeline));
  57332. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  57333. })(BABYLON || (BABYLON = {}));
  57334. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  57335. var BABYLON;
  57336. (function (BABYLON) {
  57337. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  57338. __extends(SSAO2RenderingPipeline, _super);
  57339. /**
  57340. * @constructor
  57341. * @param {string} name - The rendering pipeline name
  57342. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57343. * @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 }
  57344. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57345. */
  57346. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  57347. var _this = _super.call(this, scene.getEngine(), name) || this;
  57348. // Members
  57349. /**
  57350. * The PassPostProcess id in the pipeline that contains the original scene color
  57351. * @type {string}
  57352. */
  57353. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57354. /**
  57355. * The SSAO PostProcess id in the pipeline
  57356. * @type {string}
  57357. */
  57358. _this.SSAORenderEffect = "SSAORenderEffect";
  57359. /**
  57360. * The horizontal blur PostProcess id in the pipeline
  57361. * @type {string}
  57362. */
  57363. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57364. /**
  57365. * The vertical blur PostProcess id in the pipeline
  57366. * @type {string}
  57367. */
  57368. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57369. /**
  57370. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57371. * @type {string}
  57372. */
  57373. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57374. /**
  57375. * The output strength of the SSAO post-process. Default value is 1.0.
  57376. * @type {number}
  57377. */
  57378. _this.totalStrength = 1.0;
  57379. /**
  57380. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  57381. * @type {number}
  57382. */
  57383. _this.maxZ = 100.0;
  57384. /**
  57385. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  57386. * @type {number}
  57387. */
  57388. _this.minZAspect = 0.2;
  57389. /**
  57390. * Number of samples used for the SSAO calculations. Default value is 8
  57391. * @type {number}
  57392. */
  57393. _this._samples = 8;
  57394. /**
  57395. * Are we using bilateral blur ?
  57396. * @type {boolean}
  57397. */
  57398. _this._expensiveBlur = true;
  57399. /**
  57400. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  57401. * @type {number}
  57402. */
  57403. _this.radius = 2.0;
  57404. /**
  57405. * The base color of the SSAO post-process
  57406. * The final result is "base + ssao" between [0, 1]
  57407. * @type {number}
  57408. */
  57409. _this.base = 0.1;
  57410. _this._firstUpdate = true;
  57411. _this._scene = scene;
  57412. if (!_this.isSupported) {
  57413. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  57414. return _this;
  57415. }
  57416. var ssaoRatio = ratio.ssaoRatio || ratio;
  57417. var blurRatio = ratio.blurRatio || ratio;
  57418. _this._ratio = {
  57419. ssaoRatio: ssaoRatio,
  57420. blurRatio: blurRatio
  57421. };
  57422. // Set up assets
  57423. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  57424. _this._createRandomTexture();
  57425. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  57426. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  57427. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57428. _this._createSSAOPostProcess(1.0);
  57429. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  57430. _this._createSSAOCombinePostProcess(blurRatio);
  57431. // Set up pipeline
  57432. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57433. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57434. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57435. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57436. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57437. // Finish
  57438. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57439. if (cameras)
  57440. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57441. return _this;
  57442. }
  57443. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  57444. get: function () {
  57445. return this._samples;
  57446. },
  57447. set: function (n) {
  57448. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  57449. this._samples = n;
  57450. this._sampleSphere = this._generateHemisphere();
  57451. this._firstUpdate = true;
  57452. },
  57453. enumerable: true,
  57454. configurable: true
  57455. });
  57456. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  57457. get: function () {
  57458. return this._expensiveBlur;
  57459. },
  57460. set: function (b) {
  57461. 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"]);
  57462. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  57463. this._expensiveBlur = b;
  57464. this._firstUpdate = true;
  57465. },
  57466. enumerable: true,
  57467. configurable: true
  57468. });
  57469. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  57470. /**
  57471. * Support test.
  57472. * @type {boolean}
  57473. */
  57474. get: function () {
  57475. var engine = BABYLON.Engine.LastCreatedEngine;
  57476. if (!engine) {
  57477. return false;
  57478. }
  57479. return engine.getCaps().drawBuffersExtension;
  57480. },
  57481. enumerable: true,
  57482. configurable: true
  57483. });
  57484. // Public Methods
  57485. /**
  57486. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57487. */
  57488. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  57489. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  57490. for (var i = 0; i < this._scene.cameras.length; i++) {
  57491. var camera = this._scene.cameras[i];
  57492. this._originalColorPostProcess.dispose(camera);
  57493. this._ssaoPostProcess.dispose(camera);
  57494. this._blurHPostProcess.dispose(camera);
  57495. this._blurVPostProcess.dispose(camera);
  57496. this._ssaoCombinePostProcess.dispose(camera);
  57497. }
  57498. this._randomTexture.dispose();
  57499. if (disableGeometryBufferRenderer)
  57500. this._scene.disableGeometryBufferRenderer();
  57501. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57502. _super.prototype.dispose.call(this);
  57503. };
  57504. // Private Methods
  57505. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  57506. var _this = this;
  57507. this._samplerOffsets = [];
  57508. var expensive = this.expensiveBlur;
  57509. for (var i = -8; i < 8; i++) {
  57510. this._samplerOffsets.push(i * 2 + 0.5);
  57511. }
  57512. 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");
  57513. this._blurHPostProcess.onApply = function (effect) {
  57514. if (!_this._scene.activeCamera) {
  57515. return;
  57516. }
  57517. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57518. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57519. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57520. effect.setFloat("radius", _this.radius);
  57521. effect.setTexture("depthSampler", _this._depthTexture);
  57522. if (_this._firstUpdate) {
  57523. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57524. }
  57525. };
  57526. 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");
  57527. this._blurVPostProcess.onApply = function (effect) {
  57528. if (!_this._scene.activeCamera) {
  57529. return;
  57530. }
  57531. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57532. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57533. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57534. effect.setFloat("radius", _this.radius);
  57535. effect.setTexture("depthSampler", _this._depthTexture);
  57536. if (_this._firstUpdate) {
  57537. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57538. _this._firstUpdate = false;
  57539. }
  57540. };
  57541. };
  57542. SSAO2RenderingPipeline.prototype._rebuild = function () {
  57543. this._firstUpdate = true;
  57544. _super.prototype._rebuild.call(this);
  57545. };
  57546. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  57547. var numSamples = this.samples;
  57548. var result = [];
  57549. var vector, scale;
  57550. var rand = function (min, max) {
  57551. return Math.random() * (max - min) + min;
  57552. };
  57553. var i = 0;
  57554. while (i < numSamples) {
  57555. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  57556. vector.normalize();
  57557. scale = i / numSamples;
  57558. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  57559. vector.scaleInPlace(scale);
  57560. result.push(vector.x, vector.y, vector.z);
  57561. i++;
  57562. }
  57563. return result;
  57564. };
  57565. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57566. var _this = this;
  57567. var numSamples = this.samples;
  57568. this._sampleSphere = this._generateHemisphere();
  57569. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  57570. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57571. "base", "range", "projection", "near", "far", "texelSize",
  57572. "xViewport", "yViewport", "maxZ", "minZAspect"
  57573. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57574. this._ssaoPostProcess.onApply = function (effect) {
  57575. if (_this._firstUpdate) {
  57576. effect.setArray3("sampleSphere", _this._sampleSphere);
  57577. effect.setFloat("randTextureTiles", 4.0);
  57578. }
  57579. if (!_this._scene.activeCamera) {
  57580. return;
  57581. }
  57582. effect.setFloat("samplesFactor", 1 / _this.samples);
  57583. effect.setFloat("totalStrength", _this.totalStrength);
  57584. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  57585. effect.setFloat("radius", _this.radius);
  57586. effect.setFloat("maxZ", _this.maxZ);
  57587. effect.setFloat("minZAspect", _this.minZAspect);
  57588. effect.setFloat("base", _this.base);
  57589. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57590. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57591. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  57592. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  57593. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  57594. effect.setTexture("textureSampler", _this._depthTexture);
  57595. effect.setTexture("normalSampler", _this._normalTexture);
  57596. effect.setTexture("randomSampler", _this._randomTexture);
  57597. };
  57598. };
  57599. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57600. var _this = this;
  57601. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57602. this._ssaoCombinePostProcess.onApply = function (effect) {
  57603. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57604. };
  57605. };
  57606. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  57607. var size = 512;
  57608. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57609. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57610. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57611. var context = this._randomTexture.getContext();
  57612. var rand = function (min, max) {
  57613. return Math.random() * (max - min) + min;
  57614. };
  57615. var randVector = BABYLON.Vector3.Zero();
  57616. for (var x = 0; x < size; x++) {
  57617. for (var y = 0; y < size; y++) {
  57618. randVector.x = rand(0.0, 1.0);
  57619. randVector.y = rand(0.0, 1.0);
  57620. randVector.z = 0.0;
  57621. randVector.normalize();
  57622. randVector.scaleInPlace(255);
  57623. randVector.x = Math.floor(randVector.x);
  57624. randVector.y = Math.floor(randVector.y);
  57625. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57626. context.fillRect(x, y, 1, 1);
  57627. }
  57628. }
  57629. this._randomTexture.update(false);
  57630. };
  57631. __decorate([
  57632. BABYLON.serialize()
  57633. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  57634. __decorate([
  57635. BABYLON.serialize()
  57636. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  57637. __decorate([
  57638. BABYLON.serialize()
  57639. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  57640. __decorate([
  57641. BABYLON.serialize("samples")
  57642. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  57643. __decorate([
  57644. BABYLON.serialize("expensiveBlur")
  57645. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  57646. __decorate([
  57647. BABYLON.serialize()
  57648. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  57649. __decorate([
  57650. BABYLON.serialize()
  57651. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  57652. __decorate([
  57653. BABYLON.serialize()
  57654. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  57655. return SSAO2RenderingPipeline;
  57656. }(BABYLON.PostProcessRenderPipeline));
  57657. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  57658. })(BABYLON || (BABYLON = {}));
  57659. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  57660. // BABYLON.JS Chromatic Aberration GLSL Shader
  57661. // Author: Olivier Guyot
  57662. // Separates very slightly R, G and B colors on the edges of the screen
  57663. // Inspired by Francois Tarlier & Martins Upitis
  57664. var BABYLON;
  57665. (function (BABYLON) {
  57666. var LensRenderingPipeline = /** @class */ (function (_super) {
  57667. __extends(LensRenderingPipeline, _super);
  57668. /**
  57669. * @constructor
  57670. *
  57671. * Effect parameters are as follow:
  57672. * {
  57673. * chromatic_aberration: number; // from 0 to x (1 for realism)
  57674. * edge_blur: number; // from 0 to x (1 for realism)
  57675. * distortion: number; // from 0 to x (1 for realism)
  57676. * grain_amount: number; // from 0 to 1
  57677. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  57678. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  57679. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  57680. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  57681. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  57682. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  57683. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  57684. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  57685. * }
  57686. * Note: if an effect parameter is unset, effect is disabled
  57687. *
  57688. * @param {string} name - The rendering pipeline name
  57689. * @param {object} parameters - An object containing all parameters (see above)
  57690. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57691. * @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)
  57692. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57693. */
  57694. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  57695. if (ratio === void 0) { ratio = 1.0; }
  57696. var _this = _super.call(this, scene.getEngine(), name) || this;
  57697. // Lens effects can be of the following:
  57698. // - chromatic aberration (slight shift of RGB colors)
  57699. // - blur on the edge of the lens
  57700. // - lens distortion
  57701. // - depth-of-field blur & highlights enhancing
  57702. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  57703. // - grain effect (noise or custom texture)
  57704. // Two additional texture samplers are needed:
  57705. // - depth map (for depth-of-field)
  57706. // - grain texture
  57707. /**
  57708. * The chromatic aberration PostProcess id in the pipeline
  57709. * @type {string}
  57710. */
  57711. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  57712. /**
  57713. * The highlights enhancing PostProcess id in the pipeline
  57714. * @type {string}
  57715. */
  57716. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  57717. /**
  57718. * The depth-of-field PostProcess id in the pipeline
  57719. * @type {string}
  57720. */
  57721. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  57722. _this._scene = scene;
  57723. // Fetch texture samplers
  57724. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57725. if (parameters.grain_texture) {
  57726. _this._grainTexture = parameters.grain_texture;
  57727. }
  57728. else {
  57729. _this._createGrainTexture();
  57730. }
  57731. // save parameters
  57732. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  57733. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  57734. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  57735. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  57736. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  57737. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  57738. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  57739. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  57740. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  57741. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  57742. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  57743. // Create effects
  57744. _this._createChromaticAberrationPostProcess(ratio);
  57745. _this._createHighlightsPostProcess(ratio);
  57746. _this._createDepthOfFieldPostProcess(ratio / 4);
  57747. // Set up pipeline
  57748. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  57749. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  57750. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  57751. if (_this._highlightsGain === -1) {
  57752. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  57753. }
  57754. // Finish
  57755. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57756. if (cameras) {
  57757. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57758. }
  57759. return _this;
  57760. }
  57761. // public methods (self explanatory)
  57762. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  57763. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  57764. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  57765. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  57766. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  57767. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  57768. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  57769. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  57770. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  57771. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  57772. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  57773. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  57774. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  57775. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  57776. };
  57777. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  57778. this._highlightsPostProcess.updateEffect();
  57779. };
  57780. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  57781. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  57782. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  57783. this._highlightsGain = amount;
  57784. };
  57785. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  57786. if (this._highlightsGain === -1) {
  57787. this._highlightsGain = 1.0;
  57788. }
  57789. this._highlightsThreshold = amount;
  57790. };
  57791. LensRenderingPipeline.prototype.disableHighlights = function () {
  57792. this._highlightsGain = -1;
  57793. };
  57794. /**
  57795. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  57796. */
  57797. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57798. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57799. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57800. this._chromaticAberrationPostProcess = null;
  57801. this._highlightsPostProcess = null;
  57802. this._depthOfFieldPostProcess = null;
  57803. this._grainTexture.dispose();
  57804. if (disableDepthRender)
  57805. this._scene.disableDepthRenderer();
  57806. };
  57807. // colors shifting and distortion
  57808. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  57809. var _this = this;
  57810. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  57811. [], // samplers
  57812. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57813. this._chromaticAberrationPostProcess.onApply = function (effect) {
  57814. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  57815. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57816. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57817. };
  57818. };
  57819. // highlights enhancing
  57820. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  57821. var _this = this;
  57822. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  57823. [], // samplers
  57824. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  57825. this._highlightsPostProcess.onApply = function (effect) {
  57826. effect.setFloat('gain', _this._highlightsGain);
  57827. effect.setFloat('threshold', _this._highlightsThreshold);
  57828. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  57829. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57830. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57831. };
  57832. };
  57833. // colors shifting and distortion
  57834. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  57835. var _this = this;
  57836. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  57837. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  57838. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  57839. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57840. this._depthOfFieldPostProcess.onApply = function (effect) {
  57841. effect.setTexture("depthSampler", _this._depthTexture);
  57842. effect.setTexture("grainSampler", _this._grainTexture);
  57843. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  57844. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  57845. effect.setFloat('grain_amount', _this._grainAmount);
  57846. effect.setBool('blur_noise', _this._blurNoise);
  57847. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57848. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57849. effect.setFloat('distortion', _this._distortion);
  57850. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  57851. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  57852. effect.setFloat('aperture', _this._dofAperture);
  57853. effect.setFloat('darken', _this._dofDarken);
  57854. effect.setFloat('edge_blur', _this._edgeBlur);
  57855. effect.setBool('highlights', (_this._highlightsGain !== -1));
  57856. if (_this._scene.activeCamera) {
  57857. effect.setFloat('near', _this._scene.activeCamera.minZ);
  57858. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  57859. }
  57860. };
  57861. };
  57862. // creates a black and white random noise texture, 512x512
  57863. LensRenderingPipeline.prototype._createGrainTexture = function () {
  57864. var size = 512;
  57865. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57866. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57867. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57868. var context = this._grainTexture.getContext();
  57869. var rand = function (min, max) {
  57870. return Math.random() * (max - min) + min;
  57871. };
  57872. var value;
  57873. for (var x = 0; x < size; x++) {
  57874. for (var y = 0; y < size; y++) {
  57875. value = Math.floor(rand(0.42, 0.58) * 255);
  57876. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  57877. context.fillRect(x, y, 1, 1);
  57878. }
  57879. }
  57880. this._grainTexture.update(false);
  57881. };
  57882. return LensRenderingPipeline;
  57883. }(BABYLON.PostProcessRenderPipeline));
  57884. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  57885. })(BABYLON || (BABYLON = {}));
  57886. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  57887. var BABYLON;
  57888. (function (BABYLON) {
  57889. var StandardRenderingPipeline = /** @class */ (function (_super) {
  57890. __extends(StandardRenderingPipeline, _super);
  57891. /**
  57892. * @constructor
  57893. * @param {string} name - The rendering pipeline name
  57894. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57895. * @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)
  57896. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  57897. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57898. */
  57899. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  57900. if (originalPostProcess === void 0) { originalPostProcess = null; }
  57901. var _this = _super.call(this, scene.getEngine(), name) || this;
  57902. _this.downSampleX4PostProcess = null;
  57903. _this.brightPassPostProcess = null;
  57904. _this.blurHPostProcesses = [];
  57905. _this.blurVPostProcesses = [];
  57906. _this.textureAdderPostProcess = null;
  57907. _this.volumetricLightPostProcess = null;
  57908. _this.volumetricLightSmoothXPostProcess = null;
  57909. _this.volumetricLightSmoothYPostProcess = null;
  57910. _this.volumetricLightMergePostProces = null;
  57911. _this.volumetricLightFinalPostProcess = null;
  57912. _this.luminancePostProcess = null;
  57913. _this.luminanceDownSamplePostProcesses = [];
  57914. _this.hdrPostProcess = null;
  57915. _this.textureAdderFinalPostProcess = null;
  57916. _this.lensFlareFinalPostProcess = null;
  57917. _this.hdrFinalPostProcess = null;
  57918. _this.lensFlarePostProcess = null;
  57919. _this.lensFlareComposePostProcess = null;
  57920. _this.motionBlurPostProcess = null;
  57921. _this.depthOfFieldPostProcess = null;
  57922. // Values
  57923. _this.brightThreshold = 1.0;
  57924. _this.blurWidth = 512.0;
  57925. _this.horizontalBlur = false;
  57926. _this.exposure = 1.0;
  57927. _this.lensTexture = null;
  57928. _this.volumetricLightCoefficient = 0.2;
  57929. _this.volumetricLightPower = 4.0;
  57930. _this.volumetricLightBlurScale = 64.0;
  57931. _this.sourceLight = null;
  57932. _this.hdrMinimumLuminance = 1.0;
  57933. _this.hdrDecreaseRate = 0.5;
  57934. _this.hdrIncreaseRate = 0.5;
  57935. _this.lensColorTexture = null;
  57936. _this.lensFlareStrength = 20.0;
  57937. _this.lensFlareGhostDispersal = 1.4;
  57938. _this.lensFlareHaloWidth = 0.7;
  57939. _this.lensFlareDistortionStrength = 16.0;
  57940. _this.lensStarTexture = null;
  57941. _this.lensFlareDirtTexture = null;
  57942. _this.depthOfFieldDistance = 10.0;
  57943. _this.depthOfFieldBlurWidth = 64.0;
  57944. _this.motionStrength = 1.0;
  57945. // IAnimatable
  57946. _this.animations = [];
  57947. _this._currentDepthOfFieldSource = null;
  57948. _this._hdrCurrentLuminance = 1.0;
  57949. // Getters and setters
  57950. _this._bloomEnabled = true;
  57951. _this._depthOfFieldEnabled = false;
  57952. _this._vlsEnabled = false;
  57953. _this._lensFlareEnabled = false;
  57954. _this._hdrEnabled = false;
  57955. _this._motionBlurEnabled = false;
  57956. _this._motionBlurSamples = 64.0;
  57957. _this._volumetricLightStepsCount = 50.0;
  57958. _this._cameras = cameras || [];
  57959. // Initialize
  57960. _this._scene = scene;
  57961. _this._basePostProcess = originalPostProcess;
  57962. _this._ratio = ratio;
  57963. // Misc
  57964. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57965. // Finish
  57966. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57967. _this._buildPipeline();
  57968. return _this;
  57969. }
  57970. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  57971. get: function () {
  57972. return this._bloomEnabled;
  57973. },
  57974. set: function (enabled) {
  57975. if (this._bloomEnabled === enabled) {
  57976. return;
  57977. }
  57978. this._bloomEnabled = enabled;
  57979. this._buildPipeline();
  57980. },
  57981. enumerable: true,
  57982. configurable: true
  57983. });
  57984. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  57985. get: function () {
  57986. return this._depthOfFieldEnabled;
  57987. },
  57988. set: function (enabled) {
  57989. if (this._depthOfFieldEnabled === enabled) {
  57990. return;
  57991. }
  57992. this._depthOfFieldEnabled = enabled;
  57993. this._buildPipeline();
  57994. },
  57995. enumerable: true,
  57996. configurable: true
  57997. });
  57998. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  57999. get: function () {
  58000. return this._lensFlareEnabled;
  58001. },
  58002. set: function (enabled) {
  58003. if (this._lensFlareEnabled === enabled) {
  58004. return;
  58005. }
  58006. this._lensFlareEnabled = enabled;
  58007. this._buildPipeline();
  58008. },
  58009. enumerable: true,
  58010. configurable: true
  58011. });
  58012. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  58013. get: function () {
  58014. return this._hdrEnabled;
  58015. },
  58016. set: function (enabled) {
  58017. if (this._hdrEnabled === enabled) {
  58018. return;
  58019. }
  58020. this._hdrEnabled = enabled;
  58021. this._buildPipeline();
  58022. },
  58023. enumerable: true,
  58024. configurable: true
  58025. });
  58026. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  58027. get: function () {
  58028. return this._vlsEnabled;
  58029. },
  58030. set: function (enabled) {
  58031. if (this._vlsEnabled === enabled) {
  58032. return;
  58033. }
  58034. if (enabled) {
  58035. var geometry = this._scene.enableGeometryBufferRenderer();
  58036. if (!geometry) {
  58037. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  58038. return;
  58039. }
  58040. }
  58041. this._vlsEnabled = enabled;
  58042. this._buildPipeline();
  58043. },
  58044. enumerable: true,
  58045. configurable: true
  58046. });
  58047. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  58048. get: function () {
  58049. return this._motionBlurEnabled;
  58050. },
  58051. set: function (enabled) {
  58052. if (this._motionBlurEnabled === enabled) {
  58053. return;
  58054. }
  58055. this._motionBlurEnabled = enabled;
  58056. this._buildPipeline();
  58057. },
  58058. enumerable: true,
  58059. configurable: true
  58060. });
  58061. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  58062. get: function () {
  58063. return this._volumetricLightStepsCount;
  58064. },
  58065. set: function (count) {
  58066. if (this.volumetricLightPostProcess) {
  58067. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  58068. }
  58069. this._volumetricLightStepsCount = count;
  58070. },
  58071. enumerable: true,
  58072. configurable: true
  58073. });
  58074. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  58075. get: function () {
  58076. return this._motionBlurSamples;
  58077. },
  58078. set: function (samples) {
  58079. if (this.motionBlurPostProcess) {
  58080. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  58081. }
  58082. this._motionBlurSamples = samples;
  58083. },
  58084. enumerable: true,
  58085. configurable: true
  58086. });
  58087. StandardRenderingPipeline.prototype._buildPipeline = function () {
  58088. var _this = this;
  58089. var ratio = this._ratio;
  58090. var scene = this._scene;
  58091. this._disposePostProcesses();
  58092. this._reset();
  58093. // Create pass post-process
  58094. if (!this._basePostProcess) {
  58095. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  58096. this.originalPostProcess.onApply = function (effect) {
  58097. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  58098. };
  58099. }
  58100. else {
  58101. this.originalPostProcess = this._basePostProcess;
  58102. }
  58103. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  58104. this._currentDepthOfFieldSource = this.originalPostProcess;
  58105. if (this._vlsEnabled) {
  58106. // Create volumetric light
  58107. this._createVolumetricLightPostProcess(scene, ratio);
  58108. // Create volumetric light final post-process
  58109. 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);
  58110. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  58111. }
  58112. if (this._bloomEnabled) {
  58113. // Create down sample X4 post-process
  58114. this._createDownSampleX4PostProcess(scene, ratio / 2);
  58115. // Create bright pass post-process
  58116. this._createBrightPassPostProcess(scene, ratio / 2);
  58117. // Create gaussian blur post-processes (down sampling blurs)
  58118. this._createBlurPostProcesses(scene, ratio / 4, 1);
  58119. // Create texture adder post-process
  58120. this._createTextureAdderPostProcess(scene, ratio);
  58121. // Create depth-of-field source post-process
  58122. 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);
  58123. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  58124. }
  58125. if (this._lensFlareEnabled) {
  58126. // Create lens flare post-process
  58127. this._createLensFlarePostProcess(scene, ratio);
  58128. // Create depth-of-field source post-process post lens-flare and disable it now
  58129. 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);
  58130. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  58131. }
  58132. if (this._hdrEnabled) {
  58133. // Create luminance
  58134. this._createLuminancePostProcesses(scene, this._floatTextureType);
  58135. // Create HDR
  58136. this._createHdrPostProcess(scene, ratio);
  58137. // Create depth-of-field source post-process post hdr and disable it now
  58138. 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);
  58139. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  58140. }
  58141. if (this._depthOfFieldEnabled) {
  58142. // Create gaussian blur used by depth-of-field
  58143. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  58144. // Create depth-of-field post-process
  58145. this._createDepthOfFieldPostProcess(scene, ratio);
  58146. }
  58147. if (this._motionBlurEnabled) {
  58148. // Create motion blur post-process
  58149. this._createMotionBlurPostProcess(scene, ratio);
  58150. }
  58151. if (this._cameras !== null) {
  58152. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58153. }
  58154. };
  58155. // Down Sample X4 Post-Processs
  58156. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58157. var _this = this;
  58158. var downSampleX4Offsets = new Array(32);
  58159. 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);
  58160. this.downSampleX4PostProcess.onApply = function (effect) {
  58161. var id = 0;
  58162. var width = _this.downSampleX4PostProcess.width;
  58163. var height = _this.downSampleX4PostProcess.height;
  58164. for (var i = -2; i < 2; i++) {
  58165. for (var j = -2; j < 2; j++) {
  58166. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58167. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58168. id += 2;
  58169. }
  58170. }
  58171. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58172. };
  58173. // Add to pipeline
  58174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58175. };
  58176. // Brightpass Post-Process
  58177. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58178. var _this = this;
  58179. var brightOffsets = new Array(8);
  58180. 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);
  58181. this.brightPassPostProcess.onApply = function (effect) {
  58182. var sU = (1.0 / _this.brightPassPostProcess.width);
  58183. var sV = (1.0 / _this.brightPassPostProcess.height);
  58184. brightOffsets[0] = -0.5 * sU;
  58185. brightOffsets[1] = 0.5 * sV;
  58186. brightOffsets[2] = 0.5 * sU;
  58187. brightOffsets[3] = 0.5 * sV;
  58188. brightOffsets[4] = -0.5 * sU;
  58189. brightOffsets[5] = -0.5 * sV;
  58190. brightOffsets[6] = 0.5 * sU;
  58191. brightOffsets[7] = -0.5 * sV;
  58192. effect.setArray2("dsOffsets", brightOffsets);
  58193. effect.setFloat("brightThreshold", _this.brightThreshold);
  58194. };
  58195. // Add to pipeline
  58196. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58197. };
  58198. // Create blur H&V post-processes
  58199. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58200. var _this = this;
  58201. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58202. var engine = scene.getEngine();
  58203. 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);
  58204. 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);
  58205. blurX.onActivateObservable.add(function () {
  58206. var dw = blurX.width / engine.getRenderWidth();
  58207. blurX.kernel = _this[blurWidthKey] * dw;
  58208. });
  58209. blurY.onActivateObservable.add(function () {
  58210. var dw = blurY.height / engine.getRenderHeight();
  58211. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58212. });
  58213. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58214. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58215. this.blurHPostProcesses.push(blurX);
  58216. this.blurVPostProcesses.push(blurY);
  58217. };
  58218. // Create texture adder post-process
  58219. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58220. var _this = this;
  58221. 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);
  58222. this.textureAdderPostProcess.onApply = function (effect) {
  58223. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58224. effect.setTexture("lensSampler", _this.lensTexture);
  58225. effect.setFloat("exposure", _this.exposure);
  58226. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58227. };
  58228. // Add to pipeline
  58229. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58230. };
  58231. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58232. var _this = this;
  58233. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58234. geometryRenderer.enablePosition = true;
  58235. var geometry = geometryRenderer.getGBuffer();
  58236. // Base post-process
  58237. 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));
  58238. var depthValues = BABYLON.Vector2.Zero();
  58239. this.volumetricLightPostProcess.onApply = function (effect) {
  58240. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  58241. var generator = _this.sourceLight.getShadowGenerator();
  58242. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  58243. effect.setTexture("positionSampler", geometry.textures[2]);
  58244. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  58245. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  58246. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  58247. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  58248. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  58249. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  58250. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  58251. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  58252. effect.setVector2("depthValues", depthValues);
  58253. }
  58254. };
  58255. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  58256. // Smooth
  58257. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  58258. // Merge
  58259. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  58260. this.volumetricLightMergePostProces.onApply = function (effect) {
  58261. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  58262. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  58263. };
  58264. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  58265. };
  58266. // Create luminance
  58267. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  58268. var _this = this;
  58269. // Create luminance
  58270. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  58271. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  58272. var offsets = [];
  58273. this.luminancePostProcess.onApply = function (effect) {
  58274. var sU = (1.0 / _this.luminancePostProcess.width);
  58275. var sV = (1.0 / _this.luminancePostProcess.height);
  58276. offsets[0] = -0.5 * sU;
  58277. offsets[1] = 0.5 * sV;
  58278. offsets[2] = 0.5 * sU;
  58279. offsets[3] = 0.5 * sV;
  58280. offsets[4] = -0.5 * sU;
  58281. offsets[5] = -0.5 * sV;
  58282. offsets[6] = 0.5 * sU;
  58283. offsets[7] = -0.5 * sV;
  58284. effect.setArray2("lumOffsets", offsets);
  58285. };
  58286. // Add to pipeline
  58287. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  58288. // Create down sample luminance
  58289. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  58290. var size = Math.pow(3, i);
  58291. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  58292. if (i === 0) {
  58293. defines += "#define FINAL_DOWN_SAMPLER";
  58294. }
  58295. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  58296. this.luminanceDownSamplePostProcesses.push(postProcess);
  58297. }
  58298. // Create callbacks and add effects
  58299. var lastLuminance = this.luminancePostProcess;
  58300. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  58301. var downSampleOffsets = new Array(18);
  58302. pp.onApply = function (effect) {
  58303. if (!lastLuminance) {
  58304. return;
  58305. }
  58306. var id = 0;
  58307. for (var x = -1; x < 2; x++) {
  58308. for (var y = -1; y < 2; y++) {
  58309. downSampleOffsets[id] = x / lastLuminance.width;
  58310. downSampleOffsets[id + 1] = y / lastLuminance.height;
  58311. id += 2;
  58312. }
  58313. }
  58314. effect.setArray2("dsOffsets", downSampleOffsets);
  58315. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  58316. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58317. lastLuminance = _this.luminancePostProcess;
  58318. }
  58319. else {
  58320. lastLuminance = pp;
  58321. }
  58322. };
  58323. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58324. pp.onAfterRender = function (effect) {
  58325. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  58326. 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);
  58327. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  58328. };
  58329. }
  58330. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  58331. });
  58332. };
  58333. // Create HDR post-process
  58334. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  58335. var _this = this;
  58336. 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);
  58337. var outputLiminance = 1;
  58338. var time = 0;
  58339. var lastTime = 0;
  58340. this.hdrPostProcess.onApply = function (effect) {
  58341. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  58342. time += scene.getEngine().getDeltaTime();
  58343. if (outputLiminance < 0) {
  58344. outputLiminance = _this._hdrCurrentLuminance;
  58345. }
  58346. else {
  58347. var dt = (lastTime - time) / 1000.0;
  58348. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  58349. outputLiminance += _this.hdrDecreaseRate * dt;
  58350. }
  58351. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  58352. outputLiminance -= _this.hdrIncreaseRate * dt;
  58353. }
  58354. else {
  58355. outputLiminance = _this._hdrCurrentLuminance;
  58356. }
  58357. }
  58358. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  58359. effect.setFloat("averageLuminance", outputLiminance);
  58360. lastTime = time;
  58361. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  58362. };
  58363. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  58364. };
  58365. // Create lens flare post-process
  58366. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58367. var _this = this;
  58368. 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);
  58369. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58370. this._createBlurPostProcesses(scene, ratio / 4, 2);
  58371. 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);
  58372. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58373. var resolution = new BABYLON.Vector2(0, 0);
  58374. // Lens flare
  58375. this.lensFlarePostProcess.onApply = function (effect) {
  58376. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  58377. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58378. effect.setFloat("strength", _this.lensFlareStrength);
  58379. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58380. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58381. // Shift
  58382. resolution.x = _this.lensFlarePostProcess.width;
  58383. resolution.y = _this.lensFlarePostProcess.height;
  58384. effect.setVector2("resolution", resolution);
  58385. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58386. };
  58387. // Compose
  58388. 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);
  58389. 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);
  58390. this.lensFlareComposePostProcess.onApply = function (effect) {
  58391. if (!_this._scene.activeCamera) {
  58392. return;
  58393. }
  58394. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58395. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58396. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58397. // Lens start rotation matrix
  58398. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58399. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58400. 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));
  58401. camRot *= 4.0;
  58402. 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);
  58403. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58404. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58405. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  58406. };
  58407. };
  58408. // Create depth-of-field post-process
  58409. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58410. var _this = this;
  58411. 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);
  58412. this.depthOfFieldPostProcess.onApply = function (effect) {
  58413. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58414. effect.setTexture("depthSampler", _this._getDepthTexture());
  58415. effect.setFloat("distance", _this.depthOfFieldDistance);
  58416. };
  58417. // Add to pipeline
  58418. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58419. };
  58420. // Create motion blur post-process
  58421. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  58422. var _this = this;
  58423. 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);
  58424. var motionScale = 0;
  58425. var prevViewProjection = BABYLON.Matrix.Identity();
  58426. var invViewProjection = BABYLON.Matrix.Identity();
  58427. var viewProjection = BABYLON.Matrix.Identity();
  58428. var screenSize = BABYLON.Vector2.Zero();
  58429. this.motionBlurPostProcess.onApply = function (effect) {
  58430. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  58431. viewProjection.invertToRef(invViewProjection);
  58432. effect.setMatrix("inverseViewProjection", invViewProjection);
  58433. effect.setMatrix("prevViewProjection", prevViewProjection);
  58434. prevViewProjection = viewProjection;
  58435. screenSize.x = _this.motionBlurPostProcess.width;
  58436. screenSize.y = _this.motionBlurPostProcess.height;
  58437. effect.setVector2("screenSize", screenSize);
  58438. motionScale = scene.getEngine().getFps() / 60.0;
  58439. effect.setFloat("motionScale", motionScale);
  58440. effect.setFloat("motionStrength", _this.motionStrength);
  58441. effect.setTexture("depthSampler", _this._getDepthTexture());
  58442. };
  58443. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  58444. };
  58445. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  58446. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  58447. var renderer = this._scene.enableGeometryBufferRenderer();
  58448. return renderer.getGBuffer().textures[0];
  58449. }
  58450. return this._scene.enableDepthRenderer().getDepthMap();
  58451. };
  58452. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  58453. for (var i = 0; i < this._cameras.length; i++) {
  58454. var camera = this._cameras[i];
  58455. if (this.originalPostProcess) {
  58456. this.originalPostProcess.dispose(camera);
  58457. }
  58458. if (this.downSampleX4PostProcess) {
  58459. this.downSampleX4PostProcess.dispose(camera);
  58460. }
  58461. if (this.brightPassPostProcess) {
  58462. this.brightPassPostProcess.dispose(camera);
  58463. }
  58464. if (this.textureAdderPostProcess) {
  58465. this.textureAdderPostProcess.dispose(camera);
  58466. }
  58467. if (this.textureAdderFinalPostProcess) {
  58468. this.textureAdderFinalPostProcess.dispose(camera);
  58469. }
  58470. if (this.volumetricLightPostProcess) {
  58471. this.volumetricLightPostProcess.dispose(camera);
  58472. }
  58473. if (this.volumetricLightSmoothXPostProcess) {
  58474. this.volumetricLightSmoothXPostProcess.dispose(camera);
  58475. }
  58476. if (this.volumetricLightSmoothYPostProcess) {
  58477. this.volumetricLightSmoothYPostProcess.dispose(camera);
  58478. }
  58479. if (this.volumetricLightMergePostProces) {
  58480. this.volumetricLightMergePostProces.dispose(camera);
  58481. }
  58482. if (this.volumetricLightFinalPostProcess) {
  58483. this.volumetricLightFinalPostProcess.dispose(camera);
  58484. }
  58485. if (this.lensFlarePostProcess) {
  58486. this.lensFlarePostProcess.dispose(camera);
  58487. }
  58488. if (this.lensFlareComposePostProcess) {
  58489. this.lensFlareComposePostProcess.dispose(camera);
  58490. }
  58491. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  58492. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  58493. }
  58494. if (this.luminancePostProcess) {
  58495. this.luminancePostProcess.dispose(camera);
  58496. }
  58497. if (this.hdrPostProcess) {
  58498. this.hdrPostProcess.dispose(camera);
  58499. }
  58500. if (this.hdrFinalPostProcess) {
  58501. this.hdrFinalPostProcess.dispose(camera);
  58502. }
  58503. if (this.depthOfFieldPostProcess) {
  58504. this.depthOfFieldPostProcess.dispose(camera);
  58505. }
  58506. if (this.motionBlurPostProcess) {
  58507. this.motionBlurPostProcess.dispose(camera);
  58508. }
  58509. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  58510. this.blurHPostProcesses[j].dispose(camera);
  58511. }
  58512. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  58513. this.blurVPostProcesses[j].dispose(camera);
  58514. }
  58515. }
  58516. this.originalPostProcess = null;
  58517. this.downSampleX4PostProcess = null;
  58518. this.brightPassPostProcess = null;
  58519. this.textureAdderPostProcess = null;
  58520. this.textureAdderFinalPostProcess = null;
  58521. this.volumetricLightPostProcess = null;
  58522. this.volumetricLightSmoothXPostProcess = null;
  58523. this.volumetricLightSmoothYPostProcess = null;
  58524. this.volumetricLightMergePostProces = null;
  58525. this.volumetricLightFinalPostProcess = null;
  58526. this.lensFlarePostProcess = null;
  58527. this.lensFlareComposePostProcess = null;
  58528. this.luminancePostProcess = null;
  58529. this.hdrPostProcess = null;
  58530. this.hdrFinalPostProcess = null;
  58531. this.depthOfFieldPostProcess = null;
  58532. this.motionBlurPostProcess = null;
  58533. this.luminanceDownSamplePostProcesses = [];
  58534. this.blurHPostProcesses = [];
  58535. this.blurVPostProcesses = [];
  58536. };
  58537. // Dispose
  58538. StandardRenderingPipeline.prototype.dispose = function () {
  58539. this._disposePostProcesses();
  58540. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58541. _super.prototype.dispose.call(this);
  58542. };
  58543. // Serialize rendering pipeline
  58544. StandardRenderingPipeline.prototype.serialize = function () {
  58545. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58546. serializationObject.customType = "StandardRenderingPipeline";
  58547. return serializationObject;
  58548. };
  58549. /**
  58550. * Static members
  58551. */
  58552. // Parse serialized pipeline
  58553. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58554. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58555. };
  58556. // Luminance steps
  58557. StandardRenderingPipeline.LuminanceSteps = 6;
  58558. __decorate([
  58559. BABYLON.serialize()
  58560. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58561. __decorate([
  58562. BABYLON.serialize()
  58563. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58564. __decorate([
  58565. BABYLON.serialize()
  58566. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58567. __decorate([
  58568. BABYLON.serialize()
  58569. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58570. __decorate([
  58571. BABYLON.serializeAsTexture("lensTexture")
  58572. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58573. __decorate([
  58574. BABYLON.serialize()
  58575. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  58576. __decorate([
  58577. BABYLON.serialize()
  58578. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  58579. __decorate([
  58580. BABYLON.serialize()
  58581. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  58582. __decorate([
  58583. BABYLON.serialize()
  58584. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  58585. __decorate([
  58586. BABYLON.serialize()
  58587. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  58588. __decorate([
  58589. BABYLON.serialize()
  58590. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  58591. __decorate([
  58592. BABYLON.serializeAsTexture("lensColorTexture")
  58593. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  58594. __decorate([
  58595. BABYLON.serialize()
  58596. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  58597. __decorate([
  58598. BABYLON.serialize()
  58599. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  58600. __decorate([
  58601. BABYLON.serialize()
  58602. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  58603. __decorate([
  58604. BABYLON.serialize()
  58605. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  58606. __decorate([
  58607. BABYLON.serializeAsTexture("lensStarTexture")
  58608. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  58609. __decorate([
  58610. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  58611. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  58612. __decorate([
  58613. BABYLON.serialize()
  58614. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  58615. __decorate([
  58616. BABYLON.serialize()
  58617. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  58618. __decorate([
  58619. BABYLON.serialize()
  58620. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  58621. __decorate([
  58622. BABYLON.serialize()
  58623. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  58624. __decorate([
  58625. BABYLON.serialize()
  58626. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  58627. __decorate([
  58628. BABYLON.serialize()
  58629. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  58630. __decorate([
  58631. BABYLON.serialize()
  58632. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  58633. __decorate([
  58634. BABYLON.serialize()
  58635. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  58636. __decorate([
  58637. BABYLON.serialize()
  58638. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  58639. __decorate([
  58640. BABYLON.serialize()
  58641. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  58642. __decorate([
  58643. BABYLON.serialize()
  58644. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  58645. return StandardRenderingPipeline;
  58646. }(BABYLON.PostProcessRenderPipeline));
  58647. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  58648. })(BABYLON || (BABYLON = {}));
  58649. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  58650. var BABYLON;
  58651. (function (BABYLON) {
  58652. var FxaaPostProcess = /** @class */ (function (_super) {
  58653. __extends(FxaaPostProcess, _super);
  58654. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58655. if (camera === void 0) { camera = null; }
  58656. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58657. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  58658. _this.onApplyObservable.add(function (effect) {
  58659. var texelSize = _this.texelSize;
  58660. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  58661. });
  58662. return _this;
  58663. }
  58664. return FxaaPostProcess;
  58665. }(BABYLON.PostProcess));
  58666. BABYLON.FxaaPostProcess = FxaaPostProcess;
  58667. })(BABYLON || (BABYLON = {}));
  58668. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  58669. var BABYLON;
  58670. (function (BABYLON) {
  58671. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  58672. __extends(DefaultRenderingPipeline, _super);
  58673. /**
  58674. * @constructor
  58675. * @param {string} name - The rendering pipeline name
  58676. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58677. * @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)
  58678. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58679. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  58680. */
  58681. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  58682. if (automaticBuild === void 0) { automaticBuild = true; }
  58683. var _this = _super.call(this, scene.getEngine(), name) || this;
  58684. _this.PassPostProcessId = "PassPostProcessEffect";
  58685. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  58686. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  58687. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  58688. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  58689. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  58690. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  58691. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  58692. // IAnimatable
  58693. _this.animations = [];
  58694. // Values
  58695. _this._bloomEnabled = false;
  58696. _this._fxaaEnabled = false;
  58697. _this._imageProcessingEnabled = true;
  58698. _this._bloomScale = 0.6;
  58699. _this._buildAllowed = true;
  58700. /**
  58701. * Specifies the size of the bloom blur kernel, relative to the final output size
  58702. */
  58703. _this.bloomKernel = 64;
  58704. /**
  58705. * Specifies the weight of the bloom in the final rendering
  58706. */
  58707. _this._bloomWeight = 0.15;
  58708. _this._cameras = cameras || [];
  58709. _this._buildAllowed = automaticBuild;
  58710. // Initialize
  58711. _this._scene = scene;
  58712. var caps = _this._scene.getEngine().getCaps();
  58713. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  58714. // Misc
  58715. if (_this._hdr) {
  58716. if (caps.textureHalfFloatRender) {
  58717. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58718. }
  58719. else if (caps.textureFloatRender) {
  58720. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58721. }
  58722. }
  58723. else {
  58724. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58725. }
  58726. // Attach
  58727. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58728. _this._buildPipeline();
  58729. return _this;
  58730. }
  58731. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  58732. get: function () {
  58733. return this._bloomWeight;
  58734. },
  58735. set: function (value) {
  58736. if (this._bloomWeight === value) {
  58737. return;
  58738. }
  58739. this._bloomWeight = value;
  58740. if (this._hdr && this.copyBack) {
  58741. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  58742. }
  58743. },
  58744. enumerable: true,
  58745. configurable: true
  58746. });
  58747. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  58748. get: function () {
  58749. return this._bloomScale;
  58750. },
  58751. set: function (value) {
  58752. if (this._bloomScale === value) {
  58753. return;
  58754. }
  58755. this._bloomScale = value;
  58756. this._buildPipeline();
  58757. },
  58758. enumerable: true,
  58759. configurable: true
  58760. });
  58761. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  58762. get: function () {
  58763. return this._bloomEnabled;
  58764. },
  58765. set: function (enabled) {
  58766. if (this._bloomEnabled === enabled) {
  58767. return;
  58768. }
  58769. this._bloomEnabled = enabled;
  58770. this._buildPipeline();
  58771. },
  58772. enumerable: true,
  58773. configurable: true
  58774. });
  58775. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  58776. get: function () {
  58777. return this._fxaaEnabled;
  58778. },
  58779. set: function (enabled) {
  58780. if (this._fxaaEnabled === enabled) {
  58781. return;
  58782. }
  58783. this._fxaaEnabled = enabled;
  58784. this._buildPipeline();
  58785. },
  58786. enumerable: true,
  58787. configurable: true
  58788. });
  58789. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  58790. get: function () {
  58791. return this._imageProcessingEnabled;
  58792. },
  58793. set: function (enabled) {
  58794. if (this._imageProcessingEnabled === enabled) {
  58795. return;
  58796. }
  58797. this._imageProcessingEnabled = enabled;
  58798. this._buildPipeline();
  58799. },
  58800. enumerable: true,
  58801. configurable: true
  58802. });
  58803. /**
  58804. * Force the compilation of the entire pipeline.
  58805. */
  58806. DefaultRenderingPipeline.prototype.prepare = function () {
  58807. var previousState = this._buildAllowed;
  58808. this._buildAllowed = true;
  58809. this._buildPipeline();
  58810. this._buildAllowed = previousState;
  58811. };
  58812. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  58813. var _this = this;
  58814. if (!this._buildAllowed) {
  58815. return;
  58816. }
  58817. var engine = this._scene.getEngine();
  58818. this._disposePostProcesses();
  58819. this._reset();
  58820. if (this.bloomEnabled) {
  58821. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58822. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  58823. if (!this._hdr) {
  58824. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58825. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  58826. this.highlights.autoClear = false;
  58827. this.highlights.alwaysForcePOT = true;
  58828. }
  58829. 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);
  58830. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  58831. this.blurX.alwaysForcePOT = true;
  58832. this.blurX.autoClear = false;
  58833. this.blurX.onActivateObservable.add(function () {
  58834. var dw = _this.blurX.width / engine.getRenderWidth(true);
  58835. _this.blurX.kernel = _this.bloomKernel * dw;
  58836. });
  58837. 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);
  58838. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  58839. this.blurY.alwaysForcePOT = true;
  58840. this.blurY.autoClear = false;
  58841. this.blurY.onActivateObservable.add(function () {
  58842. var dh = _this.blurY.height / engine.getRenderHeight(true);
  58843. _this.blurY.kernel = _this.bloomKernel * dh;
  58844. });
  58845. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58846. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  58847. this.copyBack.alwaysForcePOT = true;
  58848. if (this._hdr) {
  58849. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  58850. var w = this.bloomWeight;
  58851. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  58852. }
  58853. else {
  58854. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  58855. }
  58856. this.copyBack.autoClear = false;
  58857. }
  58858. if (this._imageProcessingEnabled) {
  58859. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58860. if (this._hdr) {
  58861. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  58862. }
  58863. else {
  58864. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  58865. }
  58866. }
  58867. if (this.fxaaEnabled) {
  58868. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58869. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  58870. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58871. }
  58872. else {
  58873. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58874. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  58875. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58876. }
  58877. if (this.bloomEnabled) {
  58878. if (this._hdr) {
  58879. this.copyBack.shareOutputWith(this.blurX);
  58880. if (this.imageProcessing) {
  58881. this.imageProcessing.shareOutputWith(this.pass);
  58882. this.imageProcessing.autoClear = false;
  58883. }
  58884. else if (this.fxaa) {
  58885. this.fxaa.shareOutputWith(this.pass);
  58886. }
  58887. else {
  58888. this.finalMerge.shareOutputWith(this.pass);
  58889. }
  58890. }
  58891. else {
  58892. if (this.fxaa) {
  58893. this.fxaa.shareOutputWith(this.pass);
  58894. }
  58895. else {
  58896. this.finalMerge.shareOutputWith(this.pass);
  58897. }
  58898. }
  58899. }
  58900. if (this._cameras !== null) {
  58901. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58902. }
  58903. };
  58904. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  58905. for (var i = 0; i < this._cameras.length; i++) {
  58906. var camera = this._cameras[i];
  58907. if (this.pass) {
  58908. this.pass.dispose(camera);
  58909. }
  58910. if (this.highlights) {
  58911. this.highlights.dispose(camera);
  58912. }
  58913. if (this.blurX) {
  58914. this.blurX.dispose(camera);
  58915. }
  58916. if (this.blurY) {
  58917. this.blurY.dispose(camera);
  58918. }
  58919. if (this.copyBack) {
  58920. this.copyBack.dispose(camera);
  58921. }
  58922. if (this.imageProcessing) {
  58923. this.imageProcessing.dispose(camera);
  58924. }
  58925. if (this.fxaa) {
  58926. this.fxaa.dispose(camera);
  58927. }
  58928. if (this.finalMerge) {
  58929. this.finalMerge.dispose(camera);
  58930. }
  58931. }
  58932. this.pass = null;
  58933. this.highlights = null;
  58934. this.blurX = null;
  58935. this.blurY = null;
  58936. this.copyBack = null;
  58937. this.imageProcessing = null;
  58938. this.fxaa = null;
  58939. this.finalMerge = null;
  58940. };
  58941. // Dispose
  58942. DefaultRenderingPipeline.prototype.dispose = function () {
  58943. this._disposePostProcesses();
  58944. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58945. _super.prototype.dispose.call(this);
  58946. };
  58947. // Serialize rendering pipeline
  58948. DefaultRenderingPipeline.prototype.serialize = function () {
  58949. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58950. serializationObject.customType = "DefaultRenderingPipeline";
  58951. return serializationObject;
  58952. };
  58953. // Parse serialized pipeline
  58954. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58955. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  58956. };
  58957. __decorate([
  58958. BABYLON.serialize()
  58959. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  58960. __decorate([
  58961. BABYLON.serialize()
  58962. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  58963. __decorate([
  58964. BABYLON.serialize()
  58965. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  58966. __decorate([
  58967. BABYLON.serialize()
  58968. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  58969. __decorate([
  58970. BABYLON.serialize()
  58971. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  58972. __decorate([
  58973. BABYLON.serialize()
  58974. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  58975. __decorate([
  58976. BABYLON.serialize()
  58977. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  58978. __decorate([
  58979. BABYLON.serialize()
  58980. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  58981. return DefaultRenderingPipeline;
  58982. }(BABYLON.PostProcessRenderPipeline));
  58983. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  58984. })(BABYLON || (BABYLON = {}));
  58985. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  58986. var BABYLON;
  58987. (function (BABYLON) {
  58988. var GeometryBufferRenderer = /** @class */ (function () {
  58989. function GeometryBufferRenderer(scene, ratio) {
  58990. if (ratio === void 0) { ratio = 1; }
  58991. this._enablePosition = false;
  58992. this._scene = scene;
  58993. this._ratio = ratio;
  58994. // Render target
  58995. this._createRenderTargets();
  58996. }
  58997. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  58998. set: function (meshes) {
  58999. this._multiRenderTarget.renderList = meshes;
  59000. },
  59001. enumerable: true,
  59002. configurable: true
  59003. });
  59004. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  59005. get: function () {
  59006. return this._multiRenderTarget.isSupported;
  59007. },
  59008. enumerable: true,
  59009. configurable: true
  59010. });
  59011. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  59012. get: function () {
  59013. return this._enablePosition;
  59014. },
  59015. set: function (enable) {
  59016. this._enablePosition = enable;
  59017. this.dispose();
  59018. this._createRenderTargets();
  59019. },
  59020. enumerable: true,
  59021. configurable: true
  59022. });
  59023. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  59024. var material = subMesh.getMaterial();
  59025. if (material && material.disableDepthWrite) {
  59026. return false;
  59027. }
  59028. var defines = [];
  59029. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59030. var mesh = subMesh.getMesh();
  59031. // Alpha test
  59032. if (material && material.needAlphaTesting()) {
  59033. defines.push("#define ALPHATEST");
  59034. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59035. attribs.push(BABYLON.VertexBuffer.UVKind);
  59036. defines.push("#define UV1");
  59037. }
  59038. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59039. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59040. defines.push("#define UV2");
  59041. }
  59042. }
  59043. // Buffers
  59044. if (this._enablePosition) {
  59045. defines.push("#define POSITION");
  59046. }
  59047. // Bones
  59048. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59049. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59050. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59051. if (mesh.numBoneInfluencers > 4) {
  59052. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59053. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59054. }
  59055. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59056. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59057. }
  59058. else {
  59059. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59060. }
  59061. // Instances
  59062. if (useInstances) {
  59063. defines.push("#define INSTANCES");
  59064. attribs.push("world0");
  59065. attribs.push("world1");
  59066. attribs.push("world2");
  59067. attribs.push("world3");
  59068. }
  59069. // Get correct effect
  59070. var join = defines.join("\n");
  59071. if (this._cachedDefines !== join) {
  59072. this._cachedDefines = join;
  59073. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  59074. }
  59075. return this._effect.isReady();
  59076. };
  59077. GeometryBufferRenderer.prototype.getGBuffer = function () {
  59078. return this._multiRenderTarget;
  59079. };
  59080. // Methods
  59081. GeometryBufferRenderer.prototype.dispose = function () {
  59082. this.getGBuffer().dispose();
  59083. };
  59084. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  59085. var _this = this;
  59086. var engine = this._scene.getEngine();
  59087. var count = this._enablePosition ? 3 : 2;
  59088. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  59089. if (!this.isSupported) {
  59090. return;
  59091. }
  59092. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59093. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59094. this._multiRenderTarget.refreshRate = 1;
  59095. this._multiRenderTarget.renderParticles = false;
  59096. this._multiRenderTarget.renderList = null;
  59097. // set default depth value to 1.0 (far away)
  59098. this._multiRenderTarget.onClearObservable.add(function (engine) {
  59099. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  59100. });
  59101. // Custom render function
  59102. var renderSubMesh = function (subMesh) {
  59103. var mesh = subMesh.getRenderingMesh();
  59104. var scene = _this._scene;
  59105. var engine = scene.getEngine();
  59106. var material = subMesh.getMaterial();
  59107. if (!material) {
  59108. return;
  59109. }
  59110. // Culling
  59111. engine.setState(material.backFaceCulling);
  59112. // Managing instances
  59113. var batch = mesh._getInstancesRenderList(subMesh._id);
  59114. if (batch.mustReturn) {
  59115. return;
  59116. }
  59117. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59118. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59119. engine.enableEffect(_this._effect);
  59120. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59121. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59122. _this._effect.setMatrix("view", scene.getViewMatrix());
  59123. // Alpha test
  59124. if (material && material.needAlphaTesting()) {
  59125. var alphaTexture = material.getAlphaTestTexture();
  59126. if (alphaTexture) {
  59127. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59128. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59129. }
  59130. }
  59131. // Bones
  59132. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59133. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59134. }
  59135. // Draw
  59136. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59137. }
  59138. };
  59139. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59140. var index;
  59141. if (depthOnlySubMeshes.length) {
  59142. engine.setColorWrite(false);
  59143. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59144. renderSubMesh(depthOnlySubMeshes.data[index]);
  59145. }
  59146. engine.setColorWrite(true);
  59147. }
  59148. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59149. renderSubMesh(opaqueSubMeshes.data[index]);
  59150. }
  59151. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59152. renderSubMesh(alphaTestSubMeshes.data[index]);
  59153. }
  59154. };
  59155. };
  59156. return GeometryBufferRenderer;
  59157. }());
  59158. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  59159. })(BABYLON || (BABYLON = {}));
  59160. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59161. var BABYLON;
  59162. (function (BABYLON) {
  59163. var RefractionPostProcess = /** @class */ (function (_super) {
  59164. __extends(RefractionPostProcess, _super);
  59165. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59166. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59167. _this.color = color;
  59168. _this.depth = depth;
  59169. _this.colorLevel = colorLevel;
  59170. _this.onActivateObservable.add(function (cam) {
  59171. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59172. });
  59173. _this.onApplyObservable.add(function (effect) {
  59174. effect.setColor3("baseColor", _this.color);
  59175. effect.setFloat("depth", _this.depth);
  59176. effect.setFloat("colorLevel", _this.colorLevel);
  59177. effect.setTexture("refractionSampler", _this._refRexture);
  59178. });
  59179. return _this;
  59180. }
  59181. // Methods
  59182. RefractionPostProcess.prototype.dispose = function (camera) {
  59183. if (this._refRexture) {
  59184. this._refRexture.dispose();
  59185. }
  59186. _super.prototype.dispose.call(this, camera);
  59187. };
  59188. return RefractionPostProcess;
  59189. }(BABYLON.PostProcess));
  59190. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59191. })(BABYLON || (BABYLON = {}));
  59192. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59193. var BABYLON;
  59194. (function (BABYLON) {
  59195. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59196. __extends(BlackAndWhitePostProcess, _super);
  59197. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59198. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59199. _this.degree = 1;
  59200. _this.onApplyObservable.add(function (effect) {
  59201. effect.setFloat("degree", _this.degree);
  59202. });
  59203. return _this;
  59204. }
  59205. return BlackAndWhitePostProcess;
  59206. }(BABYLON.PostProcess));
  59207. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59208. })(BABYLON || (BABYLON = {}));
  59209. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59210. var BABYLON;
  59211. (function (BABYLON) {
  59212. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59213. __extends(ConvolutionPostProcess, _super);
  59214. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59215. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59216. _this.kernel = kernel;
  59217. _this.onApply = function (effect) {
  59218. effect.setFloat2("screenSize", _this.width, _this.height);
  59219. effect.setArray("kernel", _this.kernel);
  59220. };
  59221. return _this;
  59222. }
  59223. // Statics
  59224. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59225. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59226. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59227. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59228. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59229. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59230. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59231. return ConvolutionPostProcess;
  59232. }(BABYLON.PostProcess));
  59233. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59234. })(BABYLON || (BABYLON = {}));
  59235. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59236. var BABYLON;
  59237. (function (BABYLON) {
  59238. var FilterPostProcess = /** @class */ (function (_super) {
  59239. __extends(FilterPostProcess, _super);
  59240. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  59241. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  59242. _this.kernelMatrix = kernelMatrix;
  59243. _this.onApply = function (effect) {
  59244. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  59245. };
  59246. return _this;
  59247. }
  59248. return FilterPostProcess;
  59249. }(BABYLON.PostProcess));
  59250. BABYLON.FilterPostProcess = FilterPostProcess;
  59251. })(BABYLON || (BABYLON = {}));
  59252. //# sourceMappingURL=babylon.filterPostProcess.js.map
  59253. var BABYLON;
  59254. (function (BABYLON) {
  59255. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  59256. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  59257. __extends(VolumetricLightScatteringPostProcess, _super);
  59258. /**
  59259. * @constructor
  59260. * @param {string} name - The post-process name
  59261. * @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)
  59262. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  59263. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  59264. * @param {number} samples - The post-process quality, default 100
  59265. * @param {number} samplingMode - The post-process filtering mode
  59266. * @param {BABYLON.Engine} engine - The babylon engine
  59267. * @param {boolean} reusable - If the post-process is reusable
  59268. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  59269. */
  59270. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  59271. if (samples === void 0) { samples = 100; }
  59272. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59273. 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;
  59274. _this._screenCoordinates = BABYLON.Vector2.Zero();
  59275. /**
  59276. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  59277. * @type {Vector3}
  59278. */
  59279. _this.customMeshPosition = BABYLON.Vector3.Zero();
  59280. /**
  59281. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  59282. * @type {boolean}
  59283. */
  59284. _this.useCustomMeshPosition = false;
  59285. /**
  59286. * If the post-process should inverse the light scattering direction
  59287. * @type {boolean}
  59288. */
  59289. _this.invert = true;
  59290. /**
  59291. * Array containing the excluded meshes not rendered in the internal pass
  59292. */
  59293. _this.excludedMeshes = new Array();
  59294. /**
  59295. * Controls the overall intensity of the post-process
  59296. * @type {number}
  59297. */
  59298. _this.exposure = 0.3;
  59299. /**
  59300. * Dissipates each sample's contribution in range [0, 1]
  59301. * @type {number}
  59302. */
  59303. _this.decay = 0.96815;
  59304. /**
  59305. * Controls the overall intensity of each sample
  59306. * @type {number}
  59307. */
  59308. _this.weight = 0.58767;
  59309. /**
  59310. * Controls the density of each sample
  59311. * @type {number}
  59312. */
  59313. _this.density = 0.926;
  59314. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  59315. engine = scene.getEngine();
  59316. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59317. // Configure mesh
  59318. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  59319. // Configure
  59320. _this._createPass(scene, ratio.passRatio || ratio);
  59321. _this.onActivate = function (camera) {
  59322. if (!_this.isSupported) {
  59323. _this.dispose(camera);
  59324. }
  59325. _this.onActivate = null;
  59326. };
  59327. _this.onApplyObservable.add(function (effect) {
  59328. _this._updateMeshScreenCoordinates(scene);
  59329. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  59330. effect.setFloat("exposure", _this.exposure);
  59331. effect.setFloat("decay", _this.decay);
  59332. effect.setFloat("weight", _this.weight);
  59333. effect.setFloat("density", _this.density);
  59334. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  59335. });
  59336. return _this;
  59337. }
  59338. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  59339. get: function () {
  59340. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59341. return false;
  59342. },
  59343. set: function (useDiffuseColor) {
  59344. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59345. },
  59346. enumerable: true,
  59347. configurable: true
  59348. });
  59349. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  59350. return "VolumetricLightScatteringPostProcess";
  59351. };
  59352. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  59353. var mesh = subMesh.getMesh();
  59354. // Render this.mesh as default
  59355. if (mesh === this.mesh && mesh.material) {
  59356. return mesh.material.isReady(mesh);
  59357. }
  59358. var defines = [];
  59359. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59360. var material = subMesh.getMaterial();
  59361. // Alpha test
  59362. if (material) {
  59363. if (material.needAlphaTesting()) {
  59364. defines.push("#define ALPHATEST");
  59365. }
  59366. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59367. attribs.push(BABYLON.VertexBuffer.UVKind);
  59368. defines.push("#define UV1");
  59369. }
  59370. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59371. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59372. defines.push("#define UV2");
  59373. }
  59374. }
  59375. // Bones
  59376. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59377. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59378. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59379. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59380. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  59381. }
  59382. else {
  59383. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59384. }
  59385. // Instances
  59386. if (useInstances) {
  59387. defines.push("#define INSTANCES");
  59388. attribs.push("world0");
  59389. attribs.push("world1");
  59390. attribs.push("world2");
  59391. attribs.push("world3");
  59392. }
  59393. // Get correct effect
  59394. var join = defines.join("\n");
  59395. if (this._cachedDefines !== join) {
  59396. this._cachedDefines = join;
  59397. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  59398. }
  59399. return this._volumetricLightScatteringPass.isReady();
  59400. };
  59401. /**
  59402. * Sets the new light position for light scattering effect
  59403. * @param {BABYLON.Vector3} The new custom light position
  59404. */
  59405. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  59406. this.customMeshPosition = position;
  59407. };
  59408. /**
  59409. * Returns the light position for light scattering effect
  59410. * @return {BABYLON.Vector3} The custom light position
  59411. */
  59412. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  59413. return this.customMeshPosition;
  59414. };
  59415. /**
  59416. * Disposes the internal assets and detaches the post-process from the camera
  59417. */
  59418. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  59419. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  59420. if (rttIndex !== -1) {
  59421. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  59422. }
  59423. this._volumetricLightScatteringRTT.dispose();
  59424. _super.prototype.dispose.call(this, camera);
  59425. };
  59426. /**
  59427. * Returns the render target texture used by the post-process
  59428. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  59429. */
  59430. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  59431. return this._volumetricLightScatteringRTT;
  59432. };
  59433. // Private methods
  59434. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  59435. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  59436. return true;
  59437. }
  59438. return false;
  59439. };
  59440. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  59441. var _this = this;
  59442. var engine = scene.getEngine();
  59443. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59444. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59445. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59446. this._volumetricLightScatteringRTT.renderList = null;
  59447. this._volumetricLightScatteringRTT.renderParticles = false;
  59448. var camera = this.getCamera();
  59449. if (camera) {
  59450. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59451. }
  59452. else {
  59453. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59454. }
  59455. // Custom render function for submeshes
  59456. var renderSubMesh = function (subMesh) {
  59457. var mesh = subMesh.getRenderingMesh();
  59458. if (_this._meshExcluded(mesh)) {
  59459. return;
  59460. }
  59461. var material = subMesh.getMaterial();
  59462. if (!material) {
  59463. return;
  59464. }
  59465. var scene = mesh.getScene();
  59466. var engine = scene.getEngine();
  59467. // Culling
  59468. engine.setState(material.backFaceCulling);
  59469. // Managing instances
  59470. var batch = mesh._getInstancesRenderList(subMesh._id);
  59471. if (batch.mustReturn) {
  59472. return;
  59473. }
  59474. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59475. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59476. var effect = _this._volumetricLightScatteringPass;
  59477. if (mesh === _this.mesh) {
  59478. if (subMesh.effect) {
  59479. effect = subMesh.effect;
  59480. }
  59481. else {
  59482. effect = material.getEffect();
  59483. }
  59484. }
  59485. engine.enableEffect(effect);
  59486. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  59487. if (mesh === _this.mesh) {
  59488. material.bind(mesh.getWorldMatrix(), mesh);
  59489. }
  59490. else {
  59491. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  59492. // Alpha test
  59493. if (material && material.needAlphaTesting()) {
  59494. var alphaTexture = material.getAlphaTestTexture();
  59495. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  59496. if (alphaTexture) {
  59497. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59498. }
  59499. }
  59500. // Bones
  59501. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59502. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59503. }
  59504. }
  59505. // Draw
  59506. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  59507. }
  59508. };
  59509. // Render target texture callbacks
  59510. var savedSceneClearColor;
  59511. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  59512. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  59513. savedSceneClearColor = scene.clearColor;
  59514. scene.clearColor = sceneClearColor;
  59515. });
  59516. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  59517. scene.clearColor = savedSceneClearColor;
  59518. });
  59519. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59520. var engine = scene.getEngine();
  59521. var index;
  59522. if (depthOnlySubMeshes.length) {
  59523. engine.setColorWrite(false);
  59524. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59525. renderSubMesh(depthOnlySubMeshes.data[index]);
  59526. }
  59527. engine.setColorWrite(true);
  59528. }
  59529. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59530. renderSubMesh(opaqueSubMeshes.data[index]);
  59531. }
  59532. engine.setAlphaTesting(true);
  59533. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59534. renderSubMesh(alphaTestSubMeshes.data[index]);
  59535. }
  59536. engine.setAlphaTesting(false);
  59537. if (transparentSubMeshes.length) {
  59538. // Sort sub meshes
  59539. for (index = 0; index < transparentSubMeshes.length; index++) {
  59540. var submesh = transparentSubMeshes.data[index];
  59541. var boundingInfo = submesh.getBoundingInfo();
  59542. if (boundingInfo && scene.activeCamera) {
  59543. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  59544. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  59545. }
  59546. }
  59547. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  59548. sortedArray.sort(function (a, b) {
  59549. // Alpha index first
  59550. if (a._alphaIndex > b._alphaIndex) {
  59551. return 1;
  59552. }
  59553. if (a._alphaIndex < b._alphaIndex) {
  59554. return -1;
  59555. }
  59556. // Then distance to camera
  59557. if (a._distanceToCamera < b._distanceToCamera) {
  59558. return 1;
  59559. }
  59560. if (a._distanceToCamera > b._distanceToCamera) {
  59561. return -1;
  59562. }
  59563. return 0;
  59564. });
  59565. // Render sub meshes
  59566. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59567. for (index = 0; index < sortedArray.length; index++) {
  59568. renderSubMesh(sortedArray[index]);
  59569. }
  59570. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59571. }
  59572. };
  59573. };
  59574. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  59575. var transform = scene.getTransformMatrix();
  59576. var meshPosition;
  59577. if (this.useCustomMeshPosition) {
  59578. meshPosition = this.customMeshPosition;
  59579. }
  59580. else if (this.attachedNode) {
  59581. meshPosition = this.attachedNode.position;
  59582. }
  59583. else {
  59584. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  59585. }
  59586. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  59587. this._screenCoordinates.x = pos.x / this._viewPort.width;
  59588. this._screenCoordinates.y = pos.y / this._viewPort.height;
  59589. if (this.invert)
  59590. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  59591. };
  59592. // Static methods
  59593. /**
  59594. * Creates a default mesh for the Volumeric Light Scattering post-process
  59595. * @param {string} The mesh name
  59596. * @param {BABYLON.Scene} The scene where to create the mesh
  59597. * @return {BABYLON.Mesh} the default mesh
  59598. */
  59599. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  59600. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  59601. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59602. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  59603. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  59604. mesh.material = material;
  59605. return mesh;
  59606. };
  59607. __decorate([
  59608. BABYLON.serializeAsVector3()
  59609. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  59610. __decorate([
  59611. BABYLON.serialize()
  59612. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  59613. __decorate([
  59614. BABYLON.serialize()
  59615. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  59616. __decorate([
  59617. BABYLON.serializeAsMeshReference()
  59618. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  59619. __decorate([
  59620. BABYLON.serialize()
  59621. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  59622. __decorate([
  59623. BABYLON.serialize()
  59624. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  59625. __decorate([
  59626. BABYLON.serialize()
  59627. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  59628. __decorate([
  59629. BABYLON.serialize()
  59630. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  59631. __decorate([
  59632. BABYLON.serialize()
  59633. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  59634. return VolumetricLightScatteringPostProcess;
  59635. }(BABYLON.PostProcess));
  59636. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  59637. })(BABYLON || (BABYLON = {}));
  59638. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  59639. //
  59640. // This post-process allows the modification of rendered colors by using
  59641. // a 'look-up table' (LUT). This effect is also called Color Grading.
  59642. //
  59643. // The object needs to be provided an url to a texture containing the color
  59644. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  59645. // Use an image editing software to tweak the LUT to match your needs.
  59646. //
  59647. // For an example of a color LUT, see here:
  59648. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  59649. // For explanations on color grading, see here:
  59650. // http://udn.epicgames.com/Three/ColorGrading.html
  59651. //
  59652. var BABYLON;
  59653. (function (BABYLON) {
  59654. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  59655. __extends(ColorCorrectionPostProcess, _super);
  59656. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  59657. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  59658. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59659. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  59660. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59661. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59662. _this.onApply = function (effect) {
  59663. effect.setTexture("colorTable", _this._colorTableTexture);
  59664. };
  59665. return _this;
  59666. }
  59667. return ColorCorrectionPostProcess;
  59668. }(BABYLON.PostProcess));
  59669. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  59670. })(BABYLON || (BABYLON = {}));
  59671. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  59672. var BABYLON;
  59673. (function (BABYLON) {
  59674. var TonemappingOperator;
  59675. (function (TonemappingOperator) {
  59676. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  59677. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  59678. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  59679. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  59680. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  59681. ;
  59682. var TonemapPostProcess = /** @class */ (function (_super) {
  59683. __extends(TonemapPostProcess, _super);
  59684. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  59685. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59686. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59687. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  59688. _this._operator = _operator;
  59689. _this.exposureAdjustment = exposureAdjustment;
  59690. var defines = "#define ";
  59691. if (_this._operator === TonemappingOperator.Hable)
  59692. defines += "HABLE_TONEMAPPING";
  59693. else if (_this._operator === TonemappingOperator.Reinhard)
  59694. defines += "REINHARD_TONEMAPPING";
  59695. else if (_this._operator === TonemappingOperator.HejiDawson)
  59696. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  59697. else if (_this._operator === TonemappingOperator.Photographic)
  59698. defines += "PHOTOGRAPHIC_TONEMAPPING";
  59699. //sadly a second call to create the effect.
  59700. _this.updateEffect(defines);
  59701. _this.onApply = function (effect) {
  59702. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  59703. };
  59704. return _this;
  59705. }
  59706. return TonemapPostProcess;
  59707. }(BABYLON.PostProcess));
  59708. BABYLON.TonemapPostProcess = TonemapPostProcess;
  59709. })(BABYLON || (BABYLON = {}));
  59710. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  59711. var BABYLON;
  59712. (function (BABYLON) {
  59713. var DisplayPassPostProcess = /** @class */ (function (_super) {
  59714. __extends(DisplayPassPostProcess, _super);
  59715. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  59716. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  59717. }
  59718. return DisplayPassPostProcess;
  59719. }(BABYLON.PostProcess));
  59720. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  59721. })(BABYLON || (BABYLON = {}));
  59722. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  59723. var BABYLON;
  59724. (function (BABYLON) {
  59725. var HighlightsPostProcess = /** @class */ (function (_super) {
  59726. __extends(HighlightsPostProcess, _super);
  59727. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59728. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59729. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  59730. }
  59731. return HighlightsPostProcess;
  59732. }(BABYLON.PostProcess));
  59733. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  59734. })(BABYLON || (BABYLON = {}));
  59735. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  59736. var BABYLON;
  59737. (function (BABYLON) {
  59738. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  59739. __extends(ImageProcessingPostProcess, _super);
  59740. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59741. if (camera === void 0) { camera = null; }
  59742. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59743. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  59744. _this._fromLinearSpace = true;
  59745. /**
  59746. * Defines cache preventing GC.
  59747. */
  59748. _this._defines = {
  59749. IMAGEPROCESSING: false,
  59750. VIGNETTE: false,
  59751. VIGNETTEBLENDMODEMULTIPLY: false,
  59752. VIGNETTEBLENDMODEOPAQUE: false,
  59753. TONEMAPPING: false,
  59754. CONTRAST: false,
  59755. COLORCURVES: false,
  59756. COLORGRADING: false,
  59757. COLORGRADING3D: false,
  59758. FROMLINEARSPACE: false,
  59759. SAMPLER3DGREENDEPTH: false,
  59760. SAMPLER3DBGRMAP: false,
  59761. IMAGEPROCESSINGPOSTPROCESS: false,
  59762. EXPOSURE: false,
  59763. };
  59764. // Setup the default processing configuration to the scene.
  59765. _this._attachImageProcessingConfiguration(null, true);
  59766. _this.imageProcessingConfiguration.applyByPostProcess = true;
  59767. _this.onApply = function (effect) {
  59768. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  59769. };
  59770. return _this;
  59771. }
  59772. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  59773. /**
  59774. * Gets the image processing configuration used either in this material.
  59775. */
  59776. get: function () {
  59777. return this._imageProcessingConfiguration;
  59778. },
  59779. /**
  59780. * Sets the Default image processing configuration used either in the this material.
  59781. *
  59782. * If sets to null, the scene one is in use.
  59783. */
  59784. set: function (value) {
  59785. this._attachImageProcessingConfiguration(value);
  59786. },
  59787. enumerable: true,
  59788. configurable: true
  59789. });
  59790. /**
  59791. * Attaches a new image processing configuration to the PBR Material.
  59792. * @param configuration
  59793. */
  59794. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  59795. var _this = this;
  59796. if (doNotBuild === void 0) { doNotBuild = false; }
  59797. if (configuration === this._imageProcessingConfiguration) {
  59798. return;
  59799. }
  59800. // Detaches observer.
  59801. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59802. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59803. }
  59804. // Pick the scene configuration if needed.
  59805. if (!configuration) {
  59806. var scene = null;
  59807. var engine = this.getEngine();
  59808. var camera = this.getCamera();
  59809. if (camera) {
  59810. scene = camera.getScene();
  59811. }
  59812. else if (engine && engine.scenes) {
  59813. var scenes = engine.scenes;
  59814. scene = scenes[scenes.length - 1];
  59815. }
  59816. else {
  59817. scene = BABYLON.Engine.LastCreatedScene;
  59818. }
  59819. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  59820. }
  59821. else {
  59822. this._imageProcessingConfiguration = configuration;
  59823. }
  59824. // Attaches observer.
  59825. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  59826. _this._updateParameters();
  59827. });
  59828. // Ensure the effect will be rebuilt.
  59829. if (!doNotBuild) {
  59830. this._updateParameters();
  59831. }
  59832. };
  59833. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  59834. /**
  59835. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59836. */
  59837. get: function () {
  59838. return this.imageProcessingConfiguration.colorCurves;
  59839. },
  59840. /**
  59841. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59842. */
  59843. set: function (value) {
  59844. this.imageProcessingConfiguration.colorCurves = value;
  59845. },
  59846. enumerable: true,
  59847. configurable: true
  59848. });
  59849. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  59850. /**
  59851. * Gets wether the color curves effect is enabled.
  59852. */
  59853. get: function () {
  59854. return this.imageProcessingConfiguration.colorCurvesEnabled;
  59855. },
  59856. /**
  59857. * Sets wether the color curves effect is enabled.
  59858. */
  59859. set: function (value) {
  59860. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  59861. },
  59862. enumerable: true,
  59863. configurable: true
  59864. });
  59865. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  59866. /**
  59867. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59868. */
  59869. get: function () {
  59870. return this.imageProcessingConfiguration.colorGradingTexture;
  59871. },
  59872. /**
  59873. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59874. */
  59875. set: function (value) {
  59876. this.imageProcessingConfiguration.colorGradingTexture = value;
  59877. },
  59878. enumerable: true,
  59879. configurable: true
  59880. });
  59881. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  59882. /**
  59883. * Gets wether the color grading effect is enabled.
  59884. */
  59885. get: function () {
  59886. return this.imageProcessingConfiguration.colorGradingEnabled;
  59887. },
  59888. /**
  59889. * Gets wether the color grading effect is enabled.
  59890. */
  59891. set: function (value) {
  59892. this.imageProcessingConfiguration.colorGradingEnabled = value;
  59893. },
  59894. enumerable: true,
  59895. configurable: true
  59896. });
  59897. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  59898. /**
  59899. * Gets exposure used in the effect.
  59900. */
  59901. get: function () {
  59902. return this.imageProcessingConfiguration.exposure;
  59903. },
  59904. /**
  59905. * Sets exposure used in the effect.
  59906. */
  59907. set: function (value) {
  59908. this.imageProcessingConfiguration.exposure = value;
  59909. },
  59910. enumerable: true,
  59911. configurable: true
  59912. });
  59913. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  59914. /**
  59915. * Gets wether tonemapping is enabled or not.
  59916. */
  59917. get: function () {
  59918. return this._imageProcessingConfiguration.toneMappingEnabled;
  59919. },
  59920. /**
  59921. * Sets wether tonemapping is enabled or not
  59922. */
  59923. set: function (value) {
  59924. this._imageProcessingConfiguration.toneMappingEnabled = value;
  59925. },
  59926. enumerable: true,
  59927. configurable: true
  59928. });
  59929. ;
  59930. ;
  59931. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  59932. /**
  59933. * Gets contrast used in the effect.
  59934. */
  59935. get: function () {
  59936. return this.imageProcessingConfiguration.contrast;
  59937. },
  59938. /**
  59939. * Sets contrast used in the effect.
  59940. */
  59941. set: function (value) {
  59942. this.imageProcessingConfiguration.contrast = value;
  59943. },
  59944. enumerable: true,
  59945. configurable: true
  59946. });
  59947. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  59948. /**
  59949. * Gets Vignette stretch size.
  59950. */
  59951. get: function () {
  59952. return this.imageProcessingConfiguration.vignetteStretch;
  59953. },
  59954. /**
  59955. * Sets Vignette stretch size.
  59956. */
  59957. set: function (value) {
  59958. this.imageProcessingConfiguration.vignetteStretch = value;
  59959. },
  59960. enumerable: true,
  59961. configurable: true
  59962. });
  59963. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  59964. /**
  59965. * Gets Vignette centre X Offset.
  59966. */
  59967. get: function () {
  59968. return this.imageProcessingConfiguration.vignetteCentreX;
  59969. },
  59970. /**
  59971. * Sets Vignette centre X Offset.
  59972. */
  59973. set: function (value) {
  59974. this.imageProcessingConfiguration.vignetteCentreX = value;
  59975. },
  59976. enumerable: true,
  59977. configurable: true
  59978. });
  59979. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  59980. /**
  59981. * Gets Vignette centre Y Offset.
  59982. */
  59983. get: function () {
  59984. return this.imageProcessingConfiguration.vignetteCentreY;
  59985. },
  59986. /**
  59987. * Sets Vignette centre Y Offset.
  59988. */
  59989. set: function (value) {
  59990. this.imageProcessingConfiguration.vignetteCentreY = value;
  59991. },
  59992. enumerable: true,
  59993. configurable: true
  59994. });
  59995. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  59996. /**
  59997. * Gets Vignette weight or intensity of the vignette effect.
  59998. */
  59999. get: function () {
  60000. return this.imageProcessingConfiguration.vignetteWeight;
  60001. },
  60002. /**
  60003. * Sets Vignette weight or intensity of the vignette effect.
  60004. */
  60005. set: function (value) {
  60006. this.imageProcessingConfiguration.vignetteWeight = value;
  60007. },
  60008. enumerable: true,
  60009. configurable: true
  60010. });
  60011. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  60012. /**
  60013. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60014. * if vignetteEnabled is set to true.
  60015. */
  60016. get: function () {
  60017. return this.imageProcessingConfiguration.vignetteColor;
  60018. },
  60019. /**
  60020. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60021. * if vignetteEnabled is set to true.
  60022. */
  60023. set: function (value) {
  60024. this.imageProcessingConfiguration.vignetteColor = value;
  60025. },
  60026. enumerable: true,
  60027. configurable: true
  60028. });
  60029. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  60030. /**
  60031. * Gets Camera field of view used by the Vignette effect.
  60032. */
  60033. get: function () {
  60034. return this.imageProcessingConfiguration.vignetteCameraFov;
  60035. },
  60036. /**
  60037. * Sets Camera field of view used by the Vignette effect.
  60038. */
  60039. set: function (value) {
  60040. this.imageProcessingConfiguration.vignetteCameraFov = value;
  60041. },
  60042. enumerable: true,
  60043. configurable: true
  60044. });
  60045. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  60046. /**
  60047. * Gets the vignette blend mode allowing different kind of effect.
  60048. */
  60049. get: function () {
  60050. return this.imageProcessingConfiguration.vignetteBlendMode;
  60051. },
  60052. /**
  60053. * Sets the vignette blend mode allowing different kind of effect.
  60054. */
  60055. set: function (value) {
  60056. this.imageProcessingConfiguration.vignetteBlendMode = value;
  60057. },
  60058. enumerable: true,
  60059. configurable: true
  60060. });
  60061. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  60062. /**
  60063. * Gets wether the vignette effect is enabled.
  60064. */
  60065. get: function () {
  60066. return this.imageProcessingConfiguration.vignetteEnabled;
  60067. },
  60068. /**
  60069. * Sets wether the vignette effect is enabled.
  60070. */
  60071. set: function (value) {
  60072. this.imageProcessingConfiguration.vignetteEnabled = value;
  60073. },
  60074. enumerable: true,
  60075. configurable: true
  60076. });
  60077. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  60078. /**
  60079. * Gets wether the input of the processing is in Gamma or Linear Space.
  60080. */
  60081. get: function () {
  60082. return this._fromLinearSpace;
  60083. },
  60084. /**
  60085. * Sets wether the input of the processing is in Gamma or Linear Space.
  60086. */
  60087. set: function (value) {
  60088. if (this._fromLinearSpace === value) {
  60089. return;
  60090. }
  60091. this._fromLinearSpace = value;
  60092. this._updateParameters();
  60093. },
  60094. enumerable: true,
  60095. configurable: true
  60096. });
  60097. ImageProcessingPostProcess.prototype.getClassName = function () {
  60098. return "ImageProcessingPostProcess";
  60099. };
  60100. ImageProcessingPostProcess.prototype._updateParameters = function () {
  60101. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  60102. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  60103. var defines = "";
  60104. for (var define in this._defines) {
  60105. if (this._defines[define]) {
  60106. defines += "#define " + define + ";\r\n";
  60107. }
  60108. }
  60109. var samplers = ["textureSampler"];
  60110. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  60111. var uniforms = ["scale"];
  60112. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  60113. this.updateEffect(defines, uniforms, samplers);
  60114. };
  60115. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  60116. _super.prototype.dispose.call(this, camera);
  60117. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60118. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60119. }
  60120. this.imageProcessingConfiguration.applyByPostProcess = false;
  60121. };
  60122. __decorate([
  60123. BABYLON.serialize()
  60124. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  60125. return ImageProcessingPostProcess;
  60126. }(BABYLON.PostProcess));
  60127. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  60128. })(BABYLON || (BABYLON = {}));
  60129. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  60130. var BABYLON;
  60131. (function (BABYLON) {
  60132. var BlurPostProcess = /** @class */ (function (_super) {
  60133. __extends(BlurPostProcess, _super);
  60134. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  60135. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60136. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60137. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  60138. _this.direction = direction;
  60139. _this._packedFloat = false;
  60140. _this.onApplyObservable.add(function (effect) {
  60141. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  60142. });
  60143. _this.kernel = kernel;
  60144. return _this;
  60145. }
  60146. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  60147. /**
  60148. * Gets the length in pixels of the blur sample region
  60149. */
  60150. get: function () {
  60151. return this._idealKernel;
  60152. },
  60153. /**
  60154. * Sets the length in pixels of the blur sample region
  60155. */
  60156. set: function (v) {
  60157. if (this._idealKernel === v) {
  60158. return;
  60159. }
  60160. v = Math.max(v, 1);
  60161. this._idealKernel = v;
  60162. this._kernel = this._nearestBestKernel(v);
  60163. this._updateParameters();
  60164. },
  60165. enumerable: true,
  60166. configurable: true
  60167. });
  60168. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60169. /**
  60170. * Gets wether or not the blur is unpacking/repacking floats
  60171. */
  60172. get: function () {
  60173. return this._packedFloat;
  60174. },
  60175. /**
  60176. * Sets wether or not the blur needs to unpack/repack floats
  60177. */
  60178. set: function (v) {
  60179. if (this._packedFloat === v) {
  60180. return;
  60181. }
  60182. this._packedFloat = v;
  60183. this._updateParameters();
  60184. },
  60185. enumerable: true,
  60186. configurable: true
  60187. });
  60188. BlurPostProcess.prototype._updateParameters = function () {
  60189. // Generate sampling offsets and weights
  60190. var N = this._kernel;
  60191. var centerIndex = (N - 1) / 2;
  60192. // Generate Gaussian sampling weights over kernel
  60193. var offsets = [];
  60194. var weights = [];
  60195. var totalWeight = 0;
  60196. for (var i = 0; i < N; i++) {
  60197. var u = i / (N - 1);
  60198. var w = this._gaussianWeight(u * 2.0 - 1);
  60199. offsets[i] = (i - centerIndex);
  60200. weights[i] = w;
  60201. totalWeight += w;
  60202. }
  60203. // Normalize weights
  60204. for (var i = 0; i < weights.length; i++) {
  60205. weights[i] /= totalWeight;
  60206. }
  60207. // Optimize: combine samples to take advantage of hardware linear sampling
  60208. // Walk from left to center, combining pairs (symmetrically)
  60209. var linearSamplingWeights = [];
  60210. var linearSamplingOffsets = [];
  60211. var linearSamplingMap = [];
  60212. for (var i = 0; i <= centerIndex; i += 2) {
  60213. var j = Math.min(i + 1, Math.floor(centerIndex));
  60214. var singleCenterSample = i === j;
  60215. if (singleCenterSample) {
  60216. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60217. }
  60218. else {
  60219. var sharedCell = j === centerIndex;
  60220. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60221. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60222. if (offsetLinear === 0) {
  60223. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60224. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60225. }
  60226. else {
  60227. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60228. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60229. }
  60230. }
  60231. }
  60232. for (var i = 0; i < linearSamplingMap.length; i++) {
  60233. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60234. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60235. }
  60236. // Replace with optimized
  60237. offsets = linearSamplingOffsets;
  60238. weights = linearSamplingWeights;
  60239. // Generate shaders
  60240. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  60241. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  60242. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  60243. var defines = "";
  60244. for (var i = 0; i < varyingCount; i++) {
  60245. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  60246. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  60247. }
  60248. var depCount = 0;
  60249. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  60250. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  60251. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  60252. depCount++;
  60253. }
  60254. if (this.packedFloat) {
  60255. defines += "#define PACKEDFLOAT 1";
  60256. }
  60257. this.updateEffect(defines, null, null, {
  60258. varyingCount: varyingCount,
  60259. depCount: depCount
  60260. });
  60261. };
  60262. /**
  60263. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  60264. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  60265. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  60266. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  60267. * The gaps between physical kernels are compensated for in the weighting of the samples
  60268. * @param idealKernel Ideal blur kernel.
  60269. * @return Nearest best kernel.
  60270. */
  60271. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  60272. var v = Math.round(idealKernel);
  60273. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  60274. var k = _a[_i];
  60275. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  60276. return Math.max(k, 3);
  60277. }
  60278. }
  60279. return Math.max(v, 3);
  60280. };
  60281. /**
  60282. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  60283. * @param x The point on the Gaussian distribution to sample.
  60284. * @return the value of the Gaussian function at x.
  60285. */
  60286. BlurPostProcess.prototype._gaussianWeight = function (x) {
  60287. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  60288. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  60289. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  60290. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  60291. // truncated at around 1.3% of peak strength.
  60292. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  60293. var sigma = (1 / 3);
  60294. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  60295. var exponent = -((x * x) / (2.0 * sigma * sigma));
  60296. var weight = (1.0 / denominator) * Math.exp(exponent);
  60297. return weight;
  60298. };
  60299. /**
  60300. * Generates a string that can be used as a floating point number in GLSL.
  60301. * @param x Value to print.
  60302. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  60303. * @return GLSL float string.
  60304. */
  60305. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  60306. if (decimalFigures === void 0) { decimalFigures = 8; }
  60307. return x.toFixed(decimalFigures).replace(/0+$/, '');
  60308. };
  60309. return BlurPostProcess;
  60310. }(BABYLON.PostProcess));
  60311. BABYLON.BlurPostProcess = BlurPostProcess;
  60312. })(BABYLON || (BABYLON = {}));
  60313. //# sourceMappingURL=babylon.blurPostProcess.js.map
  60314. var BABYLON;
  60315. (function (BABYLON) {
  60316. var Bone = /** @class */ (function (_super) {
  60317. __extends(Bone, _super);
  60318. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  60319. if (parentBone === void 0) { parentBone = null; }
  60320. if (localMatrix === void 0) { localMatrix = null; }
  60321. if (restPose === void 0) { restPose = null; }
  60322. if (baseMatrix === void 0) { baseMatrix = null; }
  60323. if (index === void 0) { index = null; }
  60324. var _this = _super.call(this, name, skeleton.getScene()) || this;
  60325. _this.name = name;
  60326. _this.children = new Array();
  60327. _this.animations = new Array();
  60328. // Set this value to map this bone to a different index in the transform matrices.
  60329. // Set this value to -1 to exclude the bone from the transform matrices.
  60330. _this._index = null;
  60331. _this._worldTransform = new BABYLON.Matrix();
  60332. _this._absoluteTransform = new BABYLON.Matrix();
  60333. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  60334. _this._scaleMatrix = BABYLON.Matrix.Identity();
  60335. _this._scaleVector = BABYLON.Vector3.One();
  60336. _this._negateScaleChildren = BABYLON.Vector3.One();
  60337. _this._scalingDeterminant = 1;
  60338. _this._skeleton = skeleton;
  60339. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  60340. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  60341. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  60342. _this._index = index;
  60343. skeleton.bones.push(_this);
  60344. _this.setParent(parentBone, false);
  60345. _this._updateDifferenceMatrix();
  60346. return _this;
  60347. }
  60348. Object.defineProperty(Bone.prototype, "_matrix", {
  60349. get: function () {
  60350. return this._localMatrix;
  60351. },
  60352. set: function (val) {
  60353. if (this._localMatrix) {
  60354. this._localMatrix.copyFrom(val);
  60355. }
  60356. else {
  60357. this._localMatrix = val;
  60358. }
  60359. },
  60360. enumerable: true,
  60361. configurable: true
  60362. });
  60363. // Members
  60364. Bone.prototype.getSkeleton = function () {
  60365. return this._skeleton;
  60366. };
  60367. Bone.prototype.getParent = function () {
  60368. return this._parent;
  60369. };
  60370. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  60371. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60372. if (this._parent === parent) {
  60373. return;
  60374. }
  60375. if (this._parent) {
  60376. var index = this._parent.children.indexOf(this);
  60377. if (index !== -1) {
  60378. this._parent.children.splice(index, 1);
  60379. }
  60380. }
  60381. this._parent = parent;
  60382. if (this._parent) {
  60383. this._parent.children.push(this);
  60384. }
  60385. if (updateDifferenceMatrix) {
  60386. this._updateDifferenceMatrix();
  60387. }
  60388. };
  60389. Bone.prototype.getLocalMatrix = function () {
  60390. return this._localMatrix;
  60391. };
  60392. Bone.prototype.getBaseMatrix = function () {
  60393. return this._baseMatrix;
  60394. };
  60395. Bone.prototype.getRestPose = function () {
  60396. return this._restPose;
  60397. };
  60398. Bone.prototype.returnToRest = function () {
  60399. this.updateMatrix(this._restPose.clone());
  60400. };
  60401. Bone.prototype.getWorldMatrix = function () {
  60402. return this._worldTransform;
  60403. };
  60404. Bone.prototype.getInvertedAbsoluteTransform = function () {
  60405. return this._invertedAbsoluteTransform;
  60406. };
  60407. Bone.prototype.getAbsoluteTransform = function () {
  60408. return this._absoluteTransform;
  60409. };
  60410. Object.defineProperty(Bone.prototype, "position", {
  60411. // Properties (matches AbstractMesh properties)
  60412. get: function () {
  60413. return this.getPosition();
  60414. },
  60415. set: function (newPosition) {
  60416. this.setPosition(newPosition);
  60417. },
  60418. enumerable: true,
  60419. configurable: true
  60420. });
  60421. Object.defineProperty(Bone.prototype, "rotation", {
  60422. get: function () {
  60423. return this.getRotation();
  60424. },
  60425. set: function (newRotation) {
  60426. this.setRotation(newRotation);
  60427. },
  60428. enumerable: true,
  60429. configurable: true
  60430. });
  60431. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  60432. get: function () {
  60433. return this.getRotationQuaternion();
  60434. },
  60435. set: function (newRotation) {
  60436. this.setRotationQuaternion(newRotation);
  60437. },
  60438. enumerable: true,
  60439. configurable: true
  60440. });
  60441. Object.defineProperty(Bone.prototype, "scaling", {
  60442. get: function () {
  60443. return this.getScale();
  60444. },
  60445. set: function (newScaling) {
  60446. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  60447. },
  60448. enumerable: true,
  60449. configurable: true
  60450. });
  60451. // Methods
  60452. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  60453. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60454. this._baseMatrix = matrix.clone();
  60455. this._localMatrix = matrix.clone();
  60456. this._skeleton._markAsDirty();
  60457. if (updateDifferenceMatrix) {
  60458. this._updateDifferenceMatrix();
  60459. }
  60460. };
  60461. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  60462. if (!rootMatrix) {
  60463. rootMatrix = this._baseMatrix;
  60464. }
  60465. if (this._parent) {
  60466. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60467. }
  60468. else {
  60469. this._absoluteTransform.copyFrom(rootMatrix);
  60470. }
  60471. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  60472. for (var index = 0; index < this.children.length; index++) {
  60473. this.children[index]._updateDifferenceMatrix();
  60474. }
  60475. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  60476. };
  60477. Bone.prototype.markAsDirty = function () {
  60478. this._currentRenderId++;
  60479. this._skeleton._markAsDirty();
  60480. };
  60481. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  60482. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60483. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  60484. // all animation may be coming from a library skeleton, so may need to create animation
  60485. if (this.animations.length === 0) {
  60486. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  60487. this.animations[0].setKeys([]);
  60488. }
  60489. // get animation info / verify there is such a range from the source bone
  60490. var sourceRange = source.animations[0].getRange(rangeName);
  60491. if (!sourceRange) {
  60492. return false;
  60493. }
  60494. var from = sourceRange.from;
  60495. var to = sourceRange.to;
  60496. var sourceKeys = source.animations[0].getKeys();
  60497. // rescaling prep
  60498. var sourceBoneLength = source.length;
  60499. var sourceParent = source.getParent();
  60500. var parent = this.getParent();
  60501. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  60502. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  60503. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  60504. var destKeys = this.animations[0].getKeys();
  60505. // loop vars declaration
  60506. var orig;
  60507. var origTranslation;
  60508. var mat;
  60509. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  60510. orig = sourceKeys[key];
  60511. if (orig.frame >= from && orig.frame <= to) {
  60512. if (rescaleAsRequired) {
  60513. mat = orig.value.clone();
  60514. // scale based on parent ratio, when bone has parent
  60515. if (parentScalingReqd) {
  60516. origTranslation = mat.getTranslation();
  60517. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  60518. // scale based on skeleton dimension ratio when root bone, and value is passed
  60519. }
  60520. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  60521. origTranslation = mat.getTranslation();
  60522. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  60523. // use original when root bone, and no data for skelDimensionsRatio
  60524. }
  60525. else {
  60526. mat = orig.value;
  60527. }
  60528. }
  60529. else {
  60530. mat = orig.value;
  60531. }
  60532. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  60533. }
  60534. }
  60535. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  60536. return true;
  60537. };
  60538. /**
  60539. * Translate the bone in local or world space.
  60540. * @param vec The amount to translate the bone.
  60541. * @param space The space that the translation is in.
  60542. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60543. */
  60544. Bone.prototype.translate = function (vec, space, mesh) {
  60545. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60546. var lm = this.getLocalMatrix();
  60547. if (space == BABYLON.Space.LOCAL) {
  60548. lm.m[12] += vec.x;
  60549. lm.m[13] += vec.y;
  60550. lm.m[14] += vec.z;
  60551. }
  60552. else {
  60553. var wm = null;
  60554. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60555. if (mesh) {
  60556. wm = mesh.getWorldMatrix();
  60557. }
  60558. this._skeleton.computeAbsoluteTransforms();
  60559. var tmat = Bone._tmpMats[0];
  60560. var tvec = Bone._tmpVecs[0];
  60561. if (this._parent) {
  60562. if (mesh && wm) {
  60563. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60564. tmat.multiplyToRef(wm, tmat);
  60565. }
  60566. else {
  60567. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60568. }
  60569. }
  60570. tmat.m[12] = 0;
  60571. tmat.m[13] = 0;
  60572. tmat.m[14] = 0;
  60573. tmat.invert();
  60574. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  60575. lm.m[12] += tvec.x;
  60576. lm.m[13] += tvec.y;
  60577. lm.m[14] += tvec.z;
  60578. }
  60579. this.markAsDirty();
  60580. };
  60581. /**
  60582. * Set the postion of the bone in local or world space.
  60583. * @param position The position to set the bone.
  60584. * @param space The space that the position is in.
  60585. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60586. */
  60587. Bone.prototype.setPosition = function (position, space, mesh) {
  60588. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60589. var lm = this.getLocalMatrix();
  60590. if (space == BABYLON.Space.LOCAL) {
  60591. lm.m[12] = position.x;
  60592. lm.m[13] = position.y;
  60593. lm.m[14] = position.z;
  60594. }
  60595. else {
  60596. var wm = null;
  60597. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60598. if (mesh) {
  60599. wm = mesh.getWorldMatrix();
  60600. }
  60601. this._skeleton.computeAbsoluteTransforms();
  60602. var tmat = Bone._tmpMats[0];
  60603. var vec = Bone._tmpVecs[0];
  60604. if (this._parent) {
  60605. if (mesh && wm) {
  60606. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60607. tmat.multiplyToRef(wm, tmat);
  60608. }
  60609. else {
  60610. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60611. }
  60612. }
  60613. tmat.invert();
  60614. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  60615. lm.m[12] = vec.x;
  60616. lm.m[13] = vec.y;
  60617. lm.m[14] = vec.z;
  60618. }
  60619. this.markAsDirty();
  60620. };
  60621. /**
  60622. * Set the absolute postion of the bone (world space).
  60623. * @param position The position to set the bone.
  60624. * @param mesh The mesh that this bone is attached to.
  60625. */
  60626. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  60627. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  60628. };
  60629. /**
  60630. * Set the scale of the bone on the x, y and z axes.
  60631. * @param x The scale of the bone on the x axis.
  60632. * @param x The scale of the bone on the y axis.
  60633. * @param z The scale of the bone on the z axis.
  60634. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60635. */
  60636. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  60637. if (scaleChildren === void 0) { scaleChildren = false; }
  60638. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  60639. if (!scaleChildren) {
  60640. this._negateScaleChildren.x = 1 / x;
  60641. this._negateScaleChildren.y = 1 / y;
  60642. this._negateScaleChildren.z = 1 / z;
  60643. }
  60644. this._syncScaleVector();
  60645. }
  60646. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  60647. };
  60648. /**
  60649. * Scale the bone on the x, y and z axes.
  60650. * @param x The amount to scale the bone on the x axis.
  60651. * @param x The amount to scale the bone on the y axis.
  60652. * @param z The amount to scale the bone on the z axis.
  60653. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60654. */
  60655. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  60656. if (scaleChildren === void 0) { scaleChildren = false; }
  60657. var locMat = this.getLocalMatrix();
  60658. var origLocMat = Bone._tmpMats[0];
  60659. origLocMat.copyFrom(locMat);
  60660. var origLocMatInv = Bone._tmpMats[1];
  60661. origLocMatInv.copyFrom(origLocMat);
  60662. origLocMatInv.invert();
  60663. var scaleMat = Bone._tmpMats[2];
  60664. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  60665. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  60666. this._scaleVector.x *= x;
  60667. this._scaleVector.y *= y;
  60668. this._scaleVector.z *= z;
  60669. locMat.multiplyToRef(origLocMatInv, locMat);
  60670. locMat.multiplyToRef(scaleMat, locMat);
  60671. locMat.multiplyToRef(origLocMat, locMat);
  60672. var parent = this.getParent();
  60673. if (parent) {
  60674. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  60675. }
  60676. else {
  60677. this.getAbsoluteTransform().copyFrom(locMat);
  60678. }
  60679. var len = this.children.length;
  60680. scaleMat.invert();
  60681. for (var i = 0; i < len; i++) {
  60682. var child = this.children[i];
  60683. var cm = child.getLocalMatrix();
  60684. cm.multiplyToRef(scaleMat, cm);
  60685. var lm = child.getLocalMatrix();
  60686. lm.m[12] *= x;
  60687. lm.m[13] *= y;
  60688. lm.m[14] *= z;
  60689. }
  60690. this.computeAbsoluteTransforms();
  60691. if (scaleChildren) {
  60692. for (var i = 0; i < len; i++) {
  60693. this.children[i].scale(x, y, z, scaleChildren);
  60694. }
  60695. }
  60696. this.markAsDirty();
  60697. };
  60698. /**
  60699. * Set the yaw, pitch, and roll of the bone in local or world space.
  60700. * @param yaw The rotation of the bone on the y axis.
  60701. * @param pitch The rotation of the bone on the x axis.
  60702. * @param roll The rotation of the bone on the z axis.
  60703. * @param space The space that the axes of rotation are in.
  60704. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60705. */
  60706. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  60707. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60708. var rotMat = Bone._tmpMats[0];
  60709. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  60710. var rotMatInv = Bone._tmpMats[1];
  60711. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60712. rotMatInv.multiplyToRef(rotMat, rotMat);
  60713. this._rotateWithMatrix(rotMat, space, mesh);
  60714. };
  60715. /**
  60716. * Rotate the bone on an axis in local or world space.
  60717. * @param axis The axis to rotate the bone on.
  60718. * @param amount The amount to rotate the bone.
  60719. * @param space The space that the axis is in.
  60720. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60721. */
  60722. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  60723. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60724. var rmat = Bone._tmpMats[0];
  60725. rmat.m[12] = 0;
  60726. rmat.m[13] = 0;
  60727. rmat.m[14] = 0;
  60728. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  60729. this._rotateWithMatrix(rmat, space, mesh);
  60730. };
  60731. /**
  60732. * Set the rotation of the bone to a particular axis angle in local or world space.
  60733. * @param axis The axis to rotate the bone on.
  60734. * @param angle The angle that the bone should be rotated to.
  60735. * @param space The space that the axis is in.
  60736. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60737. */
  60738. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  60739. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60740. var rotMat = Bone._tmpMats[0];
  60741. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  60742. var rotMatInv = Bone._tmpMats[1];
  60743. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60744. rotMatInv.multiplyToRef(rotMat, rotMat);
  60745. this._rotateWithMatrix(rotMat, space, mesh);
  60746. };
  60747. /**
  60748. * Set the euler rotation of the bone in local of world space.
  60749. * @param rotation The euler rotation that the bone should be set to.
  60750. * @param space The space that the rotation is in.
  60751. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60752. */
  60753. Bone.prototype.setRotation = function (rotation, space, mesh) {
  60754. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60755. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  60756. };
  60757. /**
  60758. * Set the quaternion rotation of the bone in local of world space.
  60759. * @param quat The quaternion rotation that the bone should be set to.
  60760. * @param space The space that the rotation is in.
  60761. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60762. */
  60763. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  60764. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60765. var rotMatInv = Bone._tmpMats[0];
  60766. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60767. var rotMat = Bone._tmpMats[1];
  60768. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  60769. rotMatInv.multiplyToRef(rotMat, rotMat);
  60770. this._rotateWithMatrix(rotMat, space, mesh);
  60771. };
  60772. /**
  60773. * Set the rotation matrix of the bone in local of world space.
  60774. * @param rotMat The rotation matrix that the bone should be set to.
  60775. * @param space The space that the rotation is in.
  60776. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60777. */
  60778. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  60779. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60780. var rotMatInv = Bone._tmpMats[0];
  60781. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60782. var rotMat2 = Bone._tmpMats[1];
  60783. rotMat2.copyFrom(rotMat);
  60784. rotMatInv.multiplyToRef(rotMat, rotMat2);
  60785. this._rotateWithMatrix(rotMat2, space, mesh);
  60786. };
  60787. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  60788. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60789. var lmat = this.getLocalMatrix();
  60790. var lx = lmat.m[12];
  60791. var ly = lmat.m[13];
  60792. var lz = lmat.m[14];
  60793. var parent = this.getParent();
  60794. var parentScale = Bone._tmpMats[3];
  60795. var parentScaleInv = Bone._tmpMats[4];
  60796. if (parent) {
  60797. if (space == BABYLON.Space.WORLD) {
  60798. if (mesh) {
  60799. parentScale.copyFrom(mesh.getWorldMatrix());
  60800. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  60801. }
  60802. else {
  60803. parentScale.copyFrom(parent.getAbsoluteTransform());
  60804. }
  60805. }
  60806. else {
  60807. parentScale = parent._scaleMatrix;
  60808. }
  60809. parentScaleInv.copyFrom(parentScale);
  60810. parentScaleInv.invert();
  60811. lmat.multiplyToRef(parentScale, lmat);
  60812. lmat.multiplyToRef(rmat, lmat);
  60813. lmat.multiplyToRef(parentScaleInv, lmat);
  60814. }
  60815. else {
  60816. if (space == BABYLON.Space.WORLD && mesh) {
  60817. parentScale.copyFrom(mesh.getWorldMatrix());
  60818. parentScaleInv.copyFrom(parentScale);
  60819. parentScaleInv.invert();
  60820. lmat.multiplyToRef(parentScale, lmat);
  60821. lmat.multiplyToRef(rmat, lmat);
  60822. lmat.multiplyToRef(parentScaleInv, lmat);
  60823. }
  60824. else {
  60825. lmat.multiplyToRef(rmat, lmat);
  60826. }
  60827. }
  60828. lmat.m[12] = lx;
  60829. lmat.m[13] = ly;
  60830. lmat.m[14] = lz;
  60831. this.computeAbsoluteTransforms();
  60832. this.markAsDirty();
  60833. };
  60834. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  60835. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60836. if (space == BABYLON.Space.WORLD) {
  60837. var scaleMatrix = Bone._tmpMats[2];
  60838. scaleMatrix.copyFrom(this._scaleMatrix);
  60839. rotMatInv.copyFrom(this.getAbsoluteTransform());
  60840. if (mesh) {
  60841. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  60842. var meshScale = Bone._tmpMats[3];
  60843. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  60844. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  60845. }
  60846. rotMatInv.invert();
  60847. scaleMatrix.m[0] *= this._scalingDeterminant;
  60848. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60849. }
  60850. else {
  60851. rotMatInv.copyFrom(this.getLocalMatrix());
  60852. rotMatInv.invert();
  60853. var scaleMatrix = Bone._tmpMats[2];
  60854. scaleMatrix.copyFrom(this._scaleMatrix);
  60855. if (this._parent) {
  60856. var pscaleMatrix = Bone._tmpMats[3];
  60857. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  60858. pscaleMatrix.invert();
  60859. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  60860. }
  60861. else {
  60862. scaleMatrix.m[0] *= this._scalingDeterminant;
  60863. }
  60864. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60865. }
  60866. };
  60867. /**
  60868. * Get the scale of the bone
  60869. * @returns the scale of the bone
  60870. */
  60871. Bone.prototype.getScale = function () {
  60872. return this._scaleVector.clone();
  60873. };
  60874. /**
  60875. * Copy the scale of the bone to a vector3.
  60876. * @param result The vector3 to copy the scale to
  60877. */
  60878. Bone.prototype.getScaleToRef = function (result) {
  60879. result.copyFrom(this._scaleVector);
  60880. };
  60881. /**
  60882. * Get the position of the bone in local or world space.
  60883. * @param space The space that the returned position is in.
  60884. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60885. * @returns The position of the bone
  60886. */
  60887. Bone.prototype.getPosition = function (space, mesh) {
  60888. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60889. if (mesh === void 0) { mesh = null; }
  60890. var pos = BABYLON.Vector3.Zero();
  60891. this.getPositionToRef(space, mesh, pos);
  60892. return pos;
  60893. };
  60894. /**
  60895. * Copy the position of the bone to a vector3 in local or world space.
  60896. * @param space The space that the returned position is in.
  60897. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60898. * @param result The vector3 to copy the position to.
  60899. */
  60900. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  60901. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60902. if (space == BABYLON.Space.LOCAL) {
  60903. var lm = this.getLocalMatrix();
  60904. result.x = lm.m[12];
  60905. result.y = lm.m[13];
  60906. result.z = lm.m[14];
  60907. }
  60908. else {
  60909. var wm = null;
  60910. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60911. if (mesh) {
  60912. wm = mesh.getWorldMatrix();
  60913. }
  60914. this._skeleton.computeAbsoluteTransforms();
  60915. var tmat = Bone._tmpMats[0];
  60916. if (mesh && wm) {
  60917. tmat.copyFrom(this.getAbsoluteTransform());
  60918. tmat.multiplyToRef(wm, tmat);
  60919. }
  60920. else {
  60921. tmat = this.getAbsoluteTransform();
  60922. }
  60923. result.x = tmat.m[12];
  60924. result.y = tmat.m[13];
  60925. result.z = tmat.m[14];
  60926. }
  60927. };
  60928. /**
  60929. * Get the absolute position of the bone (world space).
  60930. * @param mesh The mesh that this bone is attached to.
  60931. * @returns The absolute position of the bone
  60932. */
  60933. Bone.prototype.getAbsolutePosition = function (mesh) {
  60934. if (mesh === void 0) { mesh = null; }
  60935. var pos = BABYLON.Vector3.Zero();
  60936. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  60937. return pos;
  60938. };
  60939. /**
  60940. * Copy the absolute position of the bone (world space) to the result param.
  60941. * @param mesh The mesh that this bone is attached to.
  60942. * @param result The vector3 to copy the absolute position to.
  60943. */
  60944. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  60945. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  60946. };
  60947. /**
  60948. * Compute the absolute transforms of this bone and its children.
  60949. */
  60950. Bone.prototype.computeAbsoluteTransforms = function () {
  60951. if (this._parent) {
  60952. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60953. }
  60954. else {
  60955. this._absoluteTransform.copyFrom(this._localMatrix);
  60956. var poseMatrix = this._skeleton.getPoseMatrix();
  60957. if (poseMatrix) {
  60958. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  60959. }
  60960. }
  60961. var children = this.children;
  60962. var len = children.length;
  60963. for (var i = 0; i < len; i++) {
  60964. children[i].computeAbsoluteTransforms();
  60965. }
  60966. };
  60967. Bone.prototype._syncScaleVector = function () {
  60968. var lm = this.getLocalMatrix();
  60969. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  60970. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  60971. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  60972. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  60973. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  60974. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  60975. this._scaleVector.x = xs * Math.sqrt(xsq);
  60976. this._scaleVector.y = ys * Math.sqrt(ysq);
  60977. this._scaleVector.z = zs * Math.sqrt(zsq);
  60978. if (this._parent) {
  60979. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  60980. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  60981. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  60982. }
  60983. 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);
  60984. };
  60985. /**
  60986. * Get the world direction from an axis that is in the local space of the bone.
  60987. * @param localAxis The local direction that is used to compute the world direction.
  60988. * @param mesh The mesh that this bone is attached to.
  60989. * @returns The world direction
  60990. */
  60991. Bone.prototype.getDirection = function (localAxis, mesh) {
  60992. if (mesh === void 0) { mesh = null; }
  60993. var result = BABYLON.Vector3.Zero();
  60994. this.getDirectionToRef(localAxis, mesh, result);
  60995. return result;
  60996. };
  60997. /**
  60998. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  60999. * @param localAxis The local direction that is used to compute the world direction.
  61000. * @param mesh The mesh that this bone is attached to.
  61001. * @param result The vector3 that the world direction will be copied to.
  61002. */
  61003. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  61004. if (mesh === void 0) { mesh = null; }
  61005. var wm = null;
  61006. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61007. if (mesh) {
  61008. wm = mesh.getWorldMatrix();
  61009. }
  61010. this._skeleton.computeAbsoluteTransforms();
  61011. var mat = Bone._tmpMats[0];
  61012. mat.copyFrom(this.getAbsoluteTransform());
  61013. if (mesh && wm) {
  61014. mat.multiplyToRef(wm, mat);
  61015. }
  61016. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  61017. result.normalize();
  61018. };
  61019. /**
  61020. * Get the euler rotation of the bone in local or world space.
  61021. * @param space The space that the rotation should be in.
  61022. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61023. * @returns The euler rotation
  61024. */
  61025. Bone.prototype.getRotation = function (space, mesh) {
  61026. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61027. if (mesh === void 0) { mesh = null; }
  61028. var result = BABYLON.Vector3.Zero();
  61029. this.getRotationToRef(space, mesh, result);
  61030. return result;
  61031. };
  61032. /**
  61033. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  61034. * @param space The space that the rotation should be in.
  61035. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61036. * @param result The vector3 that the rotation should be copied to.
  61037. */
  61038. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  61039. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61040. if (mesh === void 0) { mesh = null; }
  61041. var quat = Bone._tmpQuat;
  61042. this.getRotationQuaternionToRef(space, mesh, quat);
  61043. quat.toEulerAnglesToRef(result);
  61044. };
  61045. /**
  61046. * Get the quaternion rotation of the bone in either local or world space.
  61047. * @param space The space that the rotation should be in.
  61048. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61049. * @returns The quaternion rotation
  61050. */
  61051. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  61052. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61053. if (mesh === void 0) { mesh = null; }
  61054. var result = BABYLON.Quaternion.Identity();
  61055. this.getRotationQuaternionToRef(space, mesh, result);
  61056. return result;
  61057. };
  61058. /**
  61059. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  61060. * @param space The space that the rotation should be in.
  61061. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61062. * @param result The quaternion that the rotation should be copied to.
  61063. */
  61064. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  61065. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61066. if (mesh === void 0) { mesh = null; }
  61067. if (space == BABYLON.Space.LOCAL) {
  61068. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61069. }
  61070. else {
  61071. var mat = Bone._tmpMats[0];
  61072. var amat = this.getAbsoluteTransform();
  61073. if (mesh) {
  61074. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61075. }
  61076. else {
  61077. mat.copyFrom(amat);
  61078. }
  61079. mat.m[0] *= this._scalingDeterminant;
  61080. mat.m[1] *= this._scalingDeterminant;
  61081. mat.m[2] *= this._scalingDeterminant;
  61082. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61083. }
  61084. };
  61085. /**
  61086. * Get the rotation matrix of the bone in local or world space.
  61087. * @param space The space that the rotation should be in.
  61088. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61089. * @returns The rotation matrix
  61090. */
  61091. Bone.prototype.getRotationMatrix = function (space, mesh) {
  61092. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61093. var result = BABYLON.Matrix.Identity();
  61094. this.getRotationMatrixToRef(space, mesh, result);
  61095. return result;
  61096. };
  61097. /**
  61098. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  61099. * @param space The space that the rotation should be in.
  61100. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61101. * @param result The quaternion that the rotation should be copied to.
  61102. */
  61103. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  61104. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61105. if (space == BABYLON.Space.LOCAL) {
  61106. this.getLocalMatrix().getRotationMatrixToRef(result);
  61107. }
  61108. else {
  61109. var mat = Bone._tmpMats[0];
  61110. var amat = this.getAbsoluteTransform();
  61111. if (mesh) {
  61112. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61113. }
  61114. else {
  61115. mat.copyFrom(amat);
  61116. }
  61117. mat.m[0] *= this._scalingDeterminant;
  61118. mat.m[1] *= this._scalingDeterminant;
  61119. mat.m[2] *= this._scalingDeterminant;
  61120. mat.getRotationMatrixToRef(result);
  61121. }
  61122. };
  61123. /**
  61124. * Get the world position of a point that is in the local space of the bone.
  61125. * @param position The local position
  61126. * @param mesh The mesh that this bone is attached to.
  61127. * @returns The world position
  61128. */
  61129. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  61130. if (mesh === void 0) { mesh = null; }
  61131. var result = BABYLON.Vector3.Zero();
  61132. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  61133. return result;
  61134. };
  61135. /**
  61136. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  61137. * @param position The local position
  61138. * @param mesh The mesh that this bone is attached to.
  61139. * @param result The vector3 that the world position should be copied to.
  61140. */
  61141. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  61142. if (mesh === void 0) { mesh = null; }
  61143. var wm = null;
  61144. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61145. if (mesh) {
  61146. wm = mesh.getWorldMatrix();
  61147. }
  61148. this._skeleton.computeAbsoluteTransforms();
  61149. var tmat = Bone._tmpMats[0];
  61150. if (mesh && wm) {
  61151. tmat.copyFrom(this.getAbsoluteTransform());
  61152. tmat.multiplyToRef(wm, tmat);
  61153. }
  61154. else {
  61155. tmat = this.getAbsoluteTransform();
  61156. }
  61157. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61158. };
  61159. /**
  61160. * Get the local position of a point that is in world space.
  61161. * @param position The world position
  61162. * @param mesh The mesh that this bone is attached to.
  61163. * @returns The local position
  61164. */
  61165. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61166. if (mesh === void 0) { mesh = null; }
  61167. var result = BABYLON.Vector3.Zero();
  61168. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61169. return result;
  61170. };
  61171. /**
  61172. * Get the local position of a point that is in world space and copy it to the result param.
  61173. * @param position The world position
  61174. * @param mesh The mesh that this bone is attached to.
  61175. * @param result The vector3 that the local position should be copied to.
  61176. */
  61177. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61178. if (mesh === void 0) { mesh = null; }
  61179. var wm = null;
  61180. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61181. if (mesh) {
  61182. wm = mesh.getWorldMatrix();
  61183. }
  61184. this._skeleton.computeAbsoluteTransforms();
  61185. var tmat = Bone._tmpMats[0];
  61186. tmat.copyFrom(this.getAbsoluteTransform());
  61187. if (mesh && wm) {
  61188. tmat.multiplyToRef(wm, tmat);
  61189. }
  61190. tmat.invert();
  61191. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61192. };
  61193. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61194. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61195. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61196. return Bone;
  61197. }(BABYLON.Node));
  61198. BABYLON.Bone = Bone;
  61199. })(BABYLON || (BABYLON = {}));
  61200. //# sourceMappingURL=babylon.bone.js.map
  61201. var BABYLON;
  61202. (function (BABYLON) {
  61203. var BoneIKController = /** @class */ (function () {
  61204. function BoneIKController(mesh, bone, options) {
  61205. this.targetPosition = BABYLON.Vector3.Zero();
  61206. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61207. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61208. this.poleAngle = 0;
  61209. this.slerpAmount = 1;
  61210. this._bone1Quat = BABYLON.Quaternion.Identity();
  61211. this._bone1Mat = BABYLON.Matrix.Identity();
  61212. this._bone2Ang = Math.PI;
  61213. this._maxAngle = Math.PI;
  61214. this._rightHandedSystem = false;
  61215. this._bendAxis = BABYLON.Vector3.Right();
  61216. this._slerping = false;
  61217. this._adjustRoll = 0;
  61218. this._bone2 = bone;
  61219. this._bone1 = bone.getParent();
  61220. if (!this._bone1) {
  61221. return;
  61222. }
  61223. this.mesh = mesh;
  61224. var bonePos = bone.getPosition();
  61225. if (bone.getAbsoluteTransform().determinant() > 0) {
  61226. this._rightHandedSystem = true;
  61227. this._bendAxis.x = 0;
  61228. this._bendAxis.y = 0;
  61229. this._bendAxis.z = -1;
  61230. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61231. this._adjustRoll = Math.PI * .5;
  61232. this._bendAxis.z = 1;
  61233. }
  61234. }
  61235. if (this._bone1.length) {
  61236. var boneScale1 = this._bone1.getScale();
  61237. var boneScale2 = this._bone2.getScale();
  61238. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  61239. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  61240. }
  61241. else if (this._bone1.children[0]) {
  61242. mesh.computeWorldMatrix(true);
  61243. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  61244. var pos2 = this._bone2.getAbsolutePosition(mesh);
  61245. var pos3 = this._bone1.getAbsolutePosition(mesh);
  61246. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  61247. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  61248. }
  61249. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  61250. this.maxAngle = Math.PI;
  61251. if (options) {
  61252. if (options.targetMesh) {
  61253. this.targetMesh = options.targetMesh;
  61254. this.targetMesh.computeWorldMatrix(true);
  61255. }
  61256. if (options.poleTargetMesh) {
  61257. this.poleTargetMesh = options.poleTargetMesh;
  61258. this.poleTargetMesh.computeWorldMatrix(true);
  61259. }
  61260. else if (options.poleTargetBone) {
  61261. this.poleTargetBone = options.poleTargetBone;
  61262. }
  61263. else if (this._bone1.getParent()) {
  61264. this.poleTargetBone = this._bone1.getParent();
  61265. }
  61266. if (options.poleTargetLocalOffset) {
  61267. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  61268. }
  61269. if (options.poleAngle) {
  61270. this.poleAngle = options.poleAngle;
  61271. }
  61272. if (options.bendAxis) {
  61273. this._bendAxis.copyFrom(options.bendAxis);
  61274. }
  61275. if (options.maxAngle) {
  61276. this.maxAngle = options.maxAngle;
  61277. }
  61278. if (options.slerpAmount) {
  61279. this.slerpAmount = options.slerpAmount;
  61280. }
  61281. }
  61282. }
  61283. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  61284. get: function () {
  61285. return this._maxAngle;
  61286. },
  61287. set: function (value) {
  61288. this._setMaxAngle(value);
  61289. },
  61290. enumerable: true,
  61291. configurable: true
  61292. });
  61293. BoneIKController.prototype._setMaxAngle = function (ang) {
  61294. if (ang < 0) {
  61295. ang = 0;
  61296. }
  61297. if (ang > Math.PI || ang == undefined) {
  61298. ang = Math.PI;
  61299. }
  61300. this._maxAngle = ang;
  61301. var a = this._bone1Length;
  61302. var b = this._bone2Length;
  61303. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  61304. };
  61305. BoneIKController.prototype.update = function () {
  61306. var bone1 = this._bone1;
  61307. if (!bone1) {
  61308. return;
  61309. }
  61310. var target = this.targetPosition;
  61311. var poleTarget = this.poleTargetPosition;
  61312. var mat1 = BoneIKController._tmpMats[0];
  61313. var mat2 = BoneIKController._tmpMats[1];
  61314. if (this.targetMesh) {
  61315. target.copyFrom(this.targetMesh.getAbsolutePosition());
  61316. }
  61317. if (this.poleTargetBone) {
  61318. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  61319. }
  61320. else if (this.poleTargetMesh) {
  61321. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  61322. }
  61323. var bonePos = BoneIKController._tmpVecs[0];
  61324. var zaxis = BoneIKController._tmpVecs[1];
  61325. var xaxis = BoneIKController._tmpVecs[2];
  61326. var yaxis = BoneIKController._tmpVecs[3];
  61327. var upAxis = BoneIKController._tmpVecs[4];
  61328. var _tmpQuat = BoneIKController._tmpQuat;
  61329. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  61330. poleTarget.subtractToRef(bonePos, upAxis);
  61331. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  61332. upAxis.y = 1;
  61333. }
  61334. else {
  61335. upAxis.normalize();
  61336. }
  61337. target.subtractToRef(bonePos, yaxis);
  61338. yaxis.normalize();
  61339. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  61340. zaxis.normalize();
  61341. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  61342. xaxis.normalize();
  61343. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  61344. var a = this._bone1Length;
  61345. var b = this._bone2Length;
  61346. var c = BABYLON.Vector3.Distance(bonePos, target);
  61347. if (this._maxReach > 0) {
  61348. c = Math.min(this._maxReach, c);
  61349. }
  61350. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  61351. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  61352. if (acosa > 1) {
  61353. acosa = 1;
  61354. }
  61355. if (acosb > 1) {
  61356. acosb = 1;
  61357. }
  61358. if (acosa < -1) {
  61359. acosa = -1;
  61360. }
  61361. if (acosb < -1) {
  61362. acosb = -1;
  61363. }
  61364. var angA = Math.acos(acosa);
  61365. var angB = Math.acos(acosb);
  61366. var angC = -angA - angB;
  61367. if (this._rightHandedSystem) {
  61368. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  61369. mat2.multiplyToRef(mat1, mat1);
  61370. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  61371. mat2.multiplyToRef(mat1, mat1);
  61372. }
  61373. else {
  61374. var _tmpVec = BoneIKController._tmpVecs[5];
  61375. _tmpVec.copyFrom(this._bendAxis);
  61376. _tmpVec.x *= -1;
  61377. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  61378. mat2.multiplyToRef(mat1, mat1);
  61379. }
  61380. if (this.poleAngle) {
  61381. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  61382. mat1.multiplyToRef(mat2, mat1);
  61383. }
  61384. if (this._bone1) {
  61385. if (this.slerpAmount < 1) {
  61386. if (!this._slerping) {
  61387. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  61388. }
  61389. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  61390. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  61391. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  61392. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  61393. this._slerping = true;
  61394. }
  61395. else {
  61396. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  61397. this._bone1Mat.copyFrom(mat1);
  61398. this._slerping = false;
  61399. }
  61400. }
  61401. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  61402. this._bone2Ang = angC;
  61403. };
  61404. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61405. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  61406. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61407. return BoneIKController;
  61408. }());
  61409. BABYLON.BoneIKController = BoneIKController;
  61410. })(BABYLON || (BABYLON = {}));
  61411. //# sourceMappingURL=babylon.boneIKController.js.map
  61412. var BABYLON;
  61413. (function (BABYLON) {
  61414. var BoneLookController = /** @class */ (function () {
  61415. /**
  61416. * Create a BoneLookController
  61417. * @param mesh the mesh that the bone belongs to
  61418. * @param bone the bone that will be looking to the target
  61419. * @param target the target Vector3 to look at
  61420. * @param settings optional settings:
  61421. * - maxYaw: the maximum angle the bone will yaw to
  61422. * - minYaw: the minimum angle the bone will yaw to
  61423. * - maxPitch: the maximum angle the bone will pitch to
  61424. * - minPitch: the minimum angle the bone will yaw to
  61425. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  61426. * - upAxis: the up axis of the coordinate system
  61427. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61428. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  61429. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  61430. * - adjustYaw: used to make an adjustment to the yaw of the bone
  61431. * - adjustPitch: used to make an adjustment to the pitch of the bone
  61432. * - adjustRoll: used to make an adjustment to the roll of the bone
  61433. **/
  61434. function BoneLookController(mesh, bone, target, options) {
  61435. /**
  61436. * The up axis of the coordinate system that is used when the bone is rotated.
  61437. */
  61438. this.upAxis = BABYLON.Vector3.Up();
  61439. /**
  61440. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61441. */
  61442. this.upAxisSpace = BABYLON.Space.LOCAL;
  61443. /**
  61444. * Used to make an adjustment to the yaw of the bone.
  61445. */
  61446. this.adjustYaw = 0;
  61447. /**
  61448. * Used to make an adjustment to the pitch of the bone.
  61449. */
  61450. this.adjustPitch = 0;
  61451. /**
  61452. * Used to make an adjustment to the roll of the bone.
  61453. */
  61454. this.adjustRoll = 0;
  61455. /**
  61456. * 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).
  61457. */
  61458. this.slerpAmount = 1;
  61459. this._boneQuat = BABYLON.Quaternion.Identity();
  61460. this._slerping = false;
  61461. this._firstFrameSkipped = false;
  61462. this._fowardAxis = BABYLON.Vector3.Forward();
  61463. this.mesh = mesh;
  61464. this.bone = bone;
  61465. this.target = target;
  61466. if (options) {
  61467. if (options.adjustYaw) {
  61468. this.adjustYaw = options.adjustYaw;
  61469. }
  61470. if (options.adjustPitch) {
  61471. this.adjustPitch = options.adjustPitch;
  61472. }
  61473. if (options.adjustRoll) {
  61474. this.adjustRoll = options.adjustRoll;
  61475. }
  61476. if (options.maxYaw != null) {
  61477. this.maxYaw = options.maxYaw;
  61478. }
  61479. else {
  61480. this.maxYaw = Math.PI;
  61481. }
  61482. if (options.minYaw != null) {
  61483. this.minYaw = options.minYaw;
  61484. }
  61485. else {
  61486. this.minYaw = -Math.PI;
  61487. }
  61488. if (options.maxPitch != null) {
  61489. this.maxPitch = options.maxPitch;
  61490. }
  61491. else {
  61492. this.maxPitch = Math.PI;
  61493. }
  61494. if (options.minPitch != null) {
  61495. this.minPitch = options.minPitch;
  61496. }
  61497. else {
  61498. this.minPitch = -Math.PI;
  61499. }
  61500. if (options.slerpAmount != null) {
  61501. this.slerpAmount = options.slerpAmount;
  61502. }
  61503. if (options.upAxis != null) {
  61504. this.upAxis = options.upAxis;
  61505. }
  61506. if (options.upAxisSpace != null) {
  61507. this.upAxisSpace = options.upAxisSpace;
  61508. }
  61509. if (options.yawAxis != null || options.pitchAxis != null) {
  61510. var newYawAxis = BABYLON.Axis.Y;
  61511. var newPitchAxis = BABYLON.Axis.X;
  61512. if (options.yawAxis != null) {
  61513. newYawAxis = options.yawAxis.clone();
  61514. newYawAxis.normalize();
  61515. }
  61516. if (options.pitchAxis != null) {
  61517. newPitchAxis = options.pitchAxis.clone();
  61518. newPitchAxis.normalize();
  61519. }
  61520. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  61521. this._transformYawPitch = BABYLON.Matrix.Identity();
  61522. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  61523. this._transformYawPitchInv = this._transformYawPitch.clone();
  61524. this._transformYawPitch.invert();
  61525. }
  61526. }
  61527. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  61528. this.upAxisSpace = BABYLON.Space.LOCAL;
  61529. }
  61530. }
  61531. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  61532. /**
  61533. * Get/set the minimum yaw angle that the bone can look to.
  61534. */
  61535. get: function () {
  61536. return this._minYaw;
  61537. },
  61538. set: function (value) {
  61539. this._minYaw = value;
  61540. this._minYawSin = Math.sin(value);
  61541. this._minYawCos = Math.cos(value);
  61542. if (this._maxYaw != null) {
  61543. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61544. this._yawRange = this._maxYaw - this._minYaw;
  61545. }
  61546. },
  61547. enumerable: true,
  61548. configurable: true
  61549. });
  61550. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  61551. /**
  61552. * Get/set the maximum yaw angle that the bone can look to.
  61553. */
  61554. get: function () {
  61555. return this._maxYaw;
  61556. },
  61557. set: function (value) {
  61558. this._maxYaw = value;
  61559. this._maxYawSin = Math.sin(value);
  61560. this._maxYawCos = Math.cos(value);
  61561. if (this._minYaw != null) {
  61562. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61563. this._yawRange = this._maxYaw - this._minYaw;
  61564. }
  61565. },
  61566. enumerable: true,
  61567. configurable: true
  61568. });
  61569. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  61570. /**
  61571. * Get/set the minimum pitch angle that the bone can look to.
  61572. */
  61573. get: function () {
  61574. return this._minPitch;
  61575. },
  61576. set: function (value) {
  61577. this._minPitch = value;
  61578. this._minPitchTan = Math.tan(value);
  61579. },
  61580. enumerable: true,
  61581. configurable: true
  61582. });
  61583. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  61584. /**
  61585. * Get/set the maximum pitch angle that the bone can look to.
  61586. */
  61587. get: function () {
  61588. return this._maxPitch;
  61589. },
  61590. set: function (value) {
  61591. this._maxPitch = value;
  61592. this._maxPitchTan = Math.tan(value);
  61593. },
  61594. enumerable: true,
  61595. configurable: true
  61596. });
  61597. /**
  61598. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  61599. */
  61600. BoneLookController.prototype.update = function () {
  61601. //skip the first frame when slerping so that the mesh rotation is correct
  61602. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  61603. this._firstFrameSkipped = true;
  61604. return;
  61605. }
  61606. var bone = this.bone;
  61607. var bonePos = BoneLookController._tmpVecs[0];
  61608. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  61609. var target = this.target;
  61610. var _tmpMat1 = BoneLookController._tmpMats[0];
  61611. var _tmpMat2 = BoneLookController._tmpMats[1];
  61612. var mesh = this.mesh;
  61613. var parentBone = bone.getParent();
  61614. var upAxis = BoneLookController._tmpVecs[1];
  61615. upAxis.copyFrom(this.upAxis);
  61616. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  61617. if (this._transformYawPitch) {
  61618. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  61619. }
  61620. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  61621. }
  61622. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  61623. mesh.getDirectionToRef(upAxis, upAxis);
  61624. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  61625. upAxis.normalize();
  61626. }
  61627. }
  61628. var checkYaw = false;
  61629. var checkPitch = false;
  61630. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  61631. checkYaw = true;
  61632. }
  61633. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  61634. checkPitch = true;
  61635. }
  61636. if (checkYaw || checkPitch) {
  61637. var spaceMat = BoneLookController._tmpMats[2];
  61638. var spaceMatInv = BoneLookController._tmpMats[3];
  61639. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  61640. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  61641. }
  61642. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  61643. spaceMat.copyFrom(mesh.getWorldMatrix());
  61644. }
  61645. else {
  61646. var forwardAxis = BoneLookController._tmpVecs[2];
  61647. forwardAxis.copyFrom(this._fowardAxis);
  61648. if (this._transformYawPitch) {
  61649. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  61650. }
  61651. if (parentBone) {
  61652. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  61653. }
  61654. else {
  61655. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  61656. }
  61657. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  61658. rightAxis.normalize();
  61659. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  61660. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  61661. }
  61662. spaceMat.invertToRef(spaceMatInv);
  61663. var xzlen = null;
  61664. if (checkPitch) {
  61665. var localTarget = BoneLookController._tmpVecs[3];
  61666. target.subtractToRef(bonePos, localTarget);
  61667. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61668. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61669. var pitch = Math.atan2(localTarget.y, xzlen);
  61670. var newPitch = pitch;
  61671. if (pitch > this._maxPitch) {
  61672. localTarget.y = this._maxPitchTan * xzlen;
  61673. newPitch = this._maxPitch;
  61674. }
  61675. else if (pitch < this._minPitch) {
  61676. localTarget.y = this._minPitchTan * xzlen;
  61677. newPitch = this._minPitch;
  61678. }
  61679. if (pitch != newPitch) {
  61680. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61681. localTarget.addInPlace(bonePos);
  61682. target = localTarget;
  61683. }
  61684. }
  61685. if (checkYaw) {
  61686. var localTarget = BoneLookController._tmpVecs[4];
  61687. target.subtractToRef(bonePos, localTarget);
  61688. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61689. var yaw = Math.atan2(localTarget.x, localTarget.z);
  61690. var newYaw = yaw;
  61691. if (yaw > this._maxYaw || yaw < this._minYaw) {
  61692. if (xzlen == null) {
  61693. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61694. }
  61695. if (this._yawRange > Math.PI) {
  61696. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  61697. localTarget.z = this._maxYawCos * xzlen;
  61698. localTarget.x = this._maxYawSin * xzlen;
  61699. newYaw = this._maxYaw;
  61700. }
  61701. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  61702. localTarget.z = this._minYawCos * xzlen;
  61703. localTarget.x = this._minYawSin * xzlen;
  61704. newYaw = this._minYaw;
  61705. }
  61706. }
  61707. else {
  61708. if (yaw > this._maxYaw) {
  61709. localTarget.z = this._maxYawCos * xzlen;
  61710. localTarget.x = this._maxYawSin * xzlen;
  61711. newYaw = this._maxYaw;
  61712. }
  61713. else if (yaw < this._minYaw) {
  61714. localTarget.z = this._minYawCos * xzlen;
  61715. localTarget.x = this._minYawSin * xzlen;
  61716. newYaw = this._minYaw;
  61717. }
  61718. }
  61719. }
  61720. if (this._slerping && this._yawRange > Math.PI) {
  61721. //are we going to be crossing into the min/max region?
  61722. var boneFwd = BoneLookController._tmpVecs[8];
  61723. boneFwd.copyFrom(BABYLON.Axis.Z);
  61724. if (this._transformYawPitch) {
  61725. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  61726. }
  61727. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  61728. this._boneQuat.toRotationMatrix(boneRotMat);
  61729. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  61730. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  61731. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  61732. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  61733. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  61734. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  61735. if (angBtwTar > angBtwMidYaw) {
  61736. if (xzlen == null) {
  61737. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61738. }
  61739. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  61740. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  61741. if (angBtwMin < angBtwMax) {
  61742. newYaw = boneYaw + Math.PI * .75;
  61743. localTarget.z = Math.cos(newYaw) * xzlen;
  61744. localTarget.x = Math.sin(newYaw) * xzlen;
  61745. }
  61746. else {
  61747. newYaw = boneYaw - Math.PI * .75;
  61748. localTarget.z = Math.cos(newYaw) * xzlen;
  61749. localTarget.x = Math.sin(newYaw) * xzlen;
  61750. }
  61751. }
  61752. }
  61753. if (yaw != newYaw) {
  61754. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61755. localTarget.addInPlace(bonePos);
  61756. target = localTarget;
  61757. }
  61758. }
  61759. }
  61760. var zaxis = BoneLookController._tmpVecs[5];
  61761. var xaxis = BoneLookController._tmpVecs[6];
  61762. var yaxis = BoneLookController._tmpVecs[7];
  61763. var _tmpQuat = BoneLookController._tmpQuat;
  61764. target.subtractToRef(bonePos, zaxis);
  61765. zaxis.normalize();
  61766. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  61767. xaxis.normalize();
  61768. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  61769. yaxis.normalize();
  61770. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  61771. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  61772. return;
  61773. }
  61774. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  61775. return;
  61776. }
  61777. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  61778. return;
  61779. }
  61780. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  61781. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  61782. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  61783. }
  61784. if (this.slerpAmount < 1) {
  61785. if (!this._slerping) {
  61786. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  61787. }
  61788. if (this._transformYawPitch) {
  61789. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61790. }
  61791. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  61792. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  61793. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  61794. this._slerping = true;
  61795. }
  61796. else {
  61797. if (this._transformYawPitch) {
  61798. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61799. }
  61800. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  61801. this._slerping = false;
  61802. }
  61803. };
  61804. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  61805. var angDiff = ang2 - ang1;
  61806. angDiff %= Math.PI * 2;
  61807. if (angDiff > Math.PI) {
  61808. angDiff -= Math.PI * 2;
  61809. }
  61810. else if (angDiff < -Math.PI) {
  61811. angDiff += Math.PI * 2;
  61812. }
  61813. return angDiff;
  61814. };
  61815. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  61816. ang1 %= (2 * Math.PI);
  61817. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61818. ang2 %= (2 * Math.PI);
  61819. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61820. var ab = 0;
  61821. if (ang1 < ang2) {
  61822. ab = ang2 - ang1;
  61823. }
  61824. else {
  61825. ab = ang1 - ang2;
  61826. }
  61827. if (ab > Math.PI) {
  61828. ab = Math.PI * 2 - ab;
  61829. }
  61830. return ab;
  61831. };
  61832. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  61833. ang %= (2 * Math.PI);
  61834. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  61835. ang1 %= (2 * Math.PI);
  61836. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61837. ang2 %= (2 * Math.PI);
  61838. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61839. if (ang1 < ang2) {
  61840. if (ang > ang1 && ang < ang2) {
  61841. return true;
  61842. }
  61843. }
  61844. else {
  61845. if (ang > ang2 && ang < ang1) {
  61846. return true;
  61847. }
  61848. }
  61849. return false;
  61850. };
  61851. 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()];
  61852. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  61853. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61854. return BoneLookController;
  61855. }());
  61856. BABYLON.BoneLookController = BoneLookController;
  61857. })(BABYLON || (BABYLON = {}));
  61858. //# sourceMappingURL=babylon.boneLookController.js.map
  61859. var BABYLON;
  61860. (function (BABYLON) {
  61861. var Skeleton = /** @class */ (function () {
  61862. function Skeleton(name, id, scene) {
  61863. this.name = name;
  61864. this.id = id;
  61865. this.bones = new Array();
  61866. this.needInitialSkinMatrix = false;
  61867. this._isDirty = true;
  61868. this._meshesWithPoseMatrix = new Array();
  61869. this._identity = BABYLON.Matrix.Identity();
  61870. this._ranges = {};
  61871. this._lastAbsoluteTransformsUpdateId = -1;
  61872. // Events
  61873. /**
  61874. * An event triggered before computing the skeleton's matrices
  61875. * @type {BABYLON.Observable}
  61876. */
  61877. this.onBeforeComputeObservable = new BABYLON.Observable();
  61878. this.bones = [];
  61879. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61880. scene.skeletons.push(this);
  61881. //make sure it will recalculate the matrix next time prepare is called.
  61882. this._isDirty = true;
  61883. }
  61884. // Members
  61885. Skeleton.prototype.getTransformMatrices = function (mesh) {
  61886. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  61887. return mesh._bonesTransformMatrices;
  61888. }
  61889. if (!this._transformMatrices) {
  61890. this.prepare();
  61891. }
  61892. return this._transformMatrices;
  61893. };
  61894. Skeleton.prototype.getScene = function () {
  61895. return this._scene;
  61896. };
  61897. // Methods
  61898. /**
  61899. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  61900. */
  61901. Skeleton.prototype.toString = function (fullDetails) {
  61902. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  61903. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  61904. if (fullDetails) {
  61905. ret += ", Ranges: {";
  61906. var first = true;
  61907. for (var name_1 in this._ranges) {
  61908. if (first) {
  61909. ret += ", ";
  61910. first = false;
  61911. }
  61912. ret += name_1;
  61913. }
  61914. ret += "}";
  61915. }
  61916. return ret;
  61917. };
  61918. /**
  61919. * Get bone's index searching by name
  61920. * @param {string} name is bone's name to search for
  61921. * @return {number} Indice of the bone. Returns -1 if not found
  61922. */
  61923. Skeleton.prototype.getBoneIndexByName = function (name) {
  61924. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  61925. if (this.bones[boneIndex].name === name) {
  61926. return boneIndex;
  61927. }
  61928. }
  61929. return -1;
  61930. };
  61931. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  61932. // check name not already in use
  61933. if (!this._ranges[name]) {
  61934. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  61935. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61936. if (this.bones[i].animations[0]) {
  61937. this.bones[i].animations[0].createRange(name, from, to);
  61938. }
  61939. }
  61940. }
  61941. };
  61942. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  61943. if (deleteFrames === void 0) { deleteFrames = true; }
  61944. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61945. if (this.bones[i].animations[0]) {
  61946. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  61947. }
  61948. }
  61949. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  61950. };
  61951. Skeleton.prototype.getAnimationRange = function (name) {
  61952. return this._ranges[name];
  61953. };
  61954. /**
  61955. * Returns as an Array, all AnimationRanges defined on this skeleton
  61956. */
  61957. Skeleton.prototype.getAnimationRanges = function () {
  61958. var animationRanges = [];
  61959. var name;
  61960. var i = 0;
  61961. for (name in this._ranges) {
  61962. animationRanges[i] = this._ranges[name];
  61963. i++;
  61964. }
  61965. return animationRanges;
  61966. };
  61967. /**
  61968. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  61969. */
  61970. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  61971. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61972. if (this._ranges[name] || !source.getAnimationRange(name)) {
  61973. return false;
  61974. }
  61975. var ret = true;
  61976. var frameOffset = this._getHighestAnimationFrame() + 1;
  61977. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  61978. var boneDict = {};
  61979. var sourceBones = source.bones;
  61980. var nBones;
  61981. var i;
  61982. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  61983. boneDict[sourceBones[i].name] = sourceBones[i];
  61984. }
  61985. if (this.bones.length !== sourceBones.length) {
  61986. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  61987. ret = false;
  61988. }
  61989. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  61990. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  61991. var boneName = this.bones[i].name;
  61992. var sourceBone = boneDict[boneName];
  61993. if (sourceBone) {
  61994. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  61995. }
  61996. else {
  61997. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  61998. ret = false;
  61999. }
  62000. }
  62001. // do not call createAnimationRange(), since it also is done to bones, which was already done
  62002. var range = source.getAnimationRange(name);
  62003. if (range) {
  62004. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  62005. }
  62006. return ret;
  62007. };
  62008. Skeleton.prototype.returnToRest = function () {
  62009. for (var index = 0; index < this.bones.length; index++) {
  62010. this.bones[index].returnToRest();
  62011. }
  62012. };
  62013. Skeleton.prototype._getHighestAnimationFrame = function () {
  62014. var ret = 0;
  62015. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62016. if (this.bones[i].animations[0]) {
  62017. var highest = this.bones[i].animations[0].getHighestFrame();
  62018. if (ret < highest) {
  62019. ret = highest;
  62020. }
  62021. }
  62022. }
  62023. return ret;
  62024. };
  62025. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  62026. var range = this.getAnimationRange(name);
  62027. if (!range) {
  62028. return null;
  62029. }
  62030. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  62031. };
  62032. Skeleton.prototype._markAsDirty = function () {
  62033. this._isDirty = true;
  62034. };
  62035. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  62036. this._meshesWithPoseMatrix.push(mesh);
  62037. };
  62038. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  62039. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  62040. if (index > -1) {
  62041. this._meshesWithPoseMatrix.splice(index, 1);
  62042. }
  62043. };
  62044. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  62045. this.onBeforeComputeObservable.notifyObservers(this);
  62046. for (var index = 0; index < this.bones.length; index++) {
  62047. var bone = this.bones[index];
  62048. var parentBone = bone.getParent();
  62049. if (parentBone) {
  62050. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  62051. }
  62052. else {
  62053. if (initialSkinMatrix) {
  62054. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  62055. }
  62056. else {
  62057. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  62058. }
  62059. }
  62060. if (bone._index !== -1) {
  62061. var mappedIndex = bone._index === null ? index : bone._index;
  62062. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  62063. }
  62064. }
  62065. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  62066. };
  62067. Skeleton.prototype.prepare = function () {
  62068. if (!this._isDirty) {
  62069. return;
  62070. }
  62071. if (this.needInitialSkinMatrix) {
  62072. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  62073. var mesh = this._meshesWithPoseMatrix[index];
  62074. var poseMatrix = mesh.getPoseMatrix();
  62075. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  62076. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62077. }
  62078. if (this._synchronizedWithMesh !== mesh) {
  62079. this._synchronizedWithMesh = mesh;
  62080. // Prepare bones
  62081. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  62082. var bone = this.bones[boneIndex];
  62083. if (!bone.getParent()) {
  62084. var matrix = bone.getBaseMatrix();
  62085. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  62086. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  62087. }
  62088. }
  62089. }
  62090. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  62091. }
  62092. }
  62093. else {
  62094. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  62095. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62096. }
  62097. this._computeTransformMatrices(this._transformMatrices, null);
  62098. }
  62099. this._isDirty = false;
  62100. this._scene._activeBones.addCount(this.bones.length, false);
  62101. };
  62102. Skeleton.prototype.getAnimatables = function () {
  62103. if (!this._animatables || this._animatables.length !== this.bones.length) {
  62104. this._animatables = [];
  62105. for (var index = 0; index < this.bones.length; index++) {
  62106. this._animatables.push(this.bones[index]);
  62107. }
  62108. }
  62109. return this._animatables;
  62110. };
  62111. Skeleton.prototype.clone = function (name, id) {
  62112. var result = new Skeleton(name, id || name, this._scene);
  62113. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62114. for (var index = 0; index < this.bones.length; index++) {
  62115. var source = this.bones[index];
  62116. var parentBone = null;
  62117. var parent_1 = source.getParent();
  62118. if (parent_1) {
  62119. var parentIndex = this.bones.indexOf(parent_1);
  62120. parentBone = result.bones[parentIndex];
  62121. }
  62122. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  62123. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  62124. }
  62125. if (this._ranges) {
  62126. result._ranges = {};
  62127. for (var rangeName in this._ranges) {
  62128. var range = this._ranges[rangeName];
  62129. if (range) {
  62130. result._ranges[rangeName] = range.clone();
  62131. }
  62132. }
  62133. }
  62134. this._isDirty = true;
  62135. return result;
  62136. };
  62137. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  62138. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  62139. this.bones.forEach(function (bone) {
  62140. bone.animations.forEach(function (animation) {
  62141. animation.enableBlending = true;
  62142. animation.blendingSpeed = blendingSpeed;
  62143. });
  62144. });
  62145. };
  62146. Skeleton.prototype.dispose = function () {
  62147. this._meshesWithPoseMatrix = [];
  62148. // Animations
  62149. this.getScene().stopAnimation(this);
  62150. // Remove from scene
  62151. this.getScene().removeSkeleton(this);
  62152. };
  62153. Skeleton.prototype.serialize = function () {
  62154. var serializationObject = {};
  62155. serializationObject.name = this.name;
  62156. serializationObject.id = this.id;
  62157. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  62158. serializationObject.bones = [];
  62159. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62160. for (var index = 0; index < this.bones.length; index++) {
  62161. var bone = this.bones[index];
  62162. var parent_2 = bone.getParent();
  62163. var serializedBone = {
  62164. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62165. name: bone.name,
  62166. matrix: bone.getBaseMatrix().toArray(),
  62167. rest: bone.getRestPose().toArray()
  62168. };
  62169. serializationObject.bones.push(serializedBone);
  62170. if (bone.length) {
  62171. serializedBone.length = bone.length;
  62172. }
  62173. if (bone.animations && bone.animations.length > 0) {
  62174. serializedBone.animation = bone.animations[0].serialize();
  62175. }
  62176. serializationObject.ranges = [];
  62177. for (var name in this._ranges) {
  62178. var source = this._ranges[name];
  62179. if (!source) {
  62180. continue;
  62181. }
  62182. var range = {};
  62183. range.name = name;
  62184. range.from = source.from;
  62185. range.to = source.to;
  62186. serializationObject.ranges.push(range);
  62187. }
  62188. }
  62189. return serializationObject;
  62190. };
  62191. Skeleton.Parse = function (parsedSkeleton, scene) {
  62192. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62193. if (parsedSkeleton.dimensionsAtRest) {
  62194. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62195. }
  62196. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62197. var index;
  62198. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62199. var parsedBone = parsedSkeleton.bones[index];
  62200. var parentBone = null;
  62201. if (parsedBone.parentBoneIndex > -1) {
  62202. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62203. }
  62204. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62205. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62206. if (parsedBone.length) {
  62207. bone.length = parsedBone.length;
  62208. }
  62209. if (parsedBone.animation) {
  62210. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62211. }
  62212. }
  62213. // placed after bones, so createAnimationRange can cascade down
  62214. if (parsedSkeleton.ranges) {
  62215. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62216. var data = parsedSkeleton.ranges[index];
  62217. skeleton.createAnimationRange(data.name, data.from, data.to);
  62218. }
  62219. }
  62220. return skeleton;
  62221. };
  62222. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62223. if (forceUpdate === void 0) { forceUpdate = false; }
  62224. var renderId = this._scene.getRenderId();
  62225. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62226. this.bones[0].computeAbsoluteTransforms();
  62227. this._lastAbsoluteTransformsUpdateId = renderId;
  62228. }
  62229. };
  62230. Skeleton.prototype.getPoseMatrix = function () {
  62231. var poseMatrix = null;
  62232. if (this._meshesWithPoseMatrix.length > 0) {
  62233. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62234. }
  62235. return poseMatrix;
  62236. };
  62237. Skeleton.prototype.sortBones = function () {
  62238. var bones = new Array();
  62239. var visited = new Array(this.bones.length);
  62240. for (var index = 0; index < this.bones.length; index++) {
  62241. this._sortBones(index, bones, visited);
  62242. }
  62243. this.bones = bones;
  62244. };
  62245. Skeleton.prototype._sortBones = function (index, bones, visited) {
  62246. if (visited[index]) {
  62247. return;
  62248. }
  62249. visited[index] = true;
  62250. var bone = this.bones[index];
  62251. if (bone._index === undefined) {
  62252. bone._index = index;
  62253. }
  62254. var parentBone = bone.getParent();
  62255. if (parentBone) {
  62256. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  62257. }
  62258. bones.push(bone);
  62259. };
  62260. return Skeleton;
  62261. }());
  62262. BABYLON.Skeleton = Skeleton;
  62263. })(BABYLON || (BABYLON = {}));
  62264. //# sourceMappingURL=babylon.skeleton.js.map
  62265. var BABYLON;
  62266. (function (BABYLON) {
  62267. var SphericalPolynomial = /** @class */ (function () {
  62268. function SphericalPolynomial() {
  62269. this.x = BABYLON.Vector3.Zero();
  62270. this.y = BABYLON.Vector3.Zero();
  62271. this.z = BABYLON.Vector3.Zero();
  62272. this.xx = BABYLON.Vector3.Zero();
  62273. this.yy = BABYLON.Vector3.Zero();
  62274. this.zz = BABYLON.Vector3.Zero();
  62275. this.xy = BABYLON.Vector3.Zero();
  62276. this.yz = BABYLON.Vector3.Zero();
  62277. this.zx = BABYLON.Vector3.Zero();
  62278. }
  62279. SphericalPolynomial.prototype.addAmbient = function (color) {
  62280. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62281. this.xx = this.xx.add(colorVector);
  62282. this.yy = this.yy.add(colorVector);
  62283. this.zz = this.zz.add(colorVector);
  62284. };
  62285. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  62286. var result = new SphericalPolynomial();
  62287. result.x = harmonics.L11.scale(1.02333);
  62288. result.y = harmonics.L1_1.scale(1.02333);
  62289. result.z = harmonics.L10.scale(1.02333);
  62290. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  62291. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  62292. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  62293. result.yz = harmonics.L2_1.scale(0.858086);
  62294. result.zx = harmonics.L21.scale(0.858086);
  62295. result.xy = harmonics.L2_2.scale(0.858086);
  62296. result.scale(1.0 / Math.PI);
  62297. return result;
  62298. };
  62299. SphericalPolynomial.prototype.scale = function (scale) {
  62300. this.x = this.x.scale(scale);
  62301. this.y = this.y.scale(scale);
  62302. this.z = this.z.scale(scale);
  62303. this.xx = this.xx.scale(scale);
  62304. this.yy = this.yy.scale(scale);
  62305. this.zz = this.zz.scale(scale);
  62306. this.yz = this.yz.scale(scale);
  62307. this.zx = this.zx.scale(scale);
  62308. this.xy = this.xy.scale(scale);
  62309. };
  62310. return SphericalPolynomial;
  62311. }());
  62312. BABYLON.SphericalPolynomial = SphericalPolynomial;
  62313. var SphericalHarmonics = /** @class */ (function () {
  62314. function SphericalHarmonics() {
  62315. this.L00 = BABYLON.Vector3.Zero();
  62316. this.L1_1 = BABYLON.Vector3.Zero();
  62317. this.L10 = BABYLON.Vector3.Zero();
  62318. this.L11 = BABYLON.Vector3.Zero();
  62319. this.L2_2 = BABYLON.Vector3.Zero();
  62320. this.L2_1 = BABYLON.Vector3.Zero();
  62321. this.L20 = BABYLON.Vector3.Zero();
  62322. this.L21 = BABYLON.Vector3.Zero();
  62323. this.L22 = BABYLON.Vector3.Zero();
  62324. }
  62325. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  62326. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62327. var c = colorVector.scale(deltaSolidAngle);
  62328. this.L00 = this.L00.add(c.scale(0.282095));
  62329. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  62330. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  62331. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  62332. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  62333. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  62334. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  62335. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  62336. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  62337. };
  62338. SphericalHarmonics.prototype.scale = function (scale) {
  62339. this.L00 = this.L00.scale(scale);
  62340. this.L1_1 = this.L1_1.scale(scale);
  62341. this.L10 = this.L10.scale(scale);
  62342. this.L11 = this.L11.scale(scale);
  62343. this.L2_2 = this.L2_2.scale(scale);
  62344. this.L2_1 = this.L2_1.scale(scale);
  62345. this.L20 = this.L20.scale(scale);
  62346. this.L21 = this.L21.scale(scale);
  62347. this.L22 = this.L22.scale(scale);
  62348. };
  62349. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  62350. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  62351. //
  62352. // E_lm = A_l * L_lm
  62353. //
  62354. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  62355. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  62356. // the scaling factors are given in equation 9.
  62357. // Constant (Band 0)
  62358. this.L00 = this.L00.scale(3.141593);
  62359. // Linear (Band 1)
  62360. this.L1_1 = this.L1_1.scale(2.094395);
  62361. this.L10 = this.L10.scale(2.094395);
  62362. this.L11 = this.L11.scale(2.094395);
  62363. // Quadratic (Band 2)
  62364. this.L2_2 = this.L2_2.scale(0.785398);
  62365. this.L2_1 = this.L2_1.scale(0.785398);
  62366. this.L20 = this.L20.scale(0.785398);
  62367. this.L21 = this.L21.scale(0.785398);
  62368. this.L22 = this.L22.scale(0.785398);
  62369. };
  62370. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  62371. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  62372. // L = (1/pi) * E * rho
  62373. //
  62374. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  62375. this.scale(1.0 / Math.PI);
  62376. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  62377. // (The pixel shader must apply albedo after texture fetches, etc).
  62378. };
  62379. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  62380. var result = new SphericalHarmonics();
  62381. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  62382. result.L1_1 = polynomial.y.scale(0.977204);
  62383. result.L10 = polynomial.z.scale(0.977204);
  62384. result.L11 = polynomial.x.scale(0.977204);
  62385. result.L2_2 = polynomial.xy.scale(1.16538);
  62386. result.L2_1 = polynomial.yz.scale(1.16538);
  62387. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  62388. result.L21 = polynomial.zx.scale(1.16538);
  62389. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  62390. result.scale(Math.PI);
  62391. return result;
  62392. };
  62393. return SphericalHarmonics;
  62394. }());
  62395. BABYLON.SphericalHarmonics = SphericalHarmonics;
  62396. })(BABYLON || (BABYLON = {}));
  62397. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  62398. var BABYLON;
  62399. (function (BABYLON) {
  62400. var Internals;
  62401. (function (Internals) {
  62402. var FileFaceOrientation = /** @class */ (function () {
  62403. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  62404. this.name = name;
  62405. this.worldAxisForNormal = worldAxisForNormal;
  62406. this.worldAxisForFileX = worldAxisForFileX;
  62407. this.worldAxisForFileY = worldAxisForFileY;
  62408. }
  62409. return FileFaceOrientation;
  62410. }());
  62411. ;
  62412. /**
  62413. * Helper class dealing with the extraction of spherical polynomial dataArray
  62414. * from a cube map.
  62415. */
  62416. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  62417. function CubeMapToSphericalPolynomialTools() {
  62418. }
  62419. /**
  62420. * Converts a texture to the according Spherical Polynomial data.
  62421. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62422. *
  62423. * @param texture The texture to extract the information from.
  62424. * @return The Spherical Polynomial data.
  62425. */
  62426. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  62427. if (!texture.isCube) {
  62428. // Only supports cube Textures currently.
  62429. return null;
  62430. }
  62431. var size = texture.getSize().width;
  62432. var right = texture.readPixels(0);
  62433. var left = texture.readPixels(1);
  62434. var up;
  62435. var down;
  62436. if (texture.isRenderTarget) {
  62437. up = texture.readPixels(3);
  62438. down = texture.readPixels(2);
  62439. }
  62440. else {
  62441. up = texture.readPixels(2);
  62442. down = texture.readPixels(3);
  62443. }
  62444. var front = texture.readPixels(4);
  62445. var back = texture.readPixels(5);
  62446. var gammaSpace = texture.gammaSpace;
  62447. // Always read as RGBA.
  62448. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  62449. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62450. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62451. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62452. }
  62453. var cubeInfo = {
  62454. size: size,
  62455. right: right,
  62456. left: left,
  62457. up: up,
  62458. down: down,
  62459. front: front,
  62460. back: back,
  62461. format: format,
  62462. type: type,
  62463. gammaSpace: gammaSpace,
  62464. };
  62465. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  62466. };
  62467. /**
  62468. * Converts a cubemap to the according Spherical Polynomial data.
  62469. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62470. *
  62471. * @param cubeInfo The Cube map to extract the information from.
  62472. * @return The Spherical Polynomial data.
  62473. */
  62474. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  62475. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  62476. var totalSolidAngle = 0.0;
  62477. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  62478. var du = 2.0 / cubeInfo.size;
  62479. var dv = du;
  62480. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  62481. var minUV = du * 0.5 - 1.0;
  62482. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62483. var fileFace = this.FileFaces[faceIndex];
  62484. var dataArray = cubeInfo[fileFace.name];
  62485. var v = minUV;
  62486. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  62487. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  62488. // Because SP is still linear, so summation is fine in that basis.
  62489. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  62490. for (var y = 0; y < cubeInfo.size; y++) {
  62491. var u = minUV;
  62492. for (var x = 0; x < cubeInfo.size; x++) {
  62493. // World direction (not normalised)
  62494. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  62495. worldDirection.normalize();
  62496. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  62497. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  62498. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  62499. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  62500. // Handle Integer types.
  62501. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62502. r /= 255;
  62503. g /= 255;
  62504. b /= 255;
  62505. }
  62506. // Handle Gamma space textures.
  62507. if (cubeInfo.gammaSpace) {
  62508. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  62509. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  62510. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  62511. }
  62512. var color = new BABYLON.Color3(r, g, b);
  62513. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  62514. totalSolidAngle += deltaSolidAngle;
  62515. u += du;
  62516. }
  62517. v += dv;
  62518. }
  62519. }
  62520. // Solid angle for entire sphere is 4*pi
  62521. var sphereSolidAngle = 4.0 * Math.PI;
  62522. // Adjust the solid angle to allow for how many faces we processed.
  62523. var facesProcessed = 6.0;
  62524. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  62525. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  62526. // This is needed because the numerical integration over the cube uses a
  62527. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  62528. // and also to compensate for accumulative error due to float precision in the summation.
  62529. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  62530. sphericalHarmonics.scale(correctionFactor);
  62531. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  62532. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  62533. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  62534. };
  62535. CubeMapToSphericalPolynomialTools.FileFaces = [
  62536. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  62537. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  62538. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  62539. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  62540. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  62541. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  62542. ];
  62543. return CubeMapToSphericalPolynomialTools;
  62544. }());
  62545. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  62546. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62547. })(BABYLON || (BABYLON = {}));
  62548. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  62549. var BABYLON;
  62550. (function (BABYLON) {
  62551. var Internals;
  62552. (function (Internals) {
  62553. /**
  62554. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  62555. */
  62556. var PanoramaToCubeMapTools = /** @class */ (function () {
  62557. function PanoramaToCubeMapTools() {
  62558. }
  62559. /**
  62560. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  62561. *
  62562. * @param float32Array The source data.
  62563. * @param inputWidth The width of the input panorama.
  62564. * @param inputhHeight The height of the input panorama.
  62565. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  62566. * @return The cubemap data
  62567. */
  62568. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  62569. if (!float32Array) {
  62570. throw "ConvertPanoramaToCubemap: input cannot be null";
  62571. }
  62572. if (float32Array.length != inputWidth * inputHeight * 3) {
  62573. throw "ConvertPanoramaToCubemap: input size is wrong";
  62574. }
  62575. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  62576. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  62577. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  62578. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  62579. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  62580. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  62581. return {
  62582. front: textureFront,
  62583. back: textureBack,
  62584. left: textureLeft,
  62585. right: textureRight,
  62586. up: textureUp,
  62587. down: textureDown,
  62588. size: size,
  62589. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  62590. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  62591. gammaSpace: false,
  62592. };
  62593. };
  62594. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  62595. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  62596. var textureArray = new Float32Array(buffer);
  62597. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  62598. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  62599. var dy = 1 / texSize;
  62600. var fy = 0;
  62601. for (var y = 0; y < texSize; y++) {
  62602. var xv1 = faceData[0];
  62603. var xv2 = faceData[2];
  62604. for (var x = 0; x < texSize; x++) {
  62605. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  62606. v.normalize();
  62607. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  62608. // 3 channels per pixels
  62609. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  62610. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  62611. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  62612. xv1 = xv1.add(rotDX1);
  62613. xv2 = xv2.add(rotDX2);
  62614. }
  62615. fy += dy;
  62616. }
  62617. return textureArray;
  62618. };
  62619. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  62620. var theta = Math.atan2(vDir.z, vDir.x);
  62621. var phi = Math.acos(vDir.y);
  62622. while (theta < -Math.PI)
  62623. theta += 2 * Math.PI;
  62624. while (theta > Math.PI)
  62625. theta -= 2 * Math.PI;
  62626. var dx = theta / Math.PI;
  62627. var dy = phi / Math.PI;
  62628. // recenter.
  62629. dx = dx * 0.5 + 0.5;
  62630. var px = Math.round(dx * inputWidth);
  62631. if (px < 0)
  62632. px = 0;
  62633. else if (px >= inputWidth)
  62634. px = inputWidth - 1;
  62635. var py = Math.round(dy * inputHeight);
  62636. if (py < 0)
  62637. py = 0;
  62638. else if (py >= inputHeight)
  62639. py = inputHeight - 1;
  62640. var inputY = (inputHeight - py - 1);
  62641. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  62642. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  62643. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  62644. return {
  62645. r: r,
  62646. g: g,
  62647. b: b
  62648. };
  62649. };
  62650. PanoramaToCubeMapTools.FACE_FRONT = [
  62651. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62652. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62653. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62654. new BABYLON.Vector3(1.0, 1.0, -1.0)
  62655. ];
  62656. PanoramaToCubeMapTools.FACE_BACK = [
  62657. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62658. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62659. new BABYLON.Vector3(1.0, 1.0, 1.0),
  62660. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  62661. ];
  62662. PanoramaToCubeMapTools.FACE_RIGHT = [
  62663. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62664. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62665. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62666. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62667. ];
  62668. PanoramaToCubeMapTools.FACE_LEFT = [
  62669. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62670. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62671. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62672. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  62673. ];
  62674. PanoramaToCubeMapTools.FACE_DOWN = [
  62675. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62676. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62677. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62678. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62679. ];
  62680. PanoramaToCubeMapTools.FACE_UP = [
  62681. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62682. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62683. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62684. new BABYLON.Vector3(1.0, -1.0, -1.0)
  62685. ];
  62686. return PanoramaToCubeMapTools;
  62687. }());
  62688. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  62689. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62690. })(BABYLON || (BABYLON = {}));
  62691. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  62692. var BABYLON;
  62693. (function (BABYLON) {
  62694. var Internals;
  62695. (function (Internals) {
  62696. ;
  62697. /**
  62698. * This groups tools to convert HDR texture to native colors array.
  62699. */
  62700. var HDRTools = /** @class */ (function () {
  62701. function HDRTools() {
  62702. }
  62703. HDRTools.Ldexp = function (mantissa, exponent) {
  62704. if (exponent > 1023) {
  62705. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  62706. }
  62707. if (exponent < -1074) {
  62708. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  62709. }
  62710. return mantissa * Math.pow(2, exponent);
  62711. };
  62712. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  62713. if (exponent > 0) {
  62714. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  62715. float32array[index + 0] = red * exponent;
  62716. float32array[index + 1] = green * exponent;
  62717. float32array[index + 2] = blue * exponent;
  62718. }
  62719. else {
  62720. float32array[index + 0] = 0;
  62721. float32array[index + 1] = 0;
  62722. float32array[index + 2] = 0;
  62723. }
  62724. };
  62725. HDRTools.readStringLine = function (uint8array, startIndex) {
  62726. var line = "";
  62727. var character = "";
  62728. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  62729. character = String.fromCharCode(uint8array[i]);
  62730. if (character == "\n") {
  62731. break;
  62732. }
  62733. line += character;
  62734. }
  62735. return line;
  62736. };
  62737. /**
  62738. * Reads header information from an RGBE texture stored in a native array.
  62739. * More information on this format are available here:
  62740. * https://en.wikipedia.org/wiki/RGBE_image_format
  62741. *
  62742. * @param uint8array The binary file stored in native array.
  62743. * @return The header information.
  62744. */
  62745. HDRTools.RGBE_ReadHeader = function (uint8array) {
  62746. var height = 0;
  62747. var width = 0;
  62748. var line = this.readStringLine(uint8array, 0);
  62749. if (line[0] != '#' || line[1] != '?') {
  62750. throw "Bad HDR Format.";
  62751. }
  62752. var endOfHeader = false;
  62753. var findFormat = false;
  62754. var lineIndex = 0;
  62755. do {
  62756. lineIndex += (line.length + 1);
  62757. line = this.readStringLine(uint8array, lineIndex);
  62758. if (line == "FORMAT=32-bit_rle_rgbe") {
  62759. findFormat = true;
  62760. }
  62761. else if (line.length == 0) {
  62762. endOfHeader = true;
  62763. }
  62764. } while (!endOfHeader);
  62765. if (!findFormat) {
  62766. throw "HDR Bad header format, unsupported FORMAT";
  62767. }
  62768. lineIndex += (line.length + 1);
  62769. line = this.readStringLine(uint8array, lineIndex);
  62770. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  62771. var match = sizeRegexp.exec(line);
  62772. // TODO. Support +Y and -X if needed.
  62773. if (!match || match.length < 3) {
  62774. throw "HDR Bad header format, no size";
  62775. }
  62776. width = parseInt(match[2]);
  62777. height = parseInt(match[1]);
  62778. if (width < 8 || width > 0x7fff) {
  62779. throw "HDR Bad header format, unsupported size";
  62780. }
  62781. lineIndex += (line.length + 1);
  62782. return {
  62783. height: height,
  62784. width: width,
  62785. dataPosition: lineIndex
  62786. };
  62787. };
  62788. /**
  62789. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  62790. * This RGBE texture needs to store the information as a panorama.
  62791. *
  62792. * More information on this format are available here:
  62793. * https://en.wikipedia.org/wiki/RGBE_image_format
  62794. *
  62795. * @param buffer The binary file stored in an array buffer.
  62796. * @param size The expected size of the extracted cubemap.
  62797. * @return The Cube Map information.
  62798. */
  62799. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  62800. var uint8array = new Uint8Array(buffer);
  62801. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  62802. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62803. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  62804. return cubeMapData;
  62805. };
  62806. /**
  62807. * Returns the pixels data extracted from an RGBE texture.
  62808. * This pixels will be stored left to right up to down in the R G B order in one array.
  62809. *
  62810. * More information on this format are available here:
  62811. * https://en.wikipedia.org/wiki/RGBE_image_format
  62812. *
  62813. * @param uint8array The binary file stored in an array buffer.
  62814. * @param hdrInfo The header information of the file.
  62815. * @return The pixels data in RGB right to left up to down order.
  62816. */
  62817. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  62818. // Keep for multi format supports.
  62819. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62820. };
  62821. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  62822. var num_scanlines = hdrInfo.height;
  62823. var scanline_width = hdrInfo.width;
  62824. var a, b, c, d, count;
  62825. var dataIndex = hdrInfo.dataPosition;
  62826. var index = 0, endIndex = 0, i = 0;
  62827. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  62828. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  62829. // 3 channels of 4 bytes per pixel in float.
  62830. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  62831. var resultArray = new Float32Array(resultBuffer);
  62832. // read in each successive scanline
  62833. while (num_scanlines > 0) {
  62834. a = uint8array[dataIndex++];
  62835. b = uint8array[dataIndex++];
  62836. c = uint8array[dataIndex++];
  62837. d = uint8array[dataIndex++];
  62838. if (a != 2 || b != 2 || (c & 0x80)) {
  62839. // this file is not run length encoded
  62840. throw "HDR Bad header format, not RLE";
  62841. }
  62842. if (((c << 8) | d) != scanline_width) {
  62843. throw "HDR Bad header format, wrong scan line width";
  62844. }
  62845. index = 0;
  62846. // read each of the four channels for the scanline into the buffer
  62847. for (i = 0; i < 4; i++) {
  62848. endIndex = (i + 1) * scanline_width;
  62849. while (index < endIndex) {
  62850. a = uint8array[dataIndex++];
  62851. b = uint8array[dataIndex++];
  62852. if (a > 128) {
  62853. // a run of the same value
  62854. count = a - 128;
  62855. if ((count == 0) || (count > endIndex - index)) {
  62856. throw "HDR Bad Format, bad scanline data (run)";
  62857. }
  62858. while (count-- > 0) {
  62859. scanLineArray[index++] = b;
  62860. }
  62861. }
  62862. else {
  62863. // a non-run
  62864. count = a;
  62865. if ((count == 0) || (count > endIndex - index)) {
  62866. throw "HDR Bad Format, bad scanline data (non-run)";
  62867. }
  62868. scanLineArray[index++] = b;
  62869. if (--count > 0) {
  62870. for (var j = 0; j < count; j++) {
  62871. scanLineArray[index++] = uint8array[dataIndex++];
  62872. }
  62873. }
  62874. }
  62875. }
  62876. }
  62877. // now convert data from buffer into floats
  62878. for (i = 0; i < scanline_width; i++) {
  62879. a = scanLineArray[i];
  62880. b = scanLineArray[i + scanline_width];
  62881. c = scanLineArray[i + 2 * scanline_width];
  62882. d = scanLineArray[i + 3 * scanline_width];
  62883. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  62884. }
  62885. num_scanlines--;
  62886. }
  62887. return resultArray;
  62888. };
  62889. return HDRTools;
  62890. }());
  62891. Internals.HDRTools = HDRTools;
  62892. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62893. })(BABYLON || (BABYLON = {}));
  62894. //# sourceMappingURL=babylon.hdr.js.map
  62895. var BABYLON;
  62896. (function (BABYLON) {
  62897. /**
  62898. * This represents a texture coming from an HDR input.
  62899. *
  62900. * The only supported format is currently panorama picture stored in RGBE format.
  62901. * Example of such files can be found on HDRLib: http://hdrlib.com/
  62902. */
  62903. var HDRCubeTexture = /** @class */ (function (_super) {
  62904. __extends(HDRCubeTexture, _super);
  62905. /**
  62906. * Instantiates an HDRTexture from the following parameters.
  62907. *
  62908. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  62909. * @param scene The scene the texture will be used in
  62910. * @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.
  62911. * @param noMipmap Forces to not generate the mipmap if true
  62912. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  62913. * @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)
  62914. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  62915. */
  62916. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  62917. if (noMipmap === void 0) { noMipmap = false; }
  62918. if (generateHarmonics === void 0) { generateHarmonics = true; }
  62919. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  62920. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  62921. if (onLoad === void 0) { onLoad = null; }
  62922. if (onError === void 0) { onError = null; }
  62923. var _this = _super.call(this, scene) || this;
  62924. _this._useInGammaSpace = false;
  62925. _this._generateHarmonics = true;
  62926. _this._isBABYLONPreprocessed = false;
  62927. _this._onLoad = null;
  62928. _this._onError = null;
  62929. /**
  62930. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  62931. */
  62932. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62933. /**
  62934. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  62935. * This is usefull at run time to apply the good shader.
  62936. */
  62937. _this.isPMREM = false;
  62938. _this._isBlocking = true;
  62939. if (!url) {
  62940. return _this;
  62941. }
  62942. _this.name = url;
  62943. _this.url = url;
  62944. _this.hasAlpha = false;
  62945. _this.isCube = true;
  62946. _this._textureMatrix = BABYLON.Matrix.Identity();
  62947. _this._onLoad = onLoad;
  62948. _this._onError = onError;
  62949. _this.gammaSpace = false;
  62950. var caps = scene.getEngine().getCaps();
  62951. if (size) {
  62952. _this._isBABYLONPreprocessed = false;
  62953. _this._noMipmap = noMipmap;
  62954. _this._size = size;
  62955. _this._useInGammaSpace = useInGammaSpace;
  62956. _this._usePMREMGenerator = usePMREMGenerator &&
  62957. caps.textureLOD &&
  62958. caps.textureFloat &&
  62959. !_this._useInGammaSpace;
  62960. }
  62961. else {
  62962. _this._isBABYLONPreprocessed = true;
  62963. _this._noMipmap = false;
  62964. _this._useInGammaSpace = false;
  62965. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  62966. !_this._useInGammaSpace;
  62967. }
  62968. _this.isPMREM = _this._usePMREMGenerator;
  62969. _this._texture = _this._getFromCache(url, _this._noMipmap);
  62970. if (!_this._texture) {
  62971. if (!scene.useDelayedTextureLoading) {
  62972. _this.loadTexture();
  62973. }
  62974. else {
  62975. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62976. }
  62977. }
  62978. return _this;
  62979. }
  62980. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  62981. /**
  62982. * Gets wether or not the texture is blocking during loading.
  62983. */
  62984. get: function () {
  62985. return this._isBlocking;
  62986. },
  62987. /**
  62988. * Sets wether or not the texture is blocking during loading.
  62989. */
  62990. set: function (value) {
  62991. this._isBlocking = value;
  62992. },
  62993. enumerable: true,
  62994. configurable: true
  62995. });
  62996. /**
  62997. * Occurs when the file is a preprocessed .babylon.hdr file.
  62998. */
  62999. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  63000. var _this = this;
  63001. var mipLevels = 0;
  63002. var floatArrayView = null;
  63003. var scene = this.getScene();
  63004. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  63005. var mips = new Array();
  63006. if (!floatArrayView) {
  63007. return mips;
  63008. }
  63009. var startIndex = 30;
  63010. for (var level = 0; level < mipLevels; level++) {
  63011. mips.push([]);
  63012. // Fill each pixel of the mip level.
  63013. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  63014. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63015. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  63016. mips[level].push(faceData);
  63017. startIndex += faceSize;
  63018. }
  63019. }
  63020. return mips;
  63021. } : null;
  63022. var callback = function (buffer) {
  63023. var scene = _this.getScene();
  63024. if (!scene) {
  63025. return null;
  63026. }
  63027. // Create Native Array Views
  63028. var intArrayView = new Int32Array(buffer);
  63029. floatArrayView = new Float32Array(buffer);
  63030. // Fill header.
  63031. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  63032. _this._size = intArrayView[1]; // CubeMap max mip face size.
  63033. // Update Texture Information.
  63034. if (!_this._texture) {
  63035. return null;
  63036. }
  63037. _this._texture.updateSize(_this._size, _this._size);
  63038. // Fill polynomial information.
  63039. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  63040. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  63041. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  63042. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  63043. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  63044. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  63045. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  63046. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  63047. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  63048. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  63049. _this.sphericalPolynomial = sphericalPolynomial;
  63050. // Fill pixel data.
  63051. mipLevels = intArrayView[29]; // Number of mip levels.
  63052. var startIndex = 30;
  63053. var data = [];
  63054. var faceSize = Math.pow(_this._size, 2) * 3;
  63055. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63056. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  63057. startIndex += faceSize;
  63058. }
  63059. var results = [];
  63060. var byteArray = null;
  63061. // Push each faces.
  63062. for (var k = 0; k < 6; k++) {
  63063. var dataFace = null;
  63064. // To be deprecated.
  63065. if (version === 1) {
  63066. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  63067. dataFace = data[j];
  63068. }
  63069. // If special cases.
  63070. if (!mipmapGenerator && dataFace) {
  63071. if (!scene.getEngine().getCaps().textureFloat) {
  63072. // 3 channels of 1 bytes per pixel in bytes.
  63073. var byteBuffer = new ArrayBuffer(faceSize);
  63074. byteArray = new Uint8Array(byteBuffer);
  63075. }
  63076. for (var i = 0; i < _this._size * _this._size; i++) {
  63077. // Put in gamma space if requested.
  63078. if (_this._useInGammaSpace) {
  63079. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63080. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63081. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63082. }
  63083. // Convert to int texture for fallback.
  63084. if (byteArray) {
  63085. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63086. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63087. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63088. // May use luminance instead if the result is not accurate.
  63089. var max = Math.max(Math.max(r, g), b);
  63090. if (max > 255) {
  63091. var scale = 255 / max;
  63092. r *= scale;
  63093. g *= scale;
  63094. b *= scale;
  63095. }
  63096. byteArray[(i * 3) + 0] = r;
  63097. byteArray[(i * 3) + 1] = g;
  63098. byteArray[(i * 3) + 2] = b;
  63099. }
  63100. }
  63101. }
  63102. // Fill the array accordingly.
  63103. if (byteArray) {
  63104. results.push(byteArray);
  63105. }
  63106. else {
  63107. results.push(dataFace);
  63108. }
  63109. }
  63110. return results;
  63111. };
  63112. if (scene) {
  63113. 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);
  63114. }
  63115. };
  63116. /**
  63117. * Occurs when the file is raw .hdr file.
  63118. */
  63119. HDRCubeTexture.prototype.loadHDRTexture = function () {
  63120. var _this = this;
  63121. var callback = function (buffer) {
  63122. var scene = _this.getScene();
  63123. if (!scene) {
  63124. return null;
  63125. }
  63126. // Extract the raw linear data.
  63127. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  63128. // Generate harmonics if needed.
  63129. if (_this._generateHarmonics) {
  63130. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  63131. _this.sphericalPolynomial = sphericalPolynomial;
  63132. }
  63133. var results = [];
  63134. var byteArray = null;
  63135. // Push each faces.
  63136. for (var j = 0; j < 6; j++) {
  63137. // Create uintarray fallback.
  63138. if (!scene.getEngine().getCaps().textureFloat) {
  63139. // 3 channels of 1 bytes per pixel in bytes.
  63140. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  63141. byteArray = new Uint8Array(byteBuffer);
  63142. }
  63143. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  63144. // If special cases.
  63145. if (_this._useInGammaSpace || byteArray) {
  63146. for (var i = 0; i < _this._size * _this._size; i++) {
  63147. // Put in gamma space if requested.
  63148. if (_this._useInGammaSpace) {
  63149. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63150. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63151. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63152. }
  63153. // Convert to int texture for fallback.
  63154. if (byteArray) {
  63155. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63156. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63157. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63158. // May use luminance instead if the result is not accurate.
  63159. var max = Math.max(Math.max(r, g), b);
  63160. if (max > 255) {
  63161. var scale = 255 / max;
  63162. r *= scale;
  63163. g *= scale;
  63164. b *= scale;
  63165. }
  63166. byteArray[(i * 3) + 0] = r;
  63167. byteArray[(i * 3) + 1] = g;
  63168. byteArray[(i * 3) + 2] = b;
  63169. }
  63170. }
  63171. }
  63172. if (byteArray) {
  63173. results.push(byteArray);
  63174. }
  63175. else {
  63176. results.push(dataFace);
  63177. }
  63178. }
  63179. return results;
  63180. };
  63181. var mipmapGenerator = null;
  63182. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63183. // if (!this._noMipmap &&
  63184. // this._usePMREMGenerator) {
  63185. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63186. // // Custom setup of the generator matching with the PBR shader values.
  63187. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63188. // this._size,
  63189. // this._size,
  63190. // 0,
  63191. // 3,
  63192. // this.getScene().getEngine().getCaps().textureFloat,
  63193. // 2048,
  63194. // 0.25,
  63195. // false,
  63196. // true);
  63197. // return generator.filterCubeMap();
  63198. // };
  63199. // }
  63200. var scene = this.getScene();
  63201. if (scene) {
  63202. 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);
  63203. }
  63204. };
  63205. /**
  63206. * Starts the loading process of the texture.
  63207. */
  63208. HDRCubeTexture.prototype.loadTexture = function () {
  63209. if (this._isBABYLONPreprocessed) {
  63210. this.loadBabylonTexture();
  63211. }
  63212. else {
  63213. this.loadHDRTexture();
  63214. }
  63215. };
  63216. HDRCubeTexture.prototype.clone = function () {
  63217. var scene = this.getScene();
  63218. if (!scene) {
  63219. return this;
  63220. }
  63221. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63222. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63223. // Base texture
  63224. newTexture.level = this.level;
  63225. newTexture.wrapU = this.wrapU;
  63226. newTexture.wrapV = this.wrapV;
  63227. newTexture.coordinatesIndex = this.coordinatesIndex;
  63228. newTexture.coordinatesMode = this.coordinatesMode;
  63229. return newTexture;
  63230. };
  63231. // Methods
  63232. HDRCubeTexture.prototype.delayLoad = function () {
  63233. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63234. return;
  63235. }
  63236. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63237. this._texture = this._getFromCache(this.url, this._noMipmap);
  63238. if (!this._texture) {
  63239. this.loadTexture();
  63240. }
  63241. };
  63242. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  63243. return this._textureMatrix;
  63244. };
  63245. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63246. this._textureMatrix = value;
  63247. };
  63248. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63249. var texture = null;
  63250. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63251. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  63252. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  63253. texture.name = parsedTexture.name;
  63254. texture.hasAlpha = parsedTexture.hasAlpha;
  63255. texture.level = parsedTexture.level;
  63256. texture.coordinatesMode = parsedTexture.coordinatesMode;
  63257. texture.isBlocking = parsedTexture.isBlocking;
  63258. }
  63259. return texture;
  63260. };
  63261. HDRCubeTexture.prototype.serialize = function () {
  63262. if (!this.name) {
  63263. return null;
  63264. }
  63265. var serializationObject = {};
  63266. serializationObject.name = this.name;
  63267. serializationObject.hasAlpha = this.hasAlpha;
  63268. serializationObject.isCube = true;
  63269. serializationObject.level = this.level;
  63270. serializationObject.size = this._size;
  63271. serializationObject.coordinatesMode = this.coordinatesMode;
  63272. serializationObject.useInGammaSpace = this._useInGammaSpace;
  63273. serializationObject.generateHarmonics = this._generateHarmonics;
  63274. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  63275. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  63276. serializationObject.customType = "BABYLON.HDRCubeTexture";
  63277. serializationObject.noMipmap = this._noMipmap;
  63278. serializationObject.isBlocking = this._isBlocking;
  63279. return serializationObject;
  63280. };
  63281. /**
  63282. * Saves as a file the data contained in the texture in a binary format.
  63283. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63284. * as the spherical used in the lighting.
  63285. * @param url The HDR file url.
  63286. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63287. * @param onError Method called if any error happens during download.
  63288. * @return The packed binary data.
  63289. */
  63290. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  63291. if (onError === void 0) { onError = null; }
  63292. var callback = function (buffer) {
  63293. var data = new Blob([buffer], { type: 'application/octet-stream' });
  63294. // Returns a URL you can use as a href.
  63295. var objUrl = window.URL.createObjectURL(data);
  63296. // Simulates a link to it and click to dowload.
  63297. var a = document.createElement("a");
  63298. document.body.appendChild(a);
  63299. a.style.display = "none";
  63300. a.href = objUrl;
  63301. a.download = "envmap.babylon.hdr";
  63302. a.click();
  63303. };
  63304. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  63305. };
  63306. /**
  63307. * Serializes the data contained in the texture in a binary format.
  63308. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63309. * as the spherical used in the lighting.
  63310. * @param url The HDR file url.
  63311. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63312. * @param onError Method called if any error happens during download.
  63313. * @return The packed binary data.
  63314. */
  63315. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  63316. if (onError === void 0) { onError = null; }
  63317. // Needs the url tho create the texture.
  63318. if (!url) {
  63319. return;
  63320. }
  63321. // Check Power of two size.
  63322. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  63323. return;
  63324. }
  63325. // Coming Back in 3.x.
  63326. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  63327. };
  63328. HDRCubeTexture._facesMapping = [
  63329. "right",
  63330. "left",
  63331. "up",
  63332. "down",
  63333. "front",
  63334. "back"
  63335. ];
  63336. return HDRCubeTexture;
  63337. }(BABYLON.BaseTexture));
  63338. BABYLON.HDRCubeTexture = HDRCubeTexture;
  63339. })(BABYLON || (BABYLON = {}));
  63340. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  63341. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  63342. // Huge respect for a such great lib.
  63343. // Earcut license:
  63344. // Copyright (c) 2016, Mapbox
  63345. //
  63346. // Permission to use, copy, modify, and/or distribute this software for any purpose
  63347. // with or without fee is hereby granted, provided that the above copyright notice
  63348. // and this permission notice appear in all copies.
  63349. //
  63350. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  63351. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  63352. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  63353. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  63354. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  63355. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  63356. // THIS SOFTWARE.
  63357. var Earcut;
  63358. (function (Earcut) {
  63359. /**
  63360. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  63361. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  63362. * @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).
  63363. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  63364. */
  63365. function earcut(data, holeIndices, dim) {
  63366. dim = dim || 2;
  63367. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  63368. if (!outerNode)
  63369. return triangles;
  63370. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  63371. if (hasHoles)
  63372. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  63373. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  63374. if (data.length > 80 * dim) {
  63375. minX = maxX = data[0];
  63376. minY = maxY = data[1];
  63377. for (var i = dim; i < outerLen; i += dim) {
  63378. x = data[i];
  63379. y = data[i + 1];
  63380. if (x < minX)
  63381. minX = x;
  63382. if (y < minY)
  63383. minY = y;
  63384. if (x > maxX)
  63385. maxX = x;
  63386. if (y > maxY)
  63387. maxY = y;
  63388. }
  63389. // minX, minY and size are later used to transform coords into integers for z-order calculation
  63390. size = Math.max(maxX - minX, maxY - minY);
  63391. }
  63392. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  63393. return triangles;
  63394. }
  63395. Earcut.earcut = earcut;
  63396. var Node = /** @class */ (function () {
  63397. function Node(i, x, y) {
  63398. this.i = i;
  63399. this.x = x;
  63400. this.y = y;
  63401. this.prev = null;
  63402. this.next = null;
  63403. this.z = null;
  63404. this.prevZ = null;
  63405. this.nextZ = null;
  63406. this.steiner = false;
  63407. }
  63408. return Node;
  63409. }());
  63410. // create a circular doubly linked list from polygon points in the specified winding order
  63411. function linkedList(data, start, end, dim, clockwise) {
  63412. var i, last = null;
  63413. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  63414. for (i = start; i < end; i += dim)
  63415. last = insertNode(i, data[i], data[i + 1], last);
  63416. }
  63417. else {
  63418. for (i = end - dim; i >= start; i -= dim)
  63419. last = insertNode(i, data[i], data[i + 1], last);
  63420. }
  63421. if (last && equals(last, last.next)) {
  63422. removeNode(last);
  63423. last = last.next;
  63424. }
  63425. return last;
  63426. }
  63427. // eliminate colinear or duplicate points
  63428. function filterPoints(start, end) {
  63429. if (!start)
  63430. return start;
  63431. if (!end)
  63432. end = start;
  63433. var p = start, again;
  63434. do {
  63435. again = false;
  63436. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  63437. removeNode(p);
  63438. p = end = p.prev;
  63439. if (p === p.next)
  63440. return undefined;
  63441. again = true;
  63442. }
  63443. else {
  63444. p = p.next;
  63445. }
  63446. } while (again || p !== end);
  63447. return end;
  63448. }
  63449. // main ear slicing loop which triangulates a polygon (given as a linked list)
  63450. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63451. if (!ear)
  63452. return;
  63453. // interlink polygon nodes in z-order
  63454. if (!pass && size)
  63455. indexCurve(ear, minX, minY, size);
  63456. var stop = ear, prev, next;
  63457. // iterate through ears, slicing them one by one
  63458. while (ear.prev !== ear.next) {
  63459. prev = ear.prev;
  63460. next = ear.next;
  63461. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  63462. // cut off the triangle
  63463. triangles.push(prev.i / dim);
  63464. triangles.push(ear.i / dim);
  63465. triangles.push(next.i / dim);
  63466. removeNode(ear);
  63467. // skipping the next vertice leads to less sliver triangles
  63468. ear = next.next;
  63469. stop = next.next;
  63470. continue;
  63471. }
  63472. ear = next;
  63473. // if we looped through the whole remaining polygon and can't find any more ears
  63474. if (ear === stop) {
  63475. // try filtering points and slicing again
  63476. if (!pass) {
  63477. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  63478. // if this didn't work, try curing all small self-intersections locally
  63479. }
  63480. else if (pass === 1) {
  63481. ear = cureLocalIntersections(ear, triangles, dim);
  63482. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  63483. // as a last resort, try splitting the remaining polygon into two
  63484. }
  63485. else if (pass === 2) {
  63486. splitEarcut(ear, triangles, dim, minX, minY, size);
  63487. }
  63488. break;
  63489. }
  63490. }
  63491. }
  63492. // check whether a polygon node forms a valid ear with adjacent nodes
  63493. function isEar(ear) {
  63494. var a = ear.prev, b = ear, c = ear.next;
  63495. if (area(a, b, c) >= 0)
  63496. return false; // reflex, can't be an ear
  63497. // now make sure we don't have other points inside the potential ear
  63498. var p = ear.next.next;
  63499. while (p !== ear.prev) {
  63500. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63501. area(p.prev, p, p.next) >= 0)
  63502. return false;
  63503. p = p.next;
  63504. }
  63505. return true;
  63506. }
  63507. function isEarHashed(ear, minX, minY, size) {
  63508. var a = ear.prev, b = ear, c = ear.next;
  63509. if (area(a, b, c) >= 0)
  63510. return false; // reflex, can't be an ear
  63511. // triangle bbox; min & max are calculated like this for speed
  63512. 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);
  63513. // z-order range for the current triangle bbox;
  63514. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  63515. // first look for points inside the triangle in increasing z-order
  63516. var p = ear.nextZ;
  63517. while (p && p.z <= maxZ) {
  63518. if (p !== ear.prev &&
  63519. p !== ear.next &&
  63520. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63521. area(p.prev, p, p.next) >= 0)
  63522. return false;
  63523. p = p.nextZ;
  63524. }
  63525. // then look for points in decreasing z-order
  63526. p = ear.prevZ;
  63527. while (p && p.z >= minZ) {
  63528. if (p !== ear.prev &&
  63529. p !== ear.next &&
  63530. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63531. area(p.prev, p, p.next) >= 0)
  63532. return false;
  63533. p = p.prevZ;
  63534. }
  63535. return true;
  63536. }
  63537. // go through all polygon nodes and cure small local self-intersections
  63538. function cureLocalIntersections(start, triangles, dim) {
  63539. var p = start;
  63540. do {
  63541. var a = p.prev, b = p.next.next;
  63542. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  63543. triangles.push(a.i / dim);
  63544. triangles.push(p.i / dim);
  63545. triangles.push(b.i / dim);
  63546. // remove two nodes involved
  63547. removeNode(p);
  63548. removeNode(p.next);
  63549. p = start = b;
  63550. }
  63551. p = p.next;
  63552. } while (p !== start);
  63553. return p;
  63554. }
  63555. // try splitting polygon into two and triangulate them independently
  63556. function splitEarcut(start, triangles, dim, minX, minY, size) {
  63557. // look for a valid diagonal that divides the polygon into two
  63558. var a = start;
  63559. do {
  63560. var b = a.next.next;
  63561. while (b !== a.prev) {
  63562. if (a.i !== b.i && isValidDiagonal(a, b)) {
  63563. // split the polygon in two by the diagonal
  63564. var c = splitPolygon(a, b);
  63565. // filter colinear points around the cuts
  63566. a = filterPoints(a, a.next);
  63567. c = filterPoints(c, c.next);
  63568. // run earcut on each half
  63569. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  63570. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  63571. return;
  63572. }
  63573. b = b.next;
  63574. }
  63575. a = a.next;
  63576. } while (a !== start);
  63577. }
  63578. // link every hole into the outer loop, producing a single-ring polygon without holes
  63579. function eliminateHoles(data, holeIndices, outerNode, dim) {
  63580. var queue = [], i, len, start, end, list;
  63581. for (i = 0, len = holeIndices.length; i < len; i++) {
  63582. start = holeIndices[i] * dim;
  63583. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63584. list = linkedList(data, start, end, dim, false);
  63585. if (list === list.next)
  63586. list.steiner = true;
  63587. queue.push(getLeftmost(list));
  63588. }
  63589. queue.sort(compareX);
  63590. // process holes from left to right
  63591. for (i = 0; i < queue.length; i++) {
  63592. eliminateHole(queue[i], outerNode);
  63593. outerNode = filterPoints(outerNode, outerNode.next);
  63594. }
  63595. return outerNode;
  63596. }
  63597. function compareX(a, b) {
  63598. return a.x - b.x;
  63599. }
  63600. // find a bridge between vertices that connects hole with an outer ring and and link it
  63601. function eliminateHole(hole, outerNode) {
  63602. outerNode = findHoleBridge(hole, outerNode);
  63603. if (outerNode) {
  63604. var b = splitPolygon(outerNode, hole);
  63605. filterPoints(b, b.next);
  63606. }
  63607. }
  63608. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  63609. function findHoleBridge(hole, outerNode) {
  63610. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  63611. // find a segment intersected by a ray from the hole's leftmost point to the left;
  63612. // segment's endpoint with lesser x will be potential connection point
  63613. do {
  63614. if (hy <= p.y && hy >= p.next.y) {
  63615. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  63616. if (x <= hx && x > qx) {
  63617. qx = x;
  63618. if (x === hx) {
  63619. if (hy === p.y)
  63620. return p;
  63621. if (hy === p.next.y)
  63622. return p.next;
  63623. }
  63624. m = p.x < p.next.x ? p : p.next;
  63625. }
  63626. }
  63627. p = p.next;
  63628. } while (p !== outerNode);
  63629. if (!m)
  63630. return null;
  63631. if (hx === qx)
  63632. return m.prev; // hole touches outer segment; pick lower endpoint
  63633. // look for points inside the triangle of hole point, segment intersection and endpoint;
  63634. // if there are no points found, we have a valid connection;
  63635. // otherwise choose the point of the minimum angle with the ray as connection point
  63636. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  63637. p = m.next;
  63638. while (p !== stop) {
  63639. if (hx >= p.x &&
  63640. p.x >= mx &&
  63641. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  63642. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  63643. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  63644. m = p;
  63645. tanMin = tan;
  63646. }
  63647. }
  63648. p = p.next;
  63649. }
  63650. return m;
  63651. }
  63652. // interlink polygon nodes in z-order
  63653. function indexCurve(start, minX, minY, size) {
  63654. var p = start;
  63655. do {
  63656. if (p.z === null)
  63657. p.z = zOrder(p.x, p.y, minX, minY, size);
  63658. p.prevZ = p.prev;
  63659. p.nextZ = p.next;
  63660. p = p.next;
  63661. } while (p !== start);
  63662. p.prevZ.nextZ = null;
  63663. p.prevZ = null;
  63664. sortLinked(p);
  63665. }
  63666. // Simon Tatham's linked list merge sort algorithm
  63667. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  63668. function sortLinked(list) {
  63669. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  63670. do {
  63671. p = list;
  63672. list = null;
  63673. tail = null;
  63674. numMerges = 0;
  63675. while (p) {
  63676. numMerges++;
  63677. q = p;
  63678. pSize = 0;
  63679. for (i = 0; i < inSize; i++) {
  63680. pSize++;
  63681. q = q.nextZ;
  63682. if (!q)
  63683. break;
  63684. }
  63685. qSize = inSize;
  63686. while (pSize > 0 || (qSize > 0 && q)) {
  63687. if (pSize === 0) {
  63688. e = q;
  63689. q = q.nextZ;
  63690. qSize--;
  63691. }
  63692. else if (qSize === 0 || !q) {
  63693. e = p;
  63694. p = p.nextZ;
  63695. pSize--;
  63696. }
  63697. else if (p.z <= q.z) {
  63698. e = p;
  63699. p = p.nextZ;
  63700. pSize--;
  63701. }
  63702. else {
  63703. e = q;
  63704. q = q.nextZ;
  63705. qSize--;
  63706. }
  63707. if (tail)
  63708. tail.nextZ = e;
  63709. else
  63710. list = e;
  63711. e.prevZ = tail;
  63712. tail = e;
  63713. }
  63714. p = q;
  63715. }
  63716. tail.nextZ = null;
  63717. inSize *= 2;
  63718. } while (numMerges > 1);
  63719. return list;
  63720. }
  63721. // z-order of a point given coords and size of the data bounding box
  63722. function zOrder(x, y, minX, minY, size) {
  63723. // coords are transformed into non-negative 15-bit integer range
  63724. x = 32767 * (x - minX) / size;
  63725. y = 32767 * (y - minY) / size;
  63726. x = (x | (x << 8)) & 0x00FF00FF;
  63727. x = (x | (x << 4)) & 0x0F0F0F0F;
  63728. x = (x | (x << 2)) & 0x33333333;
  63729. x = (x | (x << 1)) & 0x55555555;
  63730. y = (y | (y << 8)) & 0x00FF00FF;
  63731. y = (y | (y << 4)) & 0x0F0F0F0F;
  63732. y = (y | (y << 2)) & 0x33333333;
  63733. y = (y | (y << 1)) & 0x55555555;
  63734. return x | (y << 1);
  63735. }
  63736. // find the leftmost node of a polygon ring
  63737. function getLeftmost(start) {
  63738. var p = start, leftmost = start;
  63739. do {
  63740. if (p.x < leftmost.x)
  63741. leftmost = p;
  63742. p = p.next;
  63743. } while (p !== start);
  63744. return leftmost;
  63745. }
  63746. // check if a point lies within a convex triangle
  63747. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  63748. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  63749. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  63750. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  63751. }
  63752. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  63753. function isValidDiagonal(a, b) {
  63754. return a.next.i !== b.i &&
  63755. a.prev.i !== b.i &&
  63756. !intersectsPolygon(a, b) &&
  63757. locallyInside(a, b) &&
  63758. locallyInside(b, a) &&
  63759. middleInside(a, b);
  63760. }
  63761. // signed area of a triangle
  63762. function area(p, q, r) {
  63763. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  63764. }
  63765. // check if two points are equal
  63766. function equals(p1, p2) {
  63767. return p1.x === p2.x && p1.y === p2.y;
  63768. }
  63769. // check if two segments intersect
  63770. function intersects(p1, q1, p2, q2) {
  63771. if ((equals(p1, q1) && equals(p2, q2)) ||
  63772. (equals(p1, q2) && equals(p2, q1)))
  63773. return true;
  63774. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  63775. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  63776. }
  63777. // check if a polygon diagonal intersects any polygon segments
  63778. function intersectsPolygon(a, b) {
  63779. var p = a;
  63780. do {
  63781. if (p.i !== a.i &&
  63782. p.next.i !== a.i &&
  63783. p.i !== b.i &&
  63784. p.next.i !== b.i &&
  63785. intersects(p, p.next, a, b))
  63786. return true;
  63787. p = p.next;
  63788. } while (p !== a);
  63789. return false;
  63790. }
  63791. // check if a polygon diagonal is locally inside the polygon
  63792. function locallyInside(a, b) {
  63793. return area(a.prev, a, a.next) < 0
  63794. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  63795. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  63796. }
  63797. // check if the middle point of a polygon diagonal is inside the polygon
  63798. function middleInside(a, b) {
  63799. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  63800. do {
  63801. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  63802. inside = !inside;
  63803. p = p.next;
  63804. } while (p !== a);
  63805. return inside;
  63806. }
  63807. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  63808. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  63809. function splitPolygon(a, b) {
  63810. 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;
  63811. a.next = b;
  63812. b.prev = a;
  63813. a2.next = an;
  63814. an.prev = a2;
  63815. b2.next = a2;
  63816. a2.prev = b2;
  63817. bp.next = b2;
  63818. b2.prev = bp;
  63819. return b2;
  63820. }
  63821. // create a node and optionally link it with previous one (in a circular doubly linked list)
  63822. function insertNode(i, x, y, last) {
  63823. var p = new Node(i, x, y);
  63824. if (!last) {
  63825. p.prev = p;
  63826. p.next = p;
  63827. }
  63828. else {
  63829. p.next = last.next;
  63830. p.prev = last;
  63831. last.next.prev = p;
  63832. last.next = p;
  63833. }
  63834. return p;
  63835. }
  63836. function removeNode(p) {
  63837. p.next.prev = p.prev;
  63838. p.prev.next = p.next;
  63839. if (p.prevZ)
  63840. p.prevZ.nextZ = p.nextZ;
  63841. if (p.nextZ)
  63842. p.nextZ.prevZ = p.prevZ;
  63843. }
  63844. /**
  63845. * return a percentage difference between the polygon area and its triangulation area;
  63846. * used to verify correctness of triangulation
  63847. */
  63848. function deviation(data, holeIndices, dim, triangles) {
  63849. var hasHoles = holeIndices && holeIndices.length;
  63850. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  63851. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  63852. if (hasHoles) {
  63853. for (var i = 0, len = holeIndices.length; i < len; i++) {
  63854. var start = holeIndices[i] * dim;
  63855. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63856. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  63857. }
  63858. }
  63859. var trianglesArea = 0;
  63860. for (i = 0; i < triangles.length; i += 3) {
  63861. var a = triangles[i] * dim;
  63862. var b = triangles[i + 1] * dim;
  63863. var c = triangles[i + 2] * dim;
  63864. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  63865. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  63866. }
  63867. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  63868. }
  63869. Earcut.deviation = deviation;
  63870. ;
  63871. function signedArea(data, start, end, dim) {
  63872. var sum = 0;
  63873. for (var i = start, j = end - dim; i < end; i += dim) {
  63874. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  63875. j = i;
  63876. }
  63877. return sum;
  63878. }
  63879. /**
  63880. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  63881. */
  63882. function flatten(data) {
  63883. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  63884. for (var i = 0; i < data.length; i++) {
  63885. for (var j = 0; j < data[i].length; j++) {
  63886. for (var d = 0; d < dim; d++)
  63887. result.vertices.push(data[i][j][d]);
  63888. }
  63889. if (i > 0) {
  63890. holeIndex += data[i - 1].length;
  63891. result.holes.push(holeIndex);
  63892. }
  63893. }
  63894. return result;
  63895. }
  63896. Earcut.flatten = flatten;
  63897. ;
  63898. })(Earcut || (Earcut = {}));
  63899. //# sourceMappingURL=babylon.earcut.js.map
  63900. var BABYLON;
  63901. (function (BABYLON) {
  63902. var IndexedVector2 = /** @class */ (function (_super) {
  63903. __extends(IndexedVector2, _super);
  63904. function IndexedVector2(original, index) {
  63905. var _this = _super.call(this, original.x, original.y) || this;
  63906. _this.index = index;
  63907. return _this;
  63908. }
  63909. return IndexedVector2;
  63910. }(BABYLON.Vector2));
  63911. var PolygonPoints = /** @class */ (function () {
  63912. function PolygonPoints() {
  63913. this.elements = new Array();
  63914. }
  63915. PolygonPoints.prototype.add = function (originalPoints) {
  63916. var _this = this;
  63917. var result = new Array();
  63918. originalPoints.forEach(function (point) {
  63919. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  63920. var newPoint = new IndexedVector2(point, _this.elements.length);
  63921. result.push(newPoint);
  63922. _this.elements.push(newPoint);
  63923. }
  63924. });
  63925. return result;
  63926. };
  63927. PolygonPoints.prototype.computeBounds = function () {
  63928. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63929. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63930. this.elements.forEach(function (point) {
  63931. // x
  63932. if (point.x < lmin.x) {
  63933. lmin.x = point.x;
  63934. }
  63935. else if (point.x > lmax.x) {
  63936. lmax.x = point.x;
  63937. }
  63938. // y
  63939. if (point.y < lmin.y) {
  63940. lmin.y = point.y;
  63941. }
  63942. else if (point.y > lmax.y) {
  63943. lmax.y = point.y;
  63944. }
  63945. });
  63946. return {
  63947. min: lmin,
  63948. max: lmax,
  63949. width: lmax.x - lmin.x,
  63950. height: lmax.y - lmin.y
  63951. };
  63952. };
  63953. return PolygonPoints;
  63954. }());
  63955. var Polygon = /** @class */ (function () {
  63956. function Polygon() {
  63957. }
  63958. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  63959. return [
  63960. new BABYLON.Vector2(xmin, ymin),
  63961. new BABYLON.Vector2(xmax, ymin),
  63962. new BABYLON.Vector2(xmax, ymax),
  63963. new BABYLON.Vector2(xmin, ymax)
  63964. ];
  63965. };
  63966. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  63967. if (cx === void 0) { cx = 0; }
  63968. if (cy === void 0) { cy = 0; }
  63969. if (numberOfSides === void 0) { numberOfSides = 32; }
  63970. var result = new Array();
  63971. var angle = 0;
  63972. var increment = (Math.PI * 2) / numberOfSides;
  63973. for (var i = 0; i < numberOfSides; i++) {
  63974. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  63975. angle -= increment;
  63976. }
  63977. return result;
  63978. };
  63979. Polygon.Parse = function (input) {
  63980. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  63981. var i, result = [];
  63982. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  63983. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  63984. }
  63985. return result;
  63986. };
  63987. Polygon.StartingAt = function (x, y) {
  63988. return BABYLON.Path2.StartingAt(x, y);
  63989. };
  63990. return Polygon;
  63991. }());
  63992. BABYLON.Polygon = Polygon;
  63993. var PolygonMeshBuilder = /** @class */ (function () {
  63994. function PolygonMeshBuilder(name, contours, scene) {
  63995. this._points = new PolygonPoints();
  63996. this._outlinepoints = new PolygonPoints();
  63997. this._holes = new Array();
  63998. this._epoints = new Array();
  63999. this._eholes = new Array();
  64000. this._name = name;
  64001. this._scene = scene;
  64002. var points;
  64003. if (contours instanceof BABYLON.Path2) {
  64004. points = contours.getPoints();
  64005. }
  64006. else {
  64007. points = contours;
  64008. }
  64009. this._addToepoint(points);
  64010. this._points.add(points);
  64011. this._outlinepoints.add(points);
  64012. }
  64013. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  64014. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  64015. var p = points_1[_i];
  64016. this._epoints.push(p.x, p.y);
  64017. }
  64018. };
  64019. PolygonMeshBuilder.prototype.addHole = function (hole) {
  64020. this._points.add(hole);
  64021. var holepoints = new PolygonPoints();
  64022. holepoints.add(hole);
  64023. this._holes.push(holepoints);
  64024. this._eholes.push(this._epoints.length / 2);
  64025. this._addToepoint(hole);
  64026. return this;
  64027. };
  64028. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  64029. var _this = this;
  64030. if (updatable === void 0) { updatable = false; }
  64031. if (depth === void 0) { depth = 0; }
  64032. var result = new BABYLON.Mesh(this._name, this._scene);
  64033. var normals = new Array();
  64034. var positions = new Array();
  64035. var uvs = new Array();
  64036. var bounds = this._points.computeBounds();
  64037. this._points.elements.forEach(function (p) {
  64038. normals.push(0, 1.0, 0);
  64039. positions.push(p.x, 0, p.y);
  64040. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  64041. });
  64042. var indices = new Array();
  64043. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  64044. for (var i = 0; i < res.length; i++) {
  64045. indices.push(res[i]);
  64046. }
  64047. if (depth > 0) {
  64048. var positionscount = (positions.length / 3); //get the current pointcount
  64049. this._points.elements.forEach(function (p) {
  64050. normals.push(0, -1.0, 0);
  64051. positions.push(p.x, -depth, p.y);
  64052. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  64053. });
  64054. var totalCount = indices.length;
  64055. for (var i = 0; i < totalCount; i += 3) {
  64056. var i0 = indices[i + 0];
  64057. var i1 = indices[i + 1];
  64058. var i2 = indices[i + 2];
  64059. indices.push(i2 + positionscount);
  64060. indices.push(i1 + positionscount);
  64061. indices.push(i0 + positionscount);
  64062. }
  64063. //Add the sides
  64064. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  64065. this._holes.forEach(function (hole) {
  64066. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  64067. });
  64068. }
  64069. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  64070. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  64071. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  64072. result.setIndices(indices);
  64073. return result;
  64074. };
  64075. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  64076. var StartIndex = positions.length / 3;
  64077. var ulength = 0;
  64078. for (var i = 0; i < points.elements.length; i++) {
  64079. var p = points.elements[i];
  64080. var p1;
  64081. if ((i + 1) > points.elements.length - 1) {
  64082. p1 = points.elements[0];
  64083. }
  64084. else {
  64085. p1 = points.elements[i + 1];
  64086. }
  64087. positions.push(p.x, 0, p.y);
  64088. positions.push(p.x, -depth, p.y);
  64089. positions.push(p1.x, 0, p1.y);
  64090. positions.push(p1.x, -depth, p1.y);
  64091. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  64092. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  64093. var v3 = v2.subtract(v1);
  64094. var v4 = new BABYLON.Vector3(0, 1, 0);
  64095. var vn = BABYLON.Vector3.Cross(v3, v4);
  64096. vn = vn.normalize();
  64097. uvs.push(ulength / bounds.width, 0);
  64098. uvs.push(ulength / bounds.width, 1);
  64099. ulength += v3.length();
  64100. uvs.push((ulength / bounds.width), 0);
  64101. uvs.push((ulength / bounds.width), 1);
  64102. if (!flip) {
  64103. normals.push(-vn.x, -vn.y, -vn.z);
  64104. normals.push(-vn.x, -vn.y, -vn.z);
  64105. normals.push(-vn.x, -vn.y, -vn.z);
  64106. normals.push(-vn.x, -vn.y, -vn.z);
  64107. indices.push(StartIndex);
  64108. indices.push(StartIndex + 1);
  64109. indices.push(StartIndex + 2);
  64110. indices.push(StartIndex + 1);
  64111. indices.push(StartIndex + 3);
  64112. indices.push(StartIndex + 2);
  64113. }
  64114. else {
  64115. normals.push(vn.x, vn.y, vn.z);
  64116. normals.push(vn.x, vn.y, vn.z);
  64117. normals.push(vn.x, vn.y, vn.z);
  64118. normals.push(vn.x, vn.y, vn.z);
  64119. indices.push(StartIndex);
  64120. indices.push(StartIndex + 2);
  64121. indices.push(StartIndex + 1);
  64122. indices.push(StartIndex + 1);
  64123. indices.push(StartIndex + 2);
  64124. indices.push(StartIndex + 3);
  64125. }
  64126. StartIndex += 4;
  64127. }
  64128. ;
  64129. };
  64130. return PolygonMeshBuilder;
  64131. }());
  64132. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  64133. })(BABYLON || (BABYLON = {}));
  64134. //# sourceMappingURL=babylon.polygonMesh.js.map
  64135. var BABYLON;
  64136. (function (BABYLON) {
  64137. // Unique ID when we import meshes from Babylon to CSG
  64138. var currentCSGMeshId = 0;
  64139. // # class Vertex
  64140. // Represents a vertex of a polygon. Use your own vertex class instead of this
  64141. // one to provide additional features like texture coordinates and vertex
  64142. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  64143. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  64144. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  64145. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  64146. // is not used anywhere else.
  64147. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  64148. var Vertex = /** @class */ (function () {
  64149. function Vertex(pos, normal, uv) {
  64150. this.pos = pos;
  64151. this.normal = normal;
  64152. this.uv = uv;
  64153. }
  64154. Vertex.prototype.clone = function () {
  64155. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  64156. };
  64157. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  64158. // orientation of a polygon is flipped.
  64159. Vertex.prototype.flip = function () {
  64160. this.normal = this.normal.scale(-1);
  64161. };
  64162. // Create a new vertex between this vertex and `other` by linearly
  64163. // interpolating all properties using a parameter of `t`. Subclasses should
  64164. // override this to interpolate additional properties.
  64165. Vertex.prototype.interpolate = function (other, t) {
  64166. 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));
  64167. };
  64168. return Vertex;
  64169. }());
  64170. // # class Plane
  64171. // Represents a plane in 3D space.
  64172. var Plane = /** @class */ (function () {
  64173. function Plane(normal, w) {
  64174. this.normal = normal;
  64175. this.w = w;
  64176. }
  64177. Plane.FromPoints = function (a, b, c) {
  64178. var v0 = c.subtract(a);
  64179. var v1 = b.subtract(a);
  64180. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64181. return null;
  64182. }
  64183. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64184. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64185. };
  64186. Plane.prototype.clone = function () {
  64187. return new Plane(this.normal.clone(), this.w);
  64188. };
  64189. Plane.prototype.flip = function () {
  64190. this.normal.scaleInPlace(-1);
  64191. this.w = -this.w;
  64192. };
  64193. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64194. // fragments in the appropriate lists. Coplanar polygons go into either
  64195. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64196. // respect to this plane. Polygons in front or in back of this plane go into
  64197. // either `front` or `back`.
  64198. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64199. var COPLANAR = 0;
  64200. var FRONT = 1;
  64201. var BACK = 2;
  64202. var SPANNING = 3;
  64203. // Classify each point as well as the entire polygon into one of the above
  64204. // four classes.
  64205. var polygonType = 0;
  64206. var types = [];
  64207. var i;
  64208. var t;
  64209. for (i = 0; i < polygon.vertices.length; i++) {
  64210. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64211. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64212. polygonType |= type;
  64213. types.push(type);
  64214. }
  64215. // Put the polygon in the correct list, splitting it when necessary.
  64216. switch (polygonType) {
  64217. case COPLANAR:
  64218. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64219. break;
  64220. case FRONT:
  64221. front.push(polygon);
  64222. break;
  64223. case BACK:
  64224. back.push(polygon);
  64225. break;
  64226. case SPANNING:
  64227. var f = [], b = [];
  64228. for (i = 0; i < polygon.vertices.length; i++) {
  64229. var j = (i + 1) % polygon.vertices.length;
  64230. var ti = types[i], tj = types[j];
  64231. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64232. if (ti !== BACK)
  64233. f.push(vi);
  64234. if (ti !== FRONT)
  64235. b.push(ti !== BACK ? vi.clone() : vi);
  64236. if ((ti | tj) === SPANNING) {
  64237. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  64238. var v = vi.interpolate(vj, t);
  64239. f.push(v);
  64240. b.push(v.clone());
  64241. }
  64242. }
  64243. var poly;
  64244. if (f.length >= 3) {
  64245. poly = new Polygon(f, polygon.shared);
  64246. if (poly.plane)
  64247. front.push(poly);
  64248. }
  64249. if (b.length >= 3) {
  64250. poly = new Polygon(b, polygon.shared);
  64251. if (poly.plane)
  64252. back.push(poly);
  64253. }
  64254. break;
  64255. }
  64256. };
  64257. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  64258. // point is on the plane.
  64259. Plane.EPSILON = 1e-5;
  64260. return Plane;
  64261. }());
  64262. // # class Polygon
  64263. // Represents a convex polygon. The vertices used to initialize a polygon must
  64264. // be coplanar and form a convex loop.
  64265. //
  64266. // Each convex polygon has a `shared` property, which is shared between all
  64267. // polygons that are clones of each other or were split from the same polygon.
  64268. // This can be used to define per-polygon properties (such as surface color).
  64269. var Polygon = /** @class */ (function () {
  64270. function Polygon(vertices, shared) {
  64271. this.vertices = vertices;
  64272. this.shared = shared;
  64273. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  64274. }
  64275. Polygon.prototype.clone = function () {
  64276. var vertices = this.vertices.map(function (v) { return v.clone(); });
  64277. return new Polygon(vertices, this.shared);
  64278. };
  64279. Polygon.prototype.flip = function () {
  64280. this.vertices.reverse().map(function (v) { v.flip(); });
  64281. this.plane.flip();
  64282. };
  64283. return Polygon;
  64284. }());
  64285. // # class Node
  64286. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  64287. // by picking a polygon to split along. That polygon (and all other coplanar
  64288. // polygons) are added directly to that node and the other polygons are added to
  64289. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  64290. // no distinction between internal and leaf nodes.
  64291. var Node = /** @class */ (function () {
  64292. function Node(polygons) {
  64293. this.plane = null;
  64294. this.front = null;
  64295. this.back = null;
  64296. this.polygons = new Array();
  64297. if (polygons) {
  64298. this.build(polygons);
  64299. }
  64300. }
  64301. Node.prototype.clone = function () {
  64302. var node = new Node();
  64303. node.plane = this.plane && this.plane.clone();
  64304. node.front = this.front && this.front.clone();
  64305. node.back = this.back && this.back.clone();
  64306. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  64307. return node;
  64308. };
  64309. // Convert solid space to empty space and empty space to solid space.
  64310. Node.prototype.invert = function () {
  64311. for (var i = 0; i < this.polygons.length; i++) {
  64312. this.polygons[i].flip();
  64313. }
  64314. if (this.plane) {
  64315. this.plane.flip();
  64316. }
  64317. if (this.front) {
  64318. this.front.invert();
  64319. }
  64320. if (this.back) {
  64321. this.back.invert();
  64322. }
  64323. var temp = this.front;
  64324. this.front = this.back;
  64325. this.back = temp;
  64326. };
  64327. // Recursively remove all polygons in `polygons` that are inside this BSP
  64328. // tree.
  64329. Node.prototype.clipPolygons = function (polygons) {
  64330. if (!this.plane)
  64331. return polygons.slice();
  64332. var front = new Array(), back = new Array();
  64333. for (var i = 0; i < polygons.length; i++) {
  64334. this.plane.splitPolygon(polygons[i], front, back, front, back);
  64335. }
  64336. if (this.front) {
  64337. front = this.front.clipPolygons(front);
  64338. }
  64339. if (this.back) {
  64340. back = this.back.clipPolygons(back);
  64341. }
  64342. else {
  64343. back = [];
  64344. }
  64345. return front.concat(back);
  64346. };
  64347. // Remove all polygons in this BSP tree that are inside the other BSP tree
  64348. // `bsp`.
  64349. Node.prototype.clipTo = function (bsp) {
  64350. this.polygons = bsp.clipPolygons(this.polygons);
  64351. if (this.front)
  64352. this.front.clipTo(bsp);
  64353. if (this.back)
  64354. this.back.clipTo(bsp);
  64355. };
  64356. // Return a list of all polygons in this BSP tree.
  64357. Node.prototype.allPolygons = function () {
  64358. var polygons = this.polygons.slice();
  64359. if (this.front)
  64360. polygons = polygons.concat(this.front.allPolygons());
  64361. if (this.back)
  64362. polygons = polygons.concat(this.back.allPolygons());
  64363. return polygons;
  64364. };
  64365. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  64366. // new polygons are filtered down to the bottom of the tree and become new
  64367. // nodes there. Each set of polygons is partitioned using the first polygon
  64368. // (no heuristic is used to pick a good split).
  64369. Node.prototype.build = function (polygons) {
  64370. if (!polygons.length)
  64371. return;
  64372. if (!this.plane)
  64373. this.plane = polygons[0].plane.clone();
  64374. var front = new Array(), back = new Array();
  64375. for (var i = 0; i < polygons.length; i++) {
  64376. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  64377. }
  64378. if (front.length) {
  64379. if (!this.front)
  64380. this.front = new Node();
  64381. this.front.build(front);
  64382. }
  64383. if (back.length) {
  64384. if (!this.back)
  64385. this.back = new Node();
  64386. this.back.build(back);
  64387. }
  64388. };
  64389. return Node;
  64390. }());
  64391. var CSG = /** @class */ (function () {
  64392. function CSG() {
  64393. this.polygons = new Array();
  64394. }
  64395. // Convert BABYLON.Mesh to BABYLON.CSG
  64396. CSG.FromMesh = function (mesh) {
  64397. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  64398. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  64399. if (mesh instanceof BABYLON.Mesh) {
  64400. mesh.computeWorldMatrix(true);
  64401. matrix = mesh.getWorldMatrix();
  64402. meshPosition = mesh.position.clone();
  64403. meshRotation = mesh.rotation.clone();
  64404. if (mesh.rotationQuaternion) {
  64405. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  64406. }
  64407. meshScaling = mesh.scaling.clone();
  64408. }
  64409. else {
  64410. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  64411. }
  64412. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64413. var subMeshes = mesh.subMeshes;
  64414. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  64415. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  64416. vertices = [];
  64417. for (var j = 0; j < 3; j++) {
  64418. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  64419. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  64420. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  64421. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  64422. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  64423. vertex = new Vertex(position, normal, uv);
  64424. vertices.push(vertex);
  64425. }
  64426. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  64427. // To handle the case of degenerated triangle
  64428. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  64429. if (polygon.plane)
  64430. polygons.push(polygon);
  64431. }
  64432. }
  64433. var csg = CSG.FromPolygons(polygons);
  64434. csg.matrix = matrix;
  64435. csg.position = meshPosition;
  64436. csg.rotation = meshRotation;
  64437. csg.scaling = meshScaling;
  64438. csg.rotationQuaternion = meshRotationQuaternion;
  64439. currentCSGMeshId++;
  64440. return csg;
  64441. };
  64442. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  64443. CSG.FromPolygons = function (polygons) {
  64444. var csg = new CSG();
  64445. csg.polygons = polygons;
  64446. return csg;
  64447. };
  64448. CSG.prototype.clone = function () {
  64449. var csg = new CSG();
  64450. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  64451. csg.copyTransformAttributes(this);
  64452. return csg;
  64453. };
  64454. CSG.prototype.union = function (csg) {
  64455. var a = new Node(this.clone().polygons);
  64456. var b = new Node(csg.clone().polygons);
  64457. a.clipTo(b);
  64458. b.clipTo(a);
  64459. b.invert();
  64460. b.clipTo(a);
  64461. b.invert();
  64462. a.build(b.allPolygons());
  64463. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64464. };
  64465. CSG.prototype.unionInPlace = function (csg) {
  64466. var a = new Node(this.polygons);
  64467. var b = new Node(csg.polygons);
  64468. a.clipTo(b);
  64469. b.clipTo(a);
  64470. b.invert();
  64471. b.clipTo(a);
  64472. b.invert();
  64473. a.build(b.allPolygons());
  64474. this.polygons = a.allPolygons();
  64475. };
  64476. CSG.prototype.subtract = function (csg) {
  64477. var a = new Node(this.clone().polygons);
  64478. var b = new Node(csg.clone().polygons);
  64479. a.invert();
  64480. a.clipTo(b);
  64481. b.clipTo(a);
  64482. b.invert();
  64483. b.clipTo(a);
  64484. b.invert();
  64485. a.build(b.allPolygons());
  64486. a.invert();
  64487. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64488. };
  64489. CSG.prototype.subtractInPlace = function (csg) {
  64490. var a = new Node(this.polygons);
  64491. var b = new Node(csg.polygons);
  64492. a.invert();
  64493. a.clipTo(b);
  64494. b.clipTo(a);
  64495. b.invert();
  64496. b.clipTo(a);
  64497. b.invert();
  64498. a.build(b.allPolygons());
  64499. a.invert();
  64500. this.polygons = a.allPolygons();
  64501. };
  64502. CSG.prototype.intersect = function (csg) {
  64503. var a = new Node(this.clone().polygons);
  64504. var b = new Node(csg.clone().polygons);
  64505. a.invert();
  64506. b.clipTo(a);
  64507. b.invert();
  64508. a.clipTo(b);
  64509. b.clipTo(a);
  64510. a.build(b.allPolygons());
  64511. a.invert();
  64512. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64513. };
  64514. CSG.prototype.intersectInPlace = function (csg) {
  64515. var a = new Node(this.polygons);
  64516. var b = new Node(csg.polygons);
  64517. a.invert();
  64518. b.clipTo(a);
  64519. b.invert();
  64520. a.clipTo(b);
  64521. b.clipTo(a);
  64522. a.build(b.allPolygons());
  64523. a.invert();
  64524. this.polygons = a.allPolygons();
  64525. };
  64526. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  64527. // not modified.
  64528. CSG.prototype.inverse = function () {
  64529. var csg = this.clone();
  64530. csg.inverseInPlace();
  64531. return csg;
  64532. };
  64533. CSG.prototype.inverseInPlace = function () {
  64534. this.polygons.map(function (p) { p.flip(); });
  64535. };
  64536. // This is used to keep meshes transformations so they can be restored
  64537. // when we build back a Babylon Mesh
  64538. // NB : All CSG operations are performed in world coordinates
  64539. CSG.prototype.copyTransformAttributes = function (csg) {
  64540. this.matrix = csg.matrix;
  64541. this.position = csg.position;
  64542. this.rotation = csg.rotation;
  64543. this.scaling = csg.scaling;
  64544. this.rotationQuaternion = csg.rotationQuaternion;
  64545. return this;
  64546. };
  64547. // Build Raw mesh from CSG
  64548. // Coordinates here are in world space
  64549. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  64550. var matrix = this.matrix.clone();
  64551. matrix.invert();
  64552. 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;
  64553. if (keepSubMeshes) {
  64554. // Sort Polygons, since subMeshes are indices range
  64555. polygons.sort(function (a, b) {
  64556. if (a.shared.meshId === b.shared.meshId) {
  64557. return a.shared.subMeshId - b.shared.subMeshId;
  64558. }
  64559. else {
  64560. return a.shared.meshId - b.shared.meshId;
  64561. }
  64562. });
  64563. }
  64564. for (var i = 0, il = polygons.length; i < il; i++) {
  64565. polygon = polygons[i];
  64566. // Building SubMeshes
  64567. if (!subMesh_dict[polygon.shared.meshId]) {
  64568. subMesh_dict[polygon.shared.meshId] = {};
  64569. }
  64570. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  64571. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  64572. indexStart: +Infinity,
  64573. indexEnd: -Infinity,
  64574. materialIndex: polygon.shared.materialIndex
  64575. };
  64576. }
  64577. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  64578. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  64579. polygonIndices[0] = 0;
  64580. polygonIndices[1] = j - 1;
  64581. polygonIndices[2] = j;
  64582. for (var k = 0; k < 3; k++) {
  64583. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  64584. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  64585. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  64586. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  64587. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  64588. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  64589. // Check if 2 points can be merged
  64590. if (!(typeof vertex_idx !== 'undefined' &&
  64591. normals[vertex_idx * 3] === localNormal.x &&
  64592. normals[vertex_idx * 3 + 1] === localNormal.y &&
  64593. normals[vertex_idx * 3 + 2] === localNormal.z &&
  64594. uvs[vertex_idx * 2] === uv.x &&
  64595. uvs[vertex_idx * 2 + 1] === uv.y)) {
  64596. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  64597. uvs.push(uv.x, uv.y);
  64598. normals.push(normal.x, normal.y, normal.z);
  64599. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  64600. }
  64601. indices.push(vertex_idx);
  64602. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  64603. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  64604. currentIndex++;
  64605. }
  64606. }
  64607. }
  64608. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  64609. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  64610. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  64611. mesh.setIndices(indices, null);
  64612. if (keepSubMeshes) {
  64613. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  64614. var materialIndexOffset = 0, materialMaxIndex;
  64615. mesh.subMeshes = new Array();
  64616. for (var m in subMesh_dict) {
  64617. materialMaxIndex = -1;
  64618. for (var sm in subMesh_dict[m]) {
  64619. subMesh_obj = subMesh_dict[m][sm];
  64620. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  64621. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  64622. }
  64623. materialIndexOffset += ++materialMaxIndex;
  64624. }
  64625. }
  64626. return mesh;
  64627. };
  64628. // Build Mesh from CSG taking material and transforms into account
  64629. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  64630. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  64631. mesh.material = material;
  64632. mesh.position.copyFrom(this.position);
  64633. mesh.rotation.copyFrom(this.rotation);
  64634. if (this.rotationQuaternion) {
  64635. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  64636. }
  64637. mesh.scaling.copyFrom(this.scaling);
  64638. mesh.computeWorldMatrix(true);
  64639. return mesh;
  64640. };
  64641. return CSG;
  64642. }());
  64643. BABYLON.CSG = CSG;
  64644. })(BABYLON || (BABYLON = {}));
  64645. //# sourceMappingURL=babylon.csg.js.map
  64646. var BABYLON;
  64647. (function (BABYLON) {
  64648. var LensFlare = /** @class */ (function () {
  64649. function LensFlare(size, position, color, imgUrl, system) {
  64650. this.size = size;
  64651. this.position = position;
  64652. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  64653. this.color = color || new BABYLON.Color3(1, 1, 1);
  64654. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  64655. this._system = system;
  64656. system.lensFlares.push(this);
  64657. }
  64658. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  64659. return new LensFlare(size, position, color, imgUrl, system);
  64660. };
  64661. LensFlare.prototype.dispose = function () {
  64662. if (this.texture) {
  64663. this.texture.dispose();
  64664. }
  64665. // Remove from scene
  64666. var index = this._system.lensFlares.indexOf(this);
  64667. this._system.lensFlares.splice(index, 1);
  64668. };
  64669. ;
  64670. return LensFlare;
  64671. }());
  64672. BABYLON.LensFlare = LensFlare;
  64673. })(BABYLON || (BABYLON = {}));
  64674. //# sourceMappingURL=babylon.lensFlare.js.map
  64675. var BABYLON;
  64676. (function (BABYLON) {
  64677. var LensFlareSystem = /** @class */ (function () {
  64678. function LensFlareSystem(name, emitter, scene) {
  64679. this.name = name;
  64680. this.lensFlares = new Array();
  64681. this.borderLimit = 300;
  64682. this.viewportBorder = 0;
  64683. this.layerMask = 0x0FFFFFFF;
  64684. this._vertexBuffers = {};
  64685. this._isEnabled = true;
  64686. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64687. this._emitter = emitter;
  64688. this.id = name;
  64689. scene.lensFlareSystems.push(this);
  64690. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  64691. var engine = scene.getEngine();
  64692. // VBO
  64693. var vertices = [];
  64694. vertices.push(1, 1);
  64695. vertices.push(-1, 1);
  64696. vertices.push(-1, -1);
  64697. vertices.push(1, -1);
  64698. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64699. // Indices
  64700. var indices = [];
  64701. indices.push(0);
  64702. indices.push(1);
  64703. indices.push(2);
  64704. indices.push(0);
  64705. indices.push(2);
  64706. indices.push(3);
  64707. this._indexBuffer = engine.createIndexBuffer(indices);
  64708. // Effects
  64709. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  64710. }
  64711. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  64712. get: function () {
  64713. return this._isEnabled;
  64714. },
  64715. set: function (value) {
  64716. this._isEnabled = value;
  64717. },
  64718. enumerable: true,
  64719. configurable: true
  64720. });
  64721. LensFlareSystem.prototype.getScene = function () {
  64722. return this._scene;
  64723. };
  64724. LensFlareSystem.prototype.getEmitter = function () {
  64725. return this._emitter;
  64726. };
  64727. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  64728. this._emitter = newEmitter;
  64729. };
  64730. LensFlareSystem.prototype.getEmitterPosition = function () {
  64731. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  64732. };
  64733. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  64734. var position = this.getEmitterPosition();
  64735. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  64736. this._positionX = position.x;
  64737. this._positionY = position.y;
  64738. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  64739. if (this.viewportBorder > 0) {
  64740. globalViewport.x -= this.viewportBorder;
  64741. globalViewport.y -= this.viewportBorder;
  64742. globalViewport.width += this.viewportBorder * 2;
  64743. globalViewport.height += this.viewportBorder * 2;
  64744. position.x += this.viewportBorder;
  64745. position.y += this.viewportBorder;
  64746. this._positionX += this.viewportBorder;
  64747. this._positionY += this.viewportBorder;
  64748. }
  64749. if (position.z > 0) {
  64750. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  64751. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  64752. return true;
  64753. }
  64754. return true;
  64755. }
  64756. return false;
  64757. };
  64758. LensFlareSystem.prototype._isVisible = function () {
  64759. if (!this._isEnabled || !this._scene.activeCamera) {
  64760. return false;
  64761. }
  64762. var emitterPosition = this.getEmitterPosition();
  64763. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  64764. var distance = direction.length();
  64765. direction.normalize();
  64766. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  64767. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  64768. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  64769. };
  64770. LensFlareSystem.prototype.render = function () {
  64771. if (!this._effect.isReady() || !this._scene.activeCamera)
  64772. return false;
  64773. var engine = this._scene.getEngine();
  64774. var viewport = this._scene.activeCamera.viewport;
  64775. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  64776. // Position
  64777. if (!this.computeEffectivePosition(globalViewport)) {
  64778. return false;
  64779. }
  64780. // Visibility
  64781. if (!this._isVisible()) {
  64782. return false;
  64783. }
  64784. // Intensity
  64785. var awayX;
  64786. var awayY;
  64787. if (this._positionX < this.borderLimit + globalViewport.x) {
  64788. awayX = this.borderLimit + globalViewport.x - this._positionX;
  64789. }
  64790. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  64791. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  64792. }
  64793. else {
  64794. awayX = 0;
  64795. }
  64796. if (this._positionY < this.borderLimit + globalViewport.y) {
  64797. awayY = this.borderLimit + globalViewport.y - this._positionY;
  64798. }
  64799. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  64800. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  64801. }
  64802. else {
  64803. awayY = 0;
  64804. }
  64805. var away = (awayX > awayY) ? awayX : awayY;
  64806. away -= this.viewportBorder;
  64807. if (away > this.borderLimit) {
  64808. away = this.borderLimit;
  64809. }
  64810. var intensity = 1.0 - (away / this.borderLimit);
  64811. if (intensity < 0) {
  64812. return false;
  64813. }
  64814. if (intensity > 1.0) {
  64815. intensity = 1.0;
  64816. }
  64817. if (this.viewportBorder > 0) {
  64818. globalViewport.x += this.viewportBorder;
  64819. globalViewport.y += this.viewportBorder;
  64820. globalViewport.width -= this.viewportBorder * 2;
  64821. globalViewport.height -= this.viewportBorder * 2;
  64822. this._positionX -= this.viewportBorder;
  64823. this._positionY -= this.viewportBorder;
  64824. }
  64825. // Position
  64826. var centerX = globalViewport.x + globalViewport.width / 2;
  64827. var centerY = globalViewport.y + globalViewport.height / 2;
  64828. var distX = centerX - this._positionX;
  64829. var distY = centerY - this._positionY;
  64830. // Effects
  64831. engine.enableEffect(this._effect);
  64832. engine.setState(false);
  64833. engine.setDepthBuffer(false);
  64834. // VBOs
  64835. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64836. // Flares
  64837. for (var index = 0; index < this.lensFlares.length; index++) {
  64838. var flare = this.lensFlares[index];
  64839. engine.setAlphaMode(flare.alphaMode);
  64840. var x = centerX - (distX * flare.position);
  64841. var y = centerY - (distY * flare.position);
  64842. var cw = flare.size;
  64843. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  64844. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  64845. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  64846. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  64847. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  64848. // Texture
  64849. this._effect.setTexture("textureSampler", flare.texture);
  64850. // Color
  64851. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  64852. // Draw order
  64853. engine.draw(true, 0, 6);
  64854. }
  64855. engine.setDepthBuffer(true);
  64856. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64857. return true;
  64858. };
  64859. LensFlareSystem.prototype.dispose = function () {
  64860. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64861. if (vertexBuffer) {
  64862. vertexBuffer.dispose();
  64863. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64864. }
  64865. if (this._indexBuffer) {
  64866. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64867. this._indexBuffer = null;
  64868. }
  64869. while (this.lensFlares.length) {
  64870. this.lensFlares[0].dispose();
  64871. }
  64872. // Remove from scene
  64873. var index = this._scene.lensFlareSystems.indexOf(this);
  64874. this._scene.lensFlareSystems.splice(index, 1);
  64875. };
  64876. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  64877. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  64878. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  64879. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  64880. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  64881. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  64882. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  64883. var parsedFlare = parsedLensFlareSystem.flares[index];
  64884. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  64885. }
  64886. return lensFlareSystem;
  64887. };
  64888. LensFlareSystem.prototype.serialize = function () {
  64889. var serializationObject = {};
  64890. serializationObject.id = this.id;
  64891. serializationObject.name = this.name;
  64892. serializationObject.emitterId = this.getEmitter().id;
  64893. serializationObject.borderLimit = this.borderLimit;
  64894. serializationObject.flares = [];
  64895. for (var index = 0; index < this.lensFlares.length; index++) {
  64896. var flare = this.lensFlares[index];
  64897. serializationObject.flares.push({
  64898. size: flare.size,
  64899. position: flare.position,
  64900. color: flare.color.asArray(),
  64901. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  64902. });
  64903. }
  64904. return serializationObject;
  64905. };
  64906. return LensFlareSystem;
  64907. }());
  64908. BABYLON.LensFlareSystem = LensFlareSystem;
  64909. })(BABYLON || (BABYLON = {}));
  64910. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  64911. var BABYLON;
  64912. (function (BABYLON) {
  64913. /**
  64914. * This is a holder class for the physics joint created by the physics plugin.
  64915. * It holds a set of functions to control the underlying joint.
  64916. */
  64917. var PhysicsJoint = /** @class */ (function () {
  64918. function PhysicsJoint(type, jointData) {
  64919. this.type = type;
  64920. this.jointData = jointData;
  64921. jointData.nativeParams = jointData.nativeParams || {};
  64922. }
  64923. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  64924. get: function () {
  64925. return this._physicsJoint;
  64926. },
  64927. set: function (newJoint) {
  64928. if (this._physicsJoint) {
  64929. //remove from the wolrd
  64930. }
  64931. this._physicsJoint = newJoint;
  64932. },
  64933. enumerable: true,
  64934. configurable: true
  64935. });
  64936. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  64937. set: function (physicsPlugin) {
  64938. this._physicsPlugin = physicsPlugin;
  64939. },
  64940. enumerable: true,
  64941. configurable: true
  64942. });
  64943. /**
  64944. * Execute a function that is physics-plugin specific.
  64945. * @param {Function} func the function that will be executed.
  64946. * It accepts two parameters: the physics world and the physics joint.
  64947. */
  64948. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  64949. func(this._physicsPlugin.world, this._physicsJoint);
  64950. };
  64951. //TODO check if the native joints are the same
  64952. //Joint Types
  64953. PhysicsJoint.DistanceJoint = 0;
  64954. PhysicsJoint.HingeJoint = 1;
  64955. PhysicsJoint.BallAndSocketJoint = 2;
  64956. PhysicsJoint.WheelJoint = 3;
  64957. PhysicsJoint.SliderJoint = 4;
  64958. //OIMO
  64959. PhysicsJoint.PrismaticJoint = 5;
  64960. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  64961. PhysicsJoint.UniversalJoint = 6;
  64962. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  64963. //Cannon
  64964. //Similar to a Ball-Joint. Different in params
  64965. PhysicsJoint.PointToPointJoint = 8;
  64966. //Cannon only at the moment
  64967. PhysicsJoint.SpringJoint = 9;
  64968. PhysicsJoint.LockJoint = 10;
  64969. return PhysicsJoint;
  64970. }());
  64971. BABYLON.PhysicsJoint = PhysicsJoint;
  64972. /**
  64973. * A class representing a physics distance joint.
  64974. */
  64975. var DistanceJoint = /** @class */ (function (_super) {
  64976. __extends(DistanceJoint, _super);
  64977. function DistanceJoint(jointData) {
  64978. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  64979. }
  64980. /**
  64981. * Update the predefined distance.
  64982. */
  64983. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  64984. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  64985. };
  64986. return DistanceJoint;
  64987. }(PhysicsJoint));
  64988. BABYLON.DistanceJoint = DistanceJoint;
  64989. var MotorEnabledJoint = /** @class */ (function (_super) {
  64990. __extends(MotorEnabledJoint, _super);
  64991. function MotorEnabledJoint(type, jointData) {
  64992. return _super.call(this, type, jointData) || this;
  64993. }
  64994. /**
  64995. * Set the motor values.
  64996. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64997. * @param {number} force the force to apply
  64998. * @param {number} maxForce max force for this motor.
  64999. */
  65000. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  65001. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65002. };
  65003. /**
  65004. * Set the motor's limits.
  65005. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65006. */
  65007. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65008. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65009. };
  65010. return MotorEnabledJoint;
  65011. }(PhysicsJoint));
  65012. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  65013. /**
  65014. * This class represents a single hinge physics joint
  65015. */
  65016. var HingeJoint = /** @class */ (function (_super) {
  65017. __extends(HingeJoint, _super);
  65018. function HingeJoint(jointData) {
  65019. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  65020. }
  65021. /**
  65022. * Set the motor values.
  65023. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65024. * @param {number} force the force to apply
  65025. * @param {number} maxForce max force for this motor.
  65026. */
  65027. HingeJoint.prototype.setMotor = function (force, maxForce) {
  65028. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65029. };
  65030. /**
  65031. * Set the motor's limits.
  65032. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65033. */
  65034. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65035. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65036. };
  65037. return HingeJoint;
  65038. }(MotorEnabledJoint));
  65039. BABYLON.HingeJoint = HingeJoint;
  65040. /**
  65041. * This class represents a dual hinge physics joint (same as wheel joint)
  65042. */
  65043. var Hinge2Joint = /** @class */ (function (_super) {
  65044. __extends(Hinge2Joint, _super);
  65045. function Hinge2Joint(jointData) {
  65046. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  65047. }
  65048. /**
  65049. * Set the motor values.
  65050. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65051. * @param {number} force the force to apply
  65052. * @param {number} maxForce max force for this motor.
  65053. * @param {motorIndex} the motor's index, 0 or 1.
  65054. */
  65055. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  65056. if (motorIndex === void 0) { motorIndex = 0; }
  65057. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  65058. };
  65059. /**
  65060. * Set the motor limits.
  65061. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65062. * @param {number} upperLimit the upper limit
  65063. * @param {number} lowerLimit lower limit
  65064. * @param {motorIndex} the motor's index, 0 or 1.
  65065. */
  65066. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  65067. if (motorIndex === void 0) { motorIndex = 0; }
  65068. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  65069. };
  65070. return Hinge2Joint;
  65071. }(MotorEnabledJoint));
  65072. BABYLON.Hinge2Joint = Hinge2Joint;
  65073. })(BABYLON || (BABYLON = {}));
  65074. //# sourceMappingURL=babylon.physicsJoint.js.map
  65075. var BABYLON;
  65076. (function (BABYLON) {
  65077. var PhysicsImpostor = /** @class */ (function () {
  65078. function PhysicsImpostor(object, type, _options, _scene) {
  65079. if (_options === void 0) { _options = { mass: 0 }; }
  65080. var _this = this;
  65081. this.object = object;
  65082. this.type = type;
  65083. this._options = _options;
  65084. this._scene = _scene;
  65085. this._bodyUpdateRequired = false;
  65086. this._onBeforePhysicsStepCallbacks = new Array();
  65087. this._onAfterPhysicsStepCallbacks = new Array();
  65088. this._onPhysicsCollideCallbacks = [];
  65089. this._deltaPosition = BABYLON.Vector3.Zero();
  65090. this._isDisposed = false;
  65091. //temp variables for parent rotation calculations
  65092. this._mats = [new BABYLON.Matrix(), new BABYLON.Matrix()];
  65093. this._tmpQuat = new BABYLON.Quaternion();
  65094. /**
  65095. * this function is executed by the physics engine.
  65096. */
  65097. this.beforeStep = function () {
  65098. if (!_this._physicsEngine) {
  65099. return;
  65100. }
  65101. _this.object.translate(_this._deltaPosition, -1);
  65102. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  65103. if (_this.object.parent) {
  65104. _this.object.computeWorldMatrix(false).getRotationMatrixToRef(_this._mats[0]);
  65105. BABYLON.Quaternion.FromRotationMatrixToRef(_this._mats[0], _this._tmpQuat);
  65106. _this._tmpQuat.normalize();
  65107. }
  65108. else {
  65109. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  65110. }
  65111. if (!_this._options.disableBidirectionalTransformation) {
  65112. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  65113. }
  65114. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  65115. func(_this);
  65116. });
  65117. };
  65118. /**
  65119. * this function is executed by the physics engine.
  65120. */
  65121. this.afterStep = function () {
  65122. if (!_this._physicsEngine) {
  65123. return;
  65124. }
  65125. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  65126. // object has now its world rotation. needs to be converted to local.
  65127. if (_this.object.parent && _this.object.rotationQuaternion) {
  65128. _this.object.parent.computeWorldMatrix(false).getRotationMatrixToRef(_this._mats[0]);
  65129. BABYLON.Quaternion.FromRotationMatrixToRef(_this._mats[0], _this._tmpQuat);
  65130. _this._tmpQuat.conjugateInPlace();
  65131. _this._tmpQuat.normalize();
  65132. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  65133. }
  65134. // take the position set and make it the absolute position of this object.
  65135. _this.object.setAbsolutePosition(_this.object.position);
  65136. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  65137. _this.object.translate(_this._deltaPosition, 1);
  65138. };
  65139. /**
  65140. * Legacy collision detection event support
  65141. */
  65142. this.onCollideEvent = null;
  65143. //event and body object due to cannon's event-based architecture.
  65144. this.onCollide = function (e) {
  65145. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  65146. return;
  65147. }
  65148. if (!_this._physicsEngine) {
  65149. return;
  65150. }
  65151. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  65152. if (otherImpostor) {
  65153. // Legacy collision detection event support
  65154. if (_this.onCollideEvent) {
  65155. _this.onCollideEvent(_this, otherImpostor);
  65156. }
  65157. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65158. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65159. }).forEach(function (obj) {
  65160. obj.callback(_this, otherImpostor);
  65161. });
  65162. }
  65163. };
  65164. //sanity check!
  65165. if (!this.object) {
  65166. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65167. return;
  65168. }
  65169. //legacy support for old syntax.
  65170. if (!this._scene && object.getScene) {
  65171. this._scene = object.getScene();
  65172. }
  65173. if (!this._scene) {
  65174. return;
  65175. }
  65176. this._physicsEngine = this._scene.getPhysicsEngine();
  65177. if (!this._physicsEngine) {
  65178. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65179. }
  65180. else {
  65181. //set the object's quaternion, if not set
  65182. if (!this.object.rotationQuaternion) {
  65183. if (this.object.rotation) {
  65184. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65185. }
  65186. else {
  65187. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65188. }
  65189. }
  65190. //default options params
  65191. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65192. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65193. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65194. this._joints = [];
  65195. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65196. if (!this.object.parent || this._options.ignoreParent) {
  65197. this._init();
  65198. }
  65199. else if (this.object.parent.physicsImpostor) {
  65200. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65201. }
  65202. }
  65203. }
  65204. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65205. get: function () {
  65206. return this._isDisposed;
  65207. },
  65208. enumerable: true,
  65209. configurable: true
  65210. });
  65211. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65212. get: function () {
  65213. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65214. },
  65215. set: function (value) {
  65216. this.setMass(value);
  65217. },
  65218. enumerable: true,
  65219. configurable: true
  65220. });
  65221. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65222. get: function () {
  65223. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65224. },
  65225. set: function (value) {
  65226. if (!this._physicsEngine) {
  65227. return;
  65228. }
  65229. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65230. },
  65231. enumerable: true,
  65232. configurable: true
  65233. });
  65234. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  65235. get: function () {
  65236. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  65237. },
  65238. set: function (value) {
  65239. if (!this._physicsEngine) {
  65240. return;
  65241. }
  65242. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  65243. },
  65244. enumerable: true,
  65245. configurable: true
  65246. });
  65247. /**
  65248. * This function will completly initialize this impostor.
  65249. * It will create a new body - but only if this mesh has no parent.
  65250. * If it has, this impostor will not be used other than to define the impostor
  65251. * of the child mesh.
  65252. */
  65253. PhysicsImpostor.prototype._init = function () {
  65254. if (!this._physicsEngine) {
  65255. return;
  65256. }
  65257. this._physicsEngine.removeImpostor(this);
  65258. this.physicsBody = null;
  65259. this._parent = this._parent || this._getPhysicsParent();
  65260. if (!this.parent || this._options.ignoreParent) {
  65261. this._physicsEngine.addImpostor(this);
  65262. }
  65263. };
  65264. PhysicsImpostor.prototype._getPhysicsParent = function () {
  65265. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  65266. var parentMesh = this.object.parent;
  65267. return parentMesh.physicsImpostor;
  65268. }
  65269. return null;
  65270. };
  65271. /**
  65272. * Should a new body be generated.
  65273. */
  65274. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  65275. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  65276. };
  65277. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  65278. this.forceUpdate();
  65279. };
  65280. /**
  65281. * Force a regeneration of this or the parent's impostor's body.
  65282. * Use under cautious - This will remove all joints already implemented.
  65283. */
  65284. PhysicsImpostor.prototype.forceUpdate = function () {
  65285. this._init();
  65286. if (this.parent && !this._options.ignoreParent) {
  65287. this.parent.forceUpdate();
  65288. }
  65289. };
  65290. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  65291. /*public get mesh(): AbstractMesh {
  65292. return this._mesh;
  65293. }*/
  65294. /**
  65295. * Gets the body that holds this impostor. Either its own, or its parent.
  65296. */
  65297. get: function () {
  65298. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  65299. },
  65300. /**
  65301. * Set the physics body. Used mainly by the physics engine/plugin
  65302. */
  65303. set: function (physicsBody) {
  65304. if (this._physicsBody && this._physicsEngine) {
  65305. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  65306. }
  65307. this._physicsBody = physicsBody;
  65308. this.resetUpdateFlags();
  65309. },
  65310. enumerable: true,
  65311. configurable: true
  65312. });
  65313. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  65314. get: function () {
  65315. return !this._options.ignoreParent && this._parent ? this._parent : null;
  65316. },
  65317. set: function (value) {
  65318. this._parent = value;
  65319. },
  65320. enumerable: true,
  65321. configurable: true
  65322. });
  65323. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  65324. this._bodyUpdateRequired = false;
  65325. };
  65326. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  65327. if (this.object.getBoundingInfo) {
  65328. var q = this.object.rotationQuaternion;
  65329. //reset rotation
  65330. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  65331. //calculate the world matrix with no rotation
  65332. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65333. var boundingInfo = this.object.getBoundingInfo();
  65334. var size = void 0;
  65335. if (boundingInfo) {
  65336. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  65337. }
  65338. else {
  65339. size = BABYLON.Vector3.Zero();
  65340. }
  65341. //bring back the rotation
  65342. this.object.rotationQuaternion = q;
  65343. //calculate the world matrix with the new rotation
  65344. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65345. return size;
  65346. }
  65347. else {
  65348. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  65349. }
  65350. };
  65351. PhysicsImpostor.prototype.getObjectCenter = function () {
  65352. if (this.object.getBoundingInfo) {
  65353. var boundingInfo = this.object.getBoundingInfo();
  65354. if (!boundingInfo) {
  65355. return this.object.position;
  65356. }
  65357. return boundingInfo.boundingBox.centerWorld;
  65358. }
  65359. else {
  65360. return this.object.position;
  65361. }
  65362. };
  65363. /**
  65364. * Get a specific parametes from the options parameter.
  65365. */
  65366. PhysicsImpostor.prototype.getParam = function (paramName) {
  65367. return this._options[paramName];
  65368. };
  65369. /**
  65370. * Sets a specific parameter in the options given to the physics plugin
  65371. */
  65372. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  65373. this._options[paramName] = value;
  65374. this._bodyUpdateRequired = true;
  65375. };
  65376. /**
  65377. * Specifically change the body's mass option. Won't recreate the physics body object
  65378. */
  65379. PhysicsImpostor.prototype.setMass = function (mass) {
  65380. if (this.getParam("mass") !== mass) {
  65381. this.setParam("mass", mass);
  65382. }
  65383. if (this._physicsEngine) {
  65384. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  65385. }
  65386. };
  65387. PhysicsImpostor.prototype.getLinearVelocity = function () {
  65388. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  65389. };
  65390. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  65391. if (this._physicsEngine) {
  65392. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  65393. }
  65394. };
  65395. PhysicsImpostor.prototype.getAngularVelocity = function () {
  65396. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  65397. };
  65398. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  65399. if (this._physicsEngine) {
  65400. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  65401. }
  65402. };
  65403. /**
  65404. * Execute a function with the physics plugin native code.
  65405. * Provide a function the will have two variables - the world object and the physics body object.
  65406. */
  65407. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  65408. if (this._physicsEngine) {
  65409. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  65410. }
  65411. };
  65412. /**
  65413. * Register a function that will be executed before the physics world is stepping forward.
  65414. */
  65415. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  65416. this._onBeforePhysicsStepCallbacks.push(func);
  65417. };
  65418. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  65419. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  65420. if (index > -1) {
  65421. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  65422. }
  65423. else {
  65424. BABYLON.Tools.Warn("Function to remove was not found");
  65425. }
  65426. };
  65427. /**
  65428. * Register a function that will be executed after the physics step
  65429. */
  65430. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  65431. this._onAfterPhysicsStepCallbacks.push(func);
  65432. };
  65433. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  65434. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  65435. if (index > -1) {
  65436. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  65437. }
  65438. else {
  65439. BABYLON.Tools.Warn("Function to remove was not found");
  65440. }
  65441. };
  65442. /**
  65443. * register a function that will be executed when this impostor collides against a different body.
  65444. */
  65445. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  65446. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65447. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  65448. };
  65449. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  65450. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65451. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  65452. if (index > -1) {
  65453. this._onPhysicsCollideCallbacks.splice(index, 1);
  65454. }
  65455. else {
  65456. BABYLON.Tools.Warn("Function to remove was not found");
  65457. }
  65458. };
  65459. /**
  65460. * Apply a force
  65461. */
  65462. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  65463. if (this._physicsEngine) {
  65464. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  65465. }
  65466. return this;
  65467. };
  65468. /**
  65469. * Apply an impulse
  65470. */
  65471. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  65472. if (this._physicsEngine) {
  65473. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  65474. }
  65475. return this;
  65476. };
  65477. /**
  65478. * A help function to create a joint.
  65479. */
  65480. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  65481. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  65482. this.addJoint(otherImpostor, joint);
  65483. return this;
  65484. };
  65485. /**
  65486. * Add a joint to this impostor with a different impostor.
  65487. */
  65488. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  65489. this._joints.push({
  65490. otherImpostor: otherImpostor,
  65491. joint: joint
  65492. });
  65493. if (this._physicsEngine) {
  65494. this._physicsEngine.addJoint(this, otherImpostor, joint);
  65495. }
  65496. return this;
  65497. };
  65498. /**
  65499. * Will keep this body still, in a sleep mode.
  65500. */
  65501. PhysicsImpostor.prototype.sleep = function () {
  65502. if (this._physicsEngine) {
  65503. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  65504. }
  65505. return this;
  65506. };
  65507. /**
  65508. * Wake the body up.
  65509. */
  65510. PhysicsImpostor.prototype.wakeUp = function () {
  65511. if (this._physicsEngine) {
  65512. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  65513. }
  65514. return this;
  65515. };
  65516. PhysicsImpostor.prototype.clone = function (newObject) {
  65517. if (!newObject)
  65518. return null;
  65519. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  65520. };
  65521. PhysicsImpostor.prototype.dispose = function () {
  65522. var _this = this;
  65523. //no dispose if no physics engine is available.
  65524. if (!this._physicsEngine) {
  65525. return;
  65526. }
  65527. this._joints.forEach(function (j) {
  65528. if (_this._physicsEngine) {
  65529. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  65530. }
  65531. });
  65532. //dispose the physics body
  65533. this._physicsEngine.removeImpostor(this);
  65534. if (this.parent) {
  65535. this.parent.forceUpdate();
  65536. }
  65537. else {
  65538. /*this._object.getChildMeshes().forEach(function(mesh) {
  65539. if (mesh.physicsImpostor) {
  65540. if (disposeChildren) {
  65541. mesh.physicsImpostor.dispose();
  65542. mesh.physicsImpostor = null;
  65543. }
  65544. }
  65545. })*/
  65546. }
  65547. this._isDisposed = true;
  65548. };
  65549. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  65550. this._deltaPosition.copyFrom(position);
  65551. };
  65552. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  65553. if (!this._deltaRotation) {
  65554. this._deltaRotation = new BABYLON.Quaternion();
  65555. }
  65556. this._deltaRotation.copyFrom(rotation);
  65557. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  65558. };
  65559. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  65560. if (this._physicsEngine) {
  65561. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  65562. }
  65563. return this;
  65564. };
  65565. PhysicsImpostor.prototype.getRadius = function () {
  65566. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  65567. };
  65568. /**
  65569. * Sync a bone with this impostor
  65570. * @param bone The bone to sync to the impostor.
  65571. * @param boneMesh The mesh that the bone is influencing.
  65572. * @param jointPivot The pivot of the joint / bone in local space.
  65573. * @param distToJoint Optional distance from the impostor to the joint.
  65574. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65575. */
  65576. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  65577. var tempVec = PhysicsImpostor._tmpVecs[0];
  65578. var mesh = this.object;
  65579. if (mesh.rotationQuaternion) {
  65580. if (adjustRotation) {
  65581. var tempQuat = PhysicsImpostor._tmpQuat;
  65582. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  65583. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  65584. }
  65585. else {
  65586. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  65587. }
  65588. }
  65589. tempVec.x = 0;
  65590. tempVec.y = 0;
  65591. tempVec.z = 0;
  65592. if (jointPivot) {
  65593. tempVec.x = jointPivot.x;
  65594. tempVec.y = jointPivot.y;
  65595. tempVec.z = jointPivot.z;
  65596. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  65597. if (distToJoint === undefined || distToJoint === null) {
  65598. distToJoint = jointPivot.length();
  65599. }
  65600. tempVec.x *= distToJoint;
  65601. tempVec.y *= distToJoint;
  65602. tempVec.z *= distToJoint;
  65603. }
  65604. if (bone.getParent()) {
  65605. tempVec.addInPlace(mesh.getAbsolutePosition());
  65606. bone.setAbsolutePosition(tempVec, boneMesh);
  65607. }
  65608. else {
  65609. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  65610. boneMesh.position.x -= tempVec.x;
  65611. boneMesh.position.y -= tempVec.y;
  65612. boneMesh.position.z -= tempVec.z;
  65613. }
  65614. };
  65615. /**
  65616. * Sync impostor to a bone
  65617. * @param bone The bone that the impostor will be synced to.
  65618. * @param boneMesh The mesh that the bone is influencing.
  65619. * @param jointPivot The pivot of the joint / bone in local space.
  65620. * @param distToJoint Optional distance from the impostor to the joint.
  65621. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65622. * @param boneAxis Optional vector3 axis the bone is aligned with
  65623. */
  65624. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  65625. var mesh = this.object;
  65626. if (mesh.rotationQuaternion) {
  65627. if (adjustRotation) {
  65628. var tempQuat = PhysicsImpostor._tmpQuat;
  65629. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  65630. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  65631. }
  65632. else {
  65633. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  65634. }
  65635. }
  65636. var pos = PhysicsImpostor._tmpVecs[0];
  65637. var boneDir = PhysicsImpostor._tmpVecs[1];
  65638. if (!boneAxis) {
  65639. boneAxis = PhysicsImpostor._tmpVecs[2];
  65640. boneAxis.x = 0;
  65641. boneAxis.y = 1;
  65642. boneAxis.z = 0;
  65643. }
  65644. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  65645. bone.getAbsolutePositionToRef(boneMesh, pos);
  65646. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  65647. distToJoint = jointPivot.length();
  65648. }
  65649. if (distToJoint !== undefined && distToJoint !== null) {
  65650. pos.x += boneDir.x * distToJoint;
  65651. pos.y += boneDir.y * distToJoint;
  65652. pos.z += boneDir.z * distToJoint;
  65653. }
  65654. mesh.setAbsolutePosition(pos);
  65655. };
  65656. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  65657. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  65658. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65659. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  65660. //Impostor types
  65661. PhysicsImpostor.NoImpostor = 0;
  65662. PhysicsImpostor.SphereImpostor = 1;
  65663. PhysicsImpostor.BoxImpostor = 2;
  65664. PhysicsImpostor.PlaneImpostor = 3;
  65665. PhysicsImpostor.MeshImpostor = 4;
  65666. PhysicsImpostor.CylinderImpostor = 7;
  65667. PhysicsImpostor.ParticleImpostor = 8;
  65668. PhysicsImpostor.HeightmapImpostor = 9;
  65669. return PhysicsImpostor;
  65670. }());
  65671. BABYLON.PhysicsImpostor = PhysicsImpostor;
  65672. })(BABYLON || (BABYLON = {}));
  65673. //# sourceMappingURL=babylon.physicsImpostor.js.map
  65674. var BABYLON;
  65675. (function (BABYLON) {
  65676. var PhysicsEngine = /** @class */ (function () {
  65677. function PhysicsEngine(gravity, _physicsPlugin) {
  65678. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  65679. this._physicsPlugin = _physicsPlugin;
  65680. //new methods and parameters
  65681. this._impostors = [];
  65682. this._joints = [];
  65683. if (!this._physicsPlugin.isSupported()) {
  65684. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  65685. + "Please make sure it is included.");
  65686. }
  65687. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  65688. this.setGravity(gravity);
  65689. this.setTimeStep();
  65690. }
  65691. PhysicsEngine.prototype.setGravity = function (gravity) {
  65692. this.gravity = gravity;
  65693. this._physicsPlugin.setGravity(this.gravity);
  65694. };
  65695. /**
  65696. * Set the time step of the physics engine.
  65697. * default is 1/60.
  65698. * To slow it down, enter 1/600 for example.
  65699. * To speed it up, 1/30
  65700. * @param {number} newTimeStep the new timestep to apply to this world.
  65701. */
  65702. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  65703. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  65704. this._physicsPlugin.setTimeStep(newTimeStep);
  65705. };
  65706. /**
  65707. * Get the time step of the physics engine.
  65708. */
  65709. PhysicsEngine.prototype.getTimeStep = function () {
  65710. return this._physicsPlugin.getTimeStep();
  65711. };
  65712. PhysicsEngine.prototype.dispose = function () {
  65713. this._impostors.forEach(function (impostor) {
  65714. impostor.dispose();
  65715. });
  65716. this._physicsPlugin.dispose();
  65717. };
  65718. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  65719. return this._physicsPlugin.name;
  65720. };
  65721. /**
  65722. * Adding a new impostor for the impostor tracking.
  65723. * This will be done by the impostor itself.
  65724. * @param {PhysicsImpostor} impostor the impostor to add
  65725. */
  65726. PhysicsEngine.prototype.addImpostor = function (impostor) {
  65727. impostor.uniqueId = this._impostors.push(impostor);
  65728. //if no parent, generate the body
  65729. if (!impostor.parent) {
  65730. this._physicsPlugin.generatePhysicsBody(impostor);
  65731. }
  65732. };
  65733. /**
  65734. * Remove an impostor from the engine.
  65735. * This impostor and its mesh will not longer be updated by the physics engine.
  65736. * @param {PhysicsImpostor} impostor the impostor to remove
  65737. */
  65738. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  65739. var index = this._impostors.indexOf(impostor);
  65740. if (index > -1) {
  65741. var removed = this._impostors.splice(index, 1);
  65742. //Is it needed?
  65743. if (removed.length) {
  65744. //this will also remove it from the world.
  65745. removed[0].physicsBody = null;
  65746. }
  65747. }
  65748. };
  65749. /**
  65750. * Add a joint to the physics engine
  65751. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  65752. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  65753. * @param {PhysicsJoint} the joint that will connect both impostors.
  65754. */
  65755. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  65756. var impostorJoint = {
  65757. mainImpostor: mainImpostor,
  65758. connectedImpostor: connectedImpostor,
  65759. joint: joint
  65760. };
  65761. joint.physicsPlugin = this._physicsPlugin;
  65762. this._joints.push(impostorJoint);
  65763. this._physicsPlugin.generateJoint(impostorJoint);
  65764. };
  65765. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  65766. var matchingJoints = this._joints.filter(function (impostorJoint) {
  65767. return (impostorJoint.connectedImpostor === connectedImpostor
  65768. && impostorJoint.joint === joint
  65769. && impostorJoint.mainImpostor === mainImpostor);
  65770. });
  65771. if (matchingJoints.length) {
  65772. this._physicsPlugin.removeJoint(matchingJoints[0]);
  65773. //TODO remove it from the list as well
  65774. }
  65775. };
  65776. /**
  65777. * Called by the scene. no need to call it.
  65778. */
  65779. PhysicsEngine.prototype._step = function (delta) {
  65780. var _this = this;
  65781. //check if any mesh has no body / requires an update
  65782. this._impostors.forEach(function (impostor) {
  65783. if (impostor.isBodyInitRequired()) {
  65784. _this._physicsPlugin.generatePhysicsBody(impostor);
  65785. }
  65786. });
  65787. if (delta > 0.1) {
  65788. delta = 0.1;
  65789. }
  65790. else if (delta <= 0) {
  65791. delta = 1.0 / 60.0;
  65792. }
  65793. this._physicsPlugin.executeStep(delta, this._impostors);
  65794. };
  65795. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  65796. return this._physicsPlugin;
  65797. };
  65798. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  65799. for (var i = 0; i < this._impostors.length; ++i) {
  65800. if (this._impostors[i].object === object) {
  65801. return this._impostors[i];
  65802. }
  65803. }
  65804. return null;
  65805. };
  65806. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  65807. for (var i = 0; i < this._impostors.length; ++i) {
  65808. if (this._impostors[i].physicsBody === body) {
  65809. return this._impostors[i];
  65810. }
  65811. }
  65812. return null;
  65813. };
  65814. // Statics
  65815. PhysicsEngine.Epsilon = 0.001;
  65816. return PhysicsEngine;
  65817. }());
  65818. BABYLON.PhysicsEngine = PhysicsEngine;
  65819. })(BABYLON || (BABYLON = {}));
  65820. //# sourceMappingURL=babylon.physicsEngine.js.map
  65821. var BABYLON;
  65822. (function (BABYLON) {
  65823. var CannonJSPlugin = /** @class */ (function () {
  65824. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  65825. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  65826. if (iterations === void 0) { iterations = 10; }
  65827. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  65828. this.name = "CannonJSPlugin";
  65829. this._physicsMaterials = new Array();
  65830. this._fixedTimeStep = 1 / 60;
  65831. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  65832. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  65833. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  65834. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  65835. this._tmpPosition = BABYLON.Vector3.Zero();
  65836. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  65837. this._tmpUnityRotation = new BABYLON.Quaternion();
  65838. if (!this.isSupported()) {
  65839. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  65840. return;
  65841. }
  65842. this.world = new this.BJSCANNON.World();
  65843. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  65844. this.world.solver.iterations = iterations;
  65845. }
  65846. CannonJSPlugin.prototype.setGravity = function (gravity) {
  65847. this.world.gravity.copy(gravity);
  65848. };
  65849. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  65850. this._fixedTimeStep = timeStep;
  65851. };
  65852. CannonJSPlugin.prototype.getTimeStep = function () {
  65853. return this._fixedTimeStep;
  65854. };
  65855. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  65856. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  65857. };
  65858. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  65859. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65860. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65861. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  65862. };
  65863. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  65864. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65865. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65866. impostor.physicsBody.applyForce(impulse, worldPoint);
  65867. };
  65868. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  65869. //parent-child relationship. Does this impostor has a parent impostor?
  65870. if (impostor.parent) {
  65871. if (impostor.physicsBody) {
  65872. this.removePhysicsBody(impostor);
  65873. //TODO is that needed?
  65874. impostor.forceUpdate();
  65875. }
  65876. return;
  65877. }
  65878. //should a new body be created for this impostor?
  65879. if (impostor.isBodyInitRequired()) {
  65880. var shape = this._createShape(impostor);
  65881. //unregister events, if body is being changed
  65882. var oldBody = impostor.physicsBody;
  65883. if (oldBody) {
  65884. this.removePhysicsBody(impostor);
  65885. }
  65886. //create the body and material
  65887. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  65888. var bodyCreationObject = {
  65889. mass: impostor.getParam("mass"),
  65890. material: material
  65891. };
  65892. // A simple extend, in case native options were used.
  65893. var nativeOptions = impostor.getParam("nativeOptions");
  65894. for (var key in nativeOptions) {
  65895. if (nativeOptions.hasOwnProperty(key)) {
  65896. bodyCreationObject[key] = nativeOptions[key];
  65897. }
  65898. }
  65899. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  65900. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  65901. this.world.addEventListener("preStep", impostor.beforeStep);
  65902. this.world.addEventListener("postStep", impostor.afterStep);
  65903. impostor.physicsBody.addShape(shape);
  65904. this.world.add(impostor.physicsBody);
  65905. //try to keep the body moving in the right direction by taking old properties.
  65906. //Should be tested!
  65907. if (oldBody) {
  65908. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  65909. impostor.physicsBody[param].copy(oldBody[param]);
  65910. });
  65911. }
  65912. this._processChildMeshes(impostor);
  65913. }
  65914. //now update the body's transformation
  65915. this._updatePhysicsBodyTransformation(impostor);
  65916. };
  65917. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  65918. var _this = this;
  65919. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  65920. var currentRotation = mainImpostor.object.rotationQuaternion;
  65921. if (meshChildren.length) {
  65922. var processMesh = function (localPosition, mesh) {
  65923. if (!currentRotation || !mesh.rotationQuaternion) {
  65924. return;
  65925. }
  65926. var childImpostor = mesh.getPhysicsImpostor();
  65927. if (childImpostor) {
  65928. var parent = childImpostor.parent;
  65929. if (parent !== mainImpostor) {
  65930. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  65931. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  65932. if (childImpostor.physicsBody) {
  65933. _this.removePhysicsBody(childImpostor);
  65934. childImpostor.physicsBody = null;
  65935. }
  65936. childImpostor.parent = mainImpostor;
  65937. childImpostor.resetUpdateFlags();
  65938. 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));
  65939. //Add the mass of the children.
  65940. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  65941. }
  65942. }
  65943. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  65944. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  65945. };
  65946. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  65947. }
  65948. };
  65949. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  65950. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  65951. this.world.removeEventListener("preStep", impostor.beforeStep);
  65952. this.world.removeEventListener("postStep", impostor.afterStep);
  65953. this.world.remove(impostor.physicsBody);
  65954. };
  65955. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  65956. var mainBody = impostorJoint.mainImpostor.physicsBody;
  65957. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  65958. if (!mainBody || !connectedBody) {
  65959. return;
  65960. }
  65961. var constraint;
  65962. var jointData = impostorJoint.joint.jointData;
  65963. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  65964. var constraintData = {
  65965. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  65966. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  65967. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  65968. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  65969. maxForce: jointData.nativeParams.maxForce,
  65970. collideConnected: !!jointData.collision
  65971. };
  65972. switch (impostorJoint.joint.type) {
  65973. case BABYLON.PhysicsJoint.HingeJoint:
  65974. case BABYLON.PhysicsJoint.Hinge2Joint:
  65975. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  65976. break;
  65977. case BABYLON.PhysicsJoint.DistanceJoint:
  65978. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  65979. break;
  65980. case BABYLON.PhysicsJoint.SpringJoint:
  65981. var springData = jointData;
  65982. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  65983. restLength: springData.length,
  65984. stiffness: springData.stiffness,
  65985. damping: springData.damping,
  65986. localAnchorA: constraintData.pivotA,
  65987. localAnchorB: constraintData.pivotB
  65988. });
  65989. break;
  65990. case BABYLON.PhysicsJoint.LockJoint:
  65991. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  65992. break;
  65993. case BABYLON.PhysicsJoint.PointToPointJoint:
  65994. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  65995. default:
  65996. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  65997. break;
  65998. }
  65999. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  66000. constraint.collideConnected = !!jointData.collision;
  66001. impostorJoint.joint.physicsJoint = constraint;
  66002. //don't add spring as constraint, as it is not one.
  66003. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  66004. this.world.addConstraint(constraint);
  66005. }
  66006. else {
  66007. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  66008. constraint.applyForce();
  66009. });
  66010. }
  66011. };
  66012. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66013. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  66014. };
  66015. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  66016. var index;
  66017. var mat;
  66018. for (index = 0; index < this._physicsMaterials.length; index++) {
  66019. mat = this._physicsMaterials[index];
  66020. if (mat.friction === friction && mat.restitution === restitution) {
  66021. return mat;
  66022. }
  66023. }
  66024. var currentMat = new this.BJSCANNON.Material(name);
  66025. currentMat.friction = friction;
  66026. currentMat.restitution = restitution;
  66027. this._physicsMaterials.push(currentMat);
  66028. return currentMat;
  66029. };
  66030. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  66031. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  66032. };
  66033. CannonJSPlugin.prototype._createShape = function (impostor) {
  66034. var object = impostor.object;
  66035. var returnValue;
  66036. var extendSize = impostor.getObjectExtendSize();
  66037. switch (impostor.type) {
  66038. case BABYLON.PhysicsImpostor.SphereImpostor:
  66039. var radiusX = extendSize.x;
  66040. var radiusY = extendSize.y;
  66041. var radiusZ = extendSize.z;
  66042. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  66043. break;
  66044. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  66045. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66046. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  66047. break;
  66048. case BABYLON.PhysicsImpostor.BoxImpostor:
  66049. var box = extendSize.scale(0.5);
  66050. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  66051. break;
  66052. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66053. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  66054. returnValue = new this.BJSCANNON.Plane();
  66055. break;
  66056. case BABYLON.PhysicsImpostor.MeshImpostor:
  66057. // should transform the vertex data to world coordinates!!
  66058. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  66059. var rawFaces = object.getIndices ? object.getIndices() : [];
  66060. if (!rawVerts)
  66061. return;
  66062. // get only scale! so the object could transform correctly.
  66063. var oldPosition = object.position.clone();
  66064. var oldRotation = object.rotation && object.rotation.clone();
  66065. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  66066. object.position.copyFromFloats(0, 0, 0);
  66067. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66068. object.rotationQuaternion && object.rotationQuaternion.copyFromFloats(0, 0, 0, 1);
  66069. var transform = object.computeWorldMatrix(true);
  66070. // convert rawVerts to object space
  66071. var temp = new Array();
  66072. var index;
  66073. for (index = 0; index < rawVerts.length; index += 3) {
  66074. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  66075. }
  66076. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  66077. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  66078. //now set back the transformation!
  66079. object.position.copyFrom(oldPosition);
  66080. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  66081. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  66082. break;
  66083. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  66084. returnValue = this._createHeightmap(object);
  66085. break;
  66086. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66087. returnValue = new this.BJSCANNON.Particle();
  66088. break;
  66089. }
  66090. return returnValue;
  66091. };
  66092. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  66093. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  66094. var matrix = new Array();
  66095. //For now pointDepth will not be used and will be automatically calculated.
  66096. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  66097. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  66098. var boundingInfo = (object.getBoundingInfo());
  66099. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.z);
  66100. var minY = boundingInfo.boundingBox.extendSizeWorld.y;
  66101. var elementSize = dim * 2 / arraySize;
  66102. for (var i = 0; i < pos.length; i = i + 3) {
  66103. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  66104. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  66105. var y = pos[i + 1] + minY;
  66106. if (!matrix[x]) {
  66107. matrix[x] = [];
  66108. }
  66109. if (!matrix[x][z]) {
  66110. matrix[x][z] = y;
  66111. }
  66112. matrix[x][z] = Math.max(y, matrix[x][z]);
  66113. }
  66114. for (var x = 0; x <= arraySize; ++x) {
  66115. if (!matrix[x]) {
  66116. var loc = 1;
  66117. while (!matrix[(x + loc) % arraySize]) {
  66118. loc++;
  66119. }
  66120. matrix[x] = matrix[(x + loc) % arraySize].slice();
  66121. //console.log("missing x", x);
  66122. }
  66123. for (var z = 0; z <= arraySize; ++z) {
  66124. if (!matrix[x][z]) {
  66125. var loc = 1;
  66126. var newValue;
  66127. while (newValue === undefined) {
  66128. newValue = matrix[x][(z + loc++) % arraySize];
  66129. }
  66130. matrix[x][z] = newValue;
  66131. }
  66132. }
  66133. }
  66134. var shape = new this.BJSCANNON.Heightfield(matrix, {
  66135. elementSize: elementSize
  66136. });
  66137. //For future reference, needed for body transformation
  66138. shape.minY = minY;
  66139. return shape;
  66140. };
  66141. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  66142. var object = impostor.object;
  66143. //make sure it is updated...
  66144. object.computeWorldMatrix && object.computeWorldMatrix(true);
  66145. // The delta between the mesh position and the mesh bounding box center
  66146. var bInfo = object.getBoundingInfo();
  66147. if (!bInfo)
  66148. return;
  66149. var center = impostor.getObjectCenter();
  66150. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  66151. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  66152. this._tmpPosition.copyFrom(center);
  66153. var quaternion = object.rotationQuaternion;
  66154. if (!quaternion) {
  66155. return;
  66156. }
  66157. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  66158. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  66159. //-90 DEG in X, precalculated
  66160. quaternion = quaternion.multiply(this._minus90X);
  66161. //Invert! (Precalculated, 90 deg in X)
  66162. //No need to clone. this will never change.
  66163. impostor.setDeltaRotation(this._plus90X);
  66164. }
  66165. //If it is a heightfield, if should be centered.
  66166. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  66167. var mesh = object;
  66168. var boundingInfo = mesh.getBoundingInfo();
  66169. //calculate the correct body position:
  66170. var rotationQuaternion = mesh.rotationQuaternion;
  66171. mesh.rotationQuaternion = this._tmpUnityRotation;
  66172. mesh.computeWorldMatrix(true);
  66173. //get original center with no rotation
  66174. var c = center.clone();
  66175. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  66176. //rotation is back
  66177. mesh.rotationQuaternion = rotationQuaternion;
  66178. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  66179. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  66180. mesh.setPivotMatrix(p);
  66181. mesh.computeWorldMatrix(true);
  66182. //calculate the translation
  66183. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  66184. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  66185. //add it inverted to the delta
  66186. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66187. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66188. mesh.setPivotMatrix(oldPivot);
  66189. mesh.computeWorldMatrix(true);
  66190. }
  66191. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66192. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66193. //this._tmpPosition.copyFrom(object.position);
  66194. }
  66195. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66196. //Now update the impostor object
  66197. impostor.physicsBody.position.copy(this._tmpPosition);
  66198. impostor.physicsBody.quaternion.copy(quaternion);
  66199. };
  66200. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66201. impostor.object.position.copyFrom(impostor.physicsBody.position);
  66202. if (impostor.object.rotationQuaternion) {
  66203. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  66204. //impostor.object.rotationQuaternion.y *= -1;
  66205. //impostor.object.rotationQuaternion.z *= -1;
  66206. }
  66207. };
  66208. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66209. impostor.physicsBody.position.copy(newPosition);
  66210. //newRotation.y *= -1;
  66211. //newRotation.z *= -1;
  66212. impostor.physicsBody.quaternion.copy(newRotation);
  66213. };
  66214. CannonJSPlugin.prototype.isSupported = function () {
  66215. return this.BJSCANNON !== undefined;
  66216. };
  66217. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66218. impostor.physicsBody.velocity.copy(velocity);
  66219. };
  66220. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66221. impostor.physicsBody.angularVelocity.copy(velocity);
  66222. };
  66223. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66224. var v = impostor.physicsBody.velocity;
  66225. if (!v) {
  66226. return null;
  66227. }
  66228. return new BABYLON.Vector3(v.x, v.y, v.z);
  66229. };
  66230. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66231. var v = impostor.physicsBody.angularVelocity;
  66232. if (!v) {
  66233. return null;
  66234. }
  66235. return new BABYLON.Vector3(v.x, v.y, v.z);
  66236. };
  66237. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66238. impostor.physicsBody.mass = mass;
  66239. impostor.physicsBody.updateMassProperties();
  66240. };
  66241. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  66242. return impostor.physicsBody.mass;
  66243. };
  66244. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  66245. return impostor.physicsBody.material.friction;
  66246. };
  66247. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66248. impostor.physicsBody.material.friction = friction;
  66249. };
  66250. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66251. return impostor.physicsBody.material.restitution;
  66252. };
  66253. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66254. impostor.physicsBody.material.restitution = restitution;
  66255. };
  66256. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  66257. impostor.physicsBody.sleep();
  66258. };
  66259. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  66260. impostor.physicsBody.wakeUp();
  66261. };
  66262. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66263. joint.physicsJoint.distance = maxDistance;
  66264. };
  66265. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66266. // if (!motorIndex) {
  66267. // joint.physicsJoint.enableMotor();
  66268. // }
  66269. // }
  66270. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66271. // if (!motorIndex) {
  66272. // joint.physicsJoint.disableMotor();
  66273. // }
  66274. // }
  66275. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66276. if (!motorIndex) {
  66277. joint.physicsJoint.enableMotor();
  66278. joint.physicsJoint.setMotorSpeed(speed);
  66279. if (maxForce) {
  66280. this.setLimit(joint, maxForce);
  66281. }
  66282. }
  66283. };
  66284. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  66285. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  66286. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  66287. };
  66288. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66289. var body = impostor.physicsBody;
  66290. mesh.position.x = body.position.x;
  66291. mesh.position.y = body.position.y;
  66292. mesh.position.z = body.position.z;
  66293. if (mesh.rotationQuaternion) {
  66294. mesh.rotationQuaternion.x = body.quaternion.x;
  66295. mesh.rotationQuaternion.y = body.quaternion.y;
  66296. mesh.rotationQuaternion.z = body.quaternion.z;
  66297. mesh.rotationQuaternion.w = body.quaternion.w;
  66298. }
  66299. };
  66300. CannonJSPlugin.prototype.getRadius = function (impostor) {
  66301. var shape = impostor.physicsBody.shapes[0];
  66302. return shape.boundingSphereRadius;
  66303. };
  66304. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66305. var shape = impostor.physicsBody.shapes[0];
  66306. result.x = shape.halfExtents.x * 2;
  66307. result.y = shape.halfExtents.y * 2;
  66308. result.z = shape.halfExtents.z * 2;
  66309. };
  66310. CannonJSPlugin.prototype.dispose = function () {
  66311. };
  66312. return CannonJSPlugin;
  66313. }());
  66314. BABYLON.CannonJSPlugin = CannonJSPlugin;
  66315. })(BABYLON || (BABYLON = {}));
  66316. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  66317. var BABYLON;
  66318. (function (BABYLON) {
  66319. var OimoJSPlugin = /** @class */ (function () {
  66320. function OimoJSPlugin(iterations) {
  66321. this.name = "OimoJSPlugin";
  66322. this._tmpImpostorsArray = [];
  66323. this._tmpPositionVector = BABYLON.Vector3.Zero();
  66324. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  66325. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  66326. this.world.worldscale(1);
  66327. this.world.clear();
  66328. //making sure no stats are calculated
  66329. this.world.isNoStat = true;
  66330. }
  66331. OimoJSPlugin.prototype.setGravity = function (gravity) {
  66332. this.world.gravity.copy(gravity);
  66333. };
  66334. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  66335. this.world.timeStep = timeStep;
  66336. };
  66337. OimoJSPlugin.prototype.getTimeStep = function () {
  66338. return this.world.timeStep;
  66339. };
  66340. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  66341. var _this = this;
  66342. impostors.forEach(function (impostor) {
  66343. impostor.beforeStep();
  66344. });
  66345. this.world.step();
  66346. impostors.forEach(function (impostor) {
  66347. impostor.afterStep();
  66348. //update the ordered impostors array
  66349. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  66350. });
  66351. //check for collisions
  66352. var contact = this.world.contacts;
  66353. while (contact !== null) {
  66354. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  66355. contact = contact.next;
  66356. continue;
  66357. }
  66358. //is this body colliding with any other? get the impostor
  66359. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  66360. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  66361. if (!mainImpostor || !collidingImpostor) {
  66362. contact = contact.next;
  66363. continue;
  66364. }
  66365. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  66366. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  66367. contact = contact.next;
  66368. }
  66369. };
  66370. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66371. var mass = impostor.physicsBody.massInfo.mass;
  66372. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  66373. };
  66374. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66375. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  66376. this.applyImpulse(impostor, force, contactPoint);
  66377. };
  66378. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66379. var _this = this;
  66380. //parent-child relationship. Does this impostor has a parent impostor?
  66381. if (impostor.parent) {
  66382. if (impostor.physicsBody) {
  66383. this.removePhysicsBody(impostor);
  66384. //TODO is that needed?
  66385. impostor.forceUpdate();
  66386. }
  66387. return;
  66388. }
  66389. if (impostor.isBodyInitRequired()) {
  66390. var bodyConfig = {
  66391. name: impostor.uniqueId,
  66392. //Oimo must have mass, also for static objects.
  66393. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  66394. size: [],
  66395. type: [],
  66396. pos: [],
  66397. rot: [],
  66398. move: impostor.getParam("mass") !== 0,
  66399. //Supporting older versions of Oimo
  66400. world: this.world
  66401. };
  66402. var impostors = [impostor];
  66403. var addToArray = function (parent) {
  66404. if (!parent.getChildMeshes)
  66405. return;
  66406. parent.getChildMeshes().forEach(function (m) {
  66407. if (m.physicsImpostor) {
  66408. impostors.push(m.physicsImpostor);
  66409. //m.physicsImpostor._init();
  66410. }
  66411. });
  66412. };
  66413. addToArray(impostor.object);
  66414. var checkWithEpsilon_1 = function (value) {
  66415. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  66416. };
  66417. impostors.forEach(function (i) {
  66418. if (!impostor.object.rotationQuaternion) {
  66419. return;
  66420. }
  66421. //get the correct bounding box
  66422. var oldQuaternion = i.object.rotationQuaternion;
  66423. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  66424. x: impostor.object.rotationQuaternion.x,
  66425. y: impostor.object.rotationQuaternion.y,
  66426. z: impostor.object.rotationQuaternion.z,
  66427. s: impostor.object.rotationQuaternion.w
  66428. });
  66429. var extendSize = i.getObjectExtendSize();
  66430. if (i === impostor) {
  66431. var center = impostor.getObjectCenter();
  66432. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  66433. //Can also use Array.prototype.push.apply
  66434. bodyConfig.pos.push(center.x);
  66435. bodyConfig.pos.push(center.y);
  66436. bodyConfig.pos.push(center.z);
  66437. //tmp solution
  66438. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66439. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66440. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66441. }
  66442. else {
  66443. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  66444. bodyConfig.pos.push(localPosition.x);
  66445. bodyConfig.pos.push(localPosition.y);
  66446. bodyConfig.pos.push(localPosition.z);
  66447. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  66448. bodyConfig.rot.push(0);
  66449. bodyConfig.rot.push(0);
  66450. bodyConfig.rot.push(0);
  66451. }
  66452. // register mesh
  66453. switch (i.type) {
  66454. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66455. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  66456. case BABYLON.PhysicsImpostor.SphereImpostor:
  66457. var radiusX = extendSize.x;
  66458. var radiusY = extendSize.y;
  66459. var radiusZ = extendSize.z;
  66460. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  66461. bodyConfig.type.push('sphere');
  66462. //due to the way oimo works with compounds, add 3 times
  66463. bodyConfig.size.push(size);
  66464. bodyConfig.size.push(size);
  66465. bodyConfig.size.push(size);
  66466. break;
  66467. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66468. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  66469. var sizeY = checkWithEpsilon_1(extendSize.y);
  66470. bodyConfig.type.push('cylinder');
  66471. bodyConfig.size.push(sizeX);
  66472. bodyConfig.size.push(sizeY);
  66473. //due to the way oimo works with compounds, add one more value.
  66474. bodyConfig.size.push(sizeY);
  66475. break;
  66476. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66477. case BABYLON.PhysicsImpostor.BoxImpostor:
  66478. default:
  66479. var sizeX = checkWithEpsilon_1(extendSize.x);
  66480. var sizeY = checkWithEpsilon_1(extendSize.y);
  66481. var sizeZ = checkWithEpsilon_1(extendSize.z);
  66482. bodyConfig.type.push('box');
  66483. bodyConfig.size.push(sizeX);
  66484. bodyConfig.size.push(sizeY);
  66485. bodyConfig.size.push(sizeZ);
  66486. break;
  66487. }
  66488. //actually not needed, but hey...
  66489. i.object.rotationQuaternion = oldQuaternion;
  66490. });
  66491. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  66492. }
  66493. else {
  66494. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  66495. }
  66496. impostor.setDeltaPosition(this._tmpPositionVector);
  66497. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  66498. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  66499. };
  66500. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66501. //impostor.physicsBody.dispose();
  66502. //Same as : (older oimo versions)
  66503. this.world.removeRigidBody(impostor.physicsBody);
  66504. };
  66505. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66506. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66507. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66508. if (!mainBody || !connectedBody) {
  66509. return;
  66510. }
  66511. var jointData = impostorJoint.joint.jointData;
  66512. var options = jointData.nativeParams || {};
  66513. var type;
  66514. var nativeJointData = {
  66515. body1: mainBody,
  66516. body2: connectedBody,
  66517. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  66518. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  66519. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  66520. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  66521. min: options.min,
  66522. max: options.max,
  66523. collision: options.collision || jointData.collision,
  66524. spring: options.spring,
  66525. //supporting older version of Oimo
  66526. world: this.world
  66527. };
  66528. switch (impostorJoint.joint.type) {
  66529. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66530. type = "jointBall";
  66531. break;
  66532. case BABYLON.PhysicsJoint.SpringJoint:
  66533. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  66534. var springData = jointData;
  66535. nativeJointData.min = springData.length || nativeJointData.min;
  66536. //Max should also be set, just make sure it is at least min
  66537. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  66538. case BABYLON.PhysicsJoint.DistanceJoint:
  66539. type = "jointDistance";
  66540. nativeJointData.max = jointData.maxDistance;
  66541. break;
  66542. case BABYLON.PhysicsJoint.PrismaticJoint:
  66543. type = "jointPrisme";
  66544. break;
  66545. case BABYLON.PhysicsJoint.SliderJoint:
  66546. type = "jointSlide";
  66547. break;
  66548. case BABYLON.PhysicsJoint.WheelJoint:
  66549. type = "jointWheel";
  66550. break;
  66551. case BABYLON.PhysicsJoint.HingeJoint:
  66552. default:
  66553. type = "jointHinge";
  66554. break;
  66555. }
  66556. nativeJointData.type = type;
  66557. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  66558. };
  66559. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66560. //Bug in Oimo prevents us from disposing a joint in the playground
  66561. //joint.joint.physicsJoint.dispose();
  66562. //So we will bruteforce it!
  66563. try {
  66564. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  66565. }
  66566. catch (e) {
  66567. BABYLON.Tools.Warn(e);
  66568. }
  66569. };
  66570. OimoJSPlugin.prototype.isSupported = function () {
  66571. return this.BJSOIMO !== undefined;
  66572. };
  66573. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66574. if (!impostor.physicsBody.sleeping) {
  66575. //TODO check that
  66576. if (impostor.physicsBody.shapes.next) {
  66577. var parentShape = this._getLastShape(impostor.physicsBody);
  66578. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  66579. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  66580. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  66581. }
  66582. else {
  66583. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  66584. }
  66585. if (impostor.object.rotationQuaternion) {
  66586. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  66587. impostor.object.rotationQuaternion.normalize();
  66588. }
  66589. }
  66590. };
  66591. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66592. var body = impostor.physicsBody;
  66593. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  66594. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  66595. body.syncShapes();
  66596. body.awake();
  66597. };
  66598. OimoJSPlugin.prototype._getLastShape = function (body) {
  66599. var lastShape = body.shapes;
  66600. while (lastShape.next) {
  66601. lastShape = lastShape.next;
  66602. }
  66603. return lastShape;
  66604. };
  66605. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66606. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  66607. };
  66608. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66609. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  66610. };
  66611. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66612. var v = impostor.physicsBody.linearVelocity;
  66613. if (!v) {
  66614. return null;
  66615. }
  66616. return new BABYLON.Vector3(v.x, v.y, v.z);
  66617. };
  66618. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66619. var v = impostor.physicsBody.angularVelocity;
  66620. if (!v) {
  66621. return null;
  66622. }
  66623. return new BABYLON.Vector3(v.x, v.y, v.z);
  66624. };
  66625. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66626. var staticBody = mass === 0;
  66627. //this will actually set the body's density and not its mass.
  66628. //But this is how oimo treats the mass variable.
  66629. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  66630. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  66631. };
  66632. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  66633. return impostor.physicsBody.shapes.density;
  66634. };
  66635. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  66636. return impostor.physicsBody.shapes.friction;
  66637. };
  66638. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66639. impostor.physicsBody.shapes.friction = friction;
  66640. };
  66641. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66642. return impostor.physicsBody.shapes.restitution;
  66643. };
  66644. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66645. impostor.physicsBody.shapes.restitution = restitution;
  66646. };
  66647. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  66648. impostor.physicsBody.sleep();
  66649. };
  66650. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  66651. impostor.physicsBody.awake();
  66652. };
  66653. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66654. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  66655. if (minDistance !== void 0) {
  66656. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  66657. }
  66658. };
  66659. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66660. //TODO separate rotational and transational motors.
  66661. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66662. if (motor) {
  66663. motor.setMotor(speed, maxForce);
  66664. }
  66665. };
  66666. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  66667. //TODO separate rotational and transational motors.
  66668. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66669. if (motor) {
  66670. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  66671. }
  66672. };
  66673. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66674. var body = impostor.physicsBody;
  66675. mesh.position.x = body.position.x;
  66676. mesh.position.y = body.position.y;
  66677. mesh.position.z = body.position.z;
  66678. if (mesh.rotationQuaternion) {
  66679. mesh.rotationQuaternion.x = body.orientation.x;
  66680. mesh.rotationQuaternion.y = body.orientation.y;
  66681. mesh.rotationQuaternion.z = body.orientation.z;
  66682. mesh.rotationQuaternion.w = body.orientation.s;
  66683. }
  66684. };
  66685. OimoJSPlugin.prototype.getRadius = function (impostor) {
  66686. return impostor.physicsBody.shapes.radius;
  66687. };
  66688. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66689. var shape = impostor.physicsBody.shapes;
  66690. result.x = shape.halfWidth * 2;
  66691. result.y = shape.halfHeight * 2;
  66692. result.z = shape.halfDepth * 2;
  66693. };
  66694. OimoJSPlugin.prototype.dispose = function () {
  66695. this.world.clear();
  66696. };
  66697. return OimoJSPlugin;
  66698. }());
  66699. BABYLON.OimoJSPlugin = OimoJSPlugin;
  66700. })(BABYLON || (BABYLON = {}));
  66701. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  66702. var BABYLON;
  66703. (function (BABYLON) {
  66704. var Internals;
  66705. (function (Internals) {
  66706. /*
  66707. * Based on jsTGALoader - Javascript loader for TGA file
  66708. * By Vincent Thibault
  66709. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  66710. */
  66711. var TGATools = /** @class */ (function () {
  66712. function TGATools() {
  66713. }
  66714. TGATools.GetTGAHeader = function (data) {
  66715. var offset = 0;
  66716. var header = {
  66717. id_length: data[offset++],
  66718. colormap_type: data[offset++],
  66719. image_type: data[offset++],
  66720. colormap_index: data[offset++] | data[offset++] << 8,
  66721. colormap_length: data[offset++] | data[offset++] << 8,
  66722. colormap_size: data[offset++],
  66723. origin: [
  66724. data[offset++] | data[offset++] << 8,
  66725. data[offset++] | data[offset++] << 8
  66726. ],
  66727. width: data[offset++] | data[offset++] << 8,
  66728. height: data[offset++] | data[offset++] << 8,
  66729. pixel_size: data[offset++],
  66730. flags: data[offset++]
  66731. };
  66732. return header;
  66733. };
  66734. TGATools.UploadContent = function (gl, data) {
  66735. // Not enough data to contain header ?
  66736. if (data.length < 19) {
  66737. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  66738. return;
  66739. }
  66740. // Read Header
  66741. var offset = 18;
  66742. var header = TGATools.GetTGAHeader(data);
  66743. // Assume it's a valid Targa file.
  66744. if (header.id_length + offset > data.length) {
  66745. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  66746. return;
  66747. }
  66748. // Skip not needed data
  66749. offset += header.id_length;
  66750. var use_rle = false;
  66751. var use_pal = false;
  66752. var use_rgb = false;
  66753. var use_grey = false;
  66754. // Get some informations.
  66755. switch (header.image_type) {
  66756. case TGATools._TYPE_RLE_INDEXED:
  66757. use_rle = true;
  66758. case TGATools._TYPE_INDEXED:
  66759. use_pal = true;
  66760. break;
  66761. case TGATools._TYPE_RLE_RGB:
  66762. use_rle = true;
  66763. case TGATools._TYPE_RGB:
  66764. use_rgb = true;
  66765. break;
  66766. case TGATools._TYPE_RLE_GREY:
  66767. use_rle = true;
  66768. case TGATools._TYPE_GREY:
  66769. use_grey = true;
  66770. break;
  66771. }
  66772. var pixel_data;
  66773. // var numAlphaBits = header.flags & 0xf;
  66774. var pixel_size = header.pixel_size >> 3;
  66775. var pixel_total = header.width * header.height * pixel_size;
  66776. // Read palettes
  66777. var palettes;
  66778. if (use_pal) {
  66779. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  66780. }
  66781. // Read LRE
  66782. if (use_rle) {
  66783. pixel_data = new Uint8Array(pixel_total);
  66784. var c, count, i;
  66785. var localOffset = 0;
  66786. var pixels = new Uint8Array(pixel_size);
  66787. while (offset < pixel_total && localOffset < pixel_total) {
  66788. c = data[offset++];
  66789. count = (c & 0x7f) + 1;
  66790. // RLE pixels
  66791. if (c & 0x80) {
  66792. // Bind pixel tmp array
  66793. for (i = 0; i < pixel_size; ++i) {
  66794. pixels[i] = data[offset++];
  66795. }
  66796. // Copy pixel array
  66797. for (i = 0; i < count; ++i) {
  66798. pixel_data.set(pixels, localOffset + i * pixel_size);
  66799. }
  66800. localOffset += pixel_size * count;
  66801. }
  66802. else {
  66803. count *= pixel_size;
  66804. for (i = 0; i < count; ++i) {
  66805. pixel_data[localOffset + i] = data[offset++];
  66806. }
  66807. localOffset += count;
  66808. }
  66809. }
  66810. }
  66811. else {
  66812. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  66813. }
  66814. // Load to texture
  66815. var x_start, y_start, x_step, y_step, y_end, x_end;
  66816. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  66817. default:
  66818. case TGATools._ORIGIN_UL:
  66819. x_start = 0;
  66820. x_step = 1;
  66821. x_end = header.width;
  66822. y_start = 0;
  66823. y_step = 1;
  66824. y_end = header.height;
  66825. break;
  66826. case TGATools._ORIGIN_BL:
  66827. x_start = 0;
  66828. x_step = 1;
  66829. x_end = header.width;
  66830. y_start = header.height - 1;
  66831. y_step = -1;
  66832. y_end = -1;
  66833. break;
  66834. case TGATools._ORIGIN_UR:
  66835. x_start = header.width - 1;
  66836. x_step = -1;
  66837. x_end = -1;
  66838. y_start = 0;
  66839. y_step = 1;
  66840. y_end = header.height;
  66841. break;
  66842. case TGATools._ORIGIN_BR:
  66843. x_start = header.width - 1;
  66844. x_step = -1;
  66845. x_end = -1;
  66846. y_start = header.height - 1;
  66847. y_step = -1;
  66848. y_end = -1;
  66849. break;
  66850. }
  66851. // Load the specify method
  66852. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  66853. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  66854. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  66855. };
  66856. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66857. var image = pixel_data, colormap = palettes;
  66858. var width = header.width, height = header.height;
  66859. var color, i = 0, x, y;
  66860. var imageData = new Uint8Array(width * height * 4);
  66861. for (y = y_start; y !== y_end; y += y_step) {
  66862. for (x = x_start; x !== x_end; x += x_step, i++) {
  66863. color = image[i];
  66864. imageData[(x + width * y) * 4 + 3] = 255;
  66865. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  66866. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  66867. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  66868. }
  66869. }
  66870. return imageData;
  66871. };
  66872. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66873. var image = pixel_data;
  66874. var width = header.width, height = header.height;
  66875. var color, i = 0, x, y;
  66876. var imageData = new Uint8Array(width * height * 4);
  66877. for (y = y_start; y !== y_end; y += y_step) {
  66878. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66879. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  66880. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  66881. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  66882. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  66883. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  66884. }
  66885. }
  66886. return imageData;
  66887. };
  66888. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66889. var image = pixel_data;
  66890. var width = header.width, height = header.height;
  66891. var i = 0, x, y;
  66892. var imageData = new Uint8Array(width * height * 4);
  66893. for (y = y_start; y !== y_end; y += y_step) {
  66894. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  66895. imageData[(x + width * y) * 4 + 3] = 255;
  66896. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66897. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66898. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66899. }
  66900. }
  66901. return imageData;
  66902. };
  66903. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66904. var image = pixel_data;
  66905. var width = header.width, height = header.height;
  66906. var i = 0, x, y;
  66907. var imageData = new Uint8Array(width * height * 4);
  66908. for (y = y_start; y !== y_end; y += y_step) {
  66909. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  66910. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66911. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66912. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66913. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  66914. }
  66915. }
  66916. return imageData;
  66917. };
  66918. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66919. var image = pixel_data;
  66920. var width = header.width, height = header.height;
  66921. var color, i = 0, x, y;
  66922. var imageData = new Uint8Array(width * height * 4);
  66923. for (y = y_start; y !== y_end; y += y_step) {
  66924. for (x = x_start; x !== x_end; x += x_step, i++) {
  66925. color = image[i];
  66926. imageData[(x + width * y) * 4 + 0] = color;
  66927. imageData[(x + width * y) * 4 + 1] = color;
  66928. imageData[(x + width * y) * 4 + 2] = color;
  66929. imageData[(x + width * y) * 4 + 3] = 255;
  66930. }
  66931. }
  66932. return imageData;
  66933. };
  66934. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66935. var image = pixel_data;
  66936. var width = header.width, height = header.height;
  66937. var i = 0, x, y;
  66938. var imageData = new Uint8Array(width * height * 4);
  66939. for (y = y_start; y !== y_end; y += y_step) {
  66940. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66941. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  66942. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  66943. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66944. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  66945. }
  66946. }
  66947. return imageData;
  66948. };
  66949. //private static _TYPE_NO_DATA = 0;
  66950. TGATools._TYPE_INDEXED = 1;
  66951. TGATools._TYPE_RGB = 2;
  66952. TGATools._TYPE_GREY = 3;
  66953. TGATools._TYPE_RLE_INDEXED = 9;
  66954. TGATools._TYPE_RLE_RGB = 10;
  66955. TGATools._TYPE_RLE_GREY = 11;
  66956. TGATools._ORIGIN_MASK = 0x30;
  66957. TGATools._ORIGIN_SHIFT = 0x04;
  66958. TGATools._ORIGIN_BL = 0x00;
  66959. TGATools._ORIGIN_BR = 0x01;
  66960. TGATools._ORIGIN_UL = 0x02;
  66961. TGATools._ORIGIN_UR = 0x03;
  66962. return TGATools;
  66963. }());
  66964. Internals.TGATools = TGATools;
  66965. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66966. })(BABYLON || (BABYLON = {}));
  66967. //# sourceMappingURL=babylon.tga.js.map
  66968. var BABYLON;
  66969. (function (BABYLON) {
  66970. var Internals;
  66971. (function (Internals) {
  66972. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  66973. // All values and structures referenced from:
  66974. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  66975. var DDS_MAGIC = 0x20534444;
  66976. var
  66977. //DDSD_CAPS = 0x1,
  66978. //DDSD_HEIGHT = 0x2,
  66979. //DDSD_WIDTH = 0x4,
  66980. //DDSD_PITCH = 0x8,
  66981. //DDSD_PIXELFORMAT = 0x1000,
  66982. DDSD_MIPMAPCOUNT = 0x20000;
  66983. //DDSD_LINEARSIZE = 0x80000,
  66984. //DDSD_DEPTH = 0x800000;
  66985. // var DDSCAPS_COMPLEX = 0x8,
  66986. // DDSCAPS_MIPMAP = 0x400000,
  66987. // DDSCAPS_TEXTURE = 0x1000;
  66988. var DDSCAPS2_CUBEMAP = 0x200;
  66989. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  66990. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  66991. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  66992. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  66993. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  66994. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  66995. // DDSCAPS2_VOLUME = 0x200000;
  66996. var
  66997. //DDPF_ALPHAPIXELS = 0x1,
  66998. //DDPF_ALPHA = 0x2,
  66999. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  67000. //DDPF_YUV = 0x200,
  67001. DDPF_LUMINANCE = 0x20000;
  67002. function FourCCToInt32(value) {
  67003. return value.charCodeAt(0) +
  67004. (value.charCodeAt(1) << 8) +
  67005. (value.charCodeAt(2) << 16) +
  67006. (value.charCodeAt(3) << 24);
  67007. }
  67008. function Int32ToFourCC(value) {
  67009. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  67010. }
  67011. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  67012. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  67013. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  67014. var FOURCC_DX10 = FourCCToInt32("DX10");
  67015. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  67016. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  67017. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  67018. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  67019. var headerLengthInt = 31; // The header length in 32 bit ints
  67020. // Offsets into the header array
  67021. var off_magic = 0;
  67022. var off_size = 1;
  67023. var off_flags = 2;
  67024. var off_height = 3;
  67025. var off_width = 4;
  67026. var off_mipmapCount = 7;
  67027. var off_pfFlags = 20;
  67028. var off_pfFourCC = 21;
  67029. var off_RGBbpp = 22;
  67030. // var off_RMask = 23;
  67031. // var off_GMask = 24;
  67032. // var off_BMask = 25;
  67033. // var off_AMask = 26;
  67034. // var off_caps1 = 27;
  67035. var off_caps2 = 28;
  67036. // var off_caps3 = 29;
  67037. // var off_caps4 = 30;
  67038. var off_dxgiFormat = 32;
  67039. ;
  67040. var DDSTools = /** @class */ (function () {
  67041. function DDSTools() {
  67042. }
  67043. DDSTools.GetDDSInfo = function (arrayBuffer) {
  67044. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  67045. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  67046. var mipmapCount = 1;
  67047. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  67048. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67049. }
  67050. var fourCC = header[off_pfFourCC];
  67051. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  67052. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67053. switch (fourCC) {
  67054. case FOURCC_D3DFMT_R16G16B16A16F:
  67055. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67056. break;
  67057. case FOURCC_D3DFMT_R32G32B32A32F:
  67058. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67059. break;
  67060. case FOURCC_DX10:
  67061. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  67062. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67063. break;
  67064. }
  67065. }
  67066. return {
  67067. width: header[off_width],
  67068. height: header[off_height],
  67069. mipmapCount: mipmapCount,
  67070. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  67071. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  67072. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  67073. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  67074. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  67075. dxgiFormat: dxgiFormat,
  67076. textureType: textureType
  67077. };
  67078. };
  67079. DDSTools._ToHalfFloat = function (value) {
  67080. if (!DDSTools._FloatView) {
  67081. DDSTools._FloatView = new Float32Array(1);
  67082. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  67083. }
  67084. DDSTools._FloatView[0] = value;
  67085. var x = DDSTools._Int32View[0];
  67086. var bits = (x >> 16) & 0x8000; /* Get the sign */
  67087. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  67088. var e = (x >> 23) & 0xff; /* Using int is faster here */
  67089. /* If zero, or denormal, or exponent underflows too much for a denormal
  67090. * half, return signed zero. */
  67091. if (e < 103) {
  67092. return bits;
  67093. }
  67094. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  67095. if (e > 142) {
  67096. bits |= 0x7c00;
  67097. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  67098. * not Inf, so make sure we set one mantissa bit too. */
  67099. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  67100. return bits;
  67101. }
  67102. /* If exponent underflows but not too much, return a denormal */
  67103. if (e < 113) {
  67104. m |= 0x0800;
  67105. /* Extra rounding may overflow and set mantissa to 0 and exponent
  67106. * to 1, which is OK. */
  67107. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  67108. return bits;
  67109. }
  67110. bits |= ((e - 112) << 10) | (m >> 1);
  67111. bits += m & 1;
  67112. return bits;
  67113. };
  67114. DDSTools._FromHalfFloat = function (value) {
  67115. var s = (value & 0x8000) >> 15;
  67116. var e = (value & 0x7C00) >> 10;
  67117. var f = value & 0x03FF;
  67118. if (e === 0) {
  67119. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  67120. }
  67121. else if (e == 0x1F) {
  67122. return f ? NaN : ((s ? -1 : 1) * Infinity);
  67123. }
  67124. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  67125. };
  67126. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67127. var destArray = new Float32Array(dataLength);
  67128. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67129. var index = 0;
  67130. for (var y = 0; y < height; y++) {
  67131. for (var x = 0; x < width; x++) {
  67132. var srcPos = (x + y * width) * 4;
  67133. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  67134. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  67135. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  67136. if (DDSTools.StoreLODInAlphaChannel) {
  67137. destArray[index + 3] = lod;
  67138. }
  67139. else {
  67140. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  67141. }
  67142. index += 4;
  67143. }
  67144. }
  67145. return destArray;
  67146. };
  67147. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67148. if (DDSTools.StoreLODInAlphaChannel) {
  67149. var destArray = new Uint16Array(dataLength);
  67150. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67151. var index = 0;
  67152. for (var y = 0; y < height; y++) {
  67153. for (var x = 0; x < width; x++) {
  67154. var srcPos = (x + y * width) * 4;
  67155. destArray[index] = srcData[srcPos];
  67156. destArray[index + 1] = srcData[srcPos + 1];
  67157. destArray[index + 2] = srcData[srcPos + 2];
  67158. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  67159. index += 4;
  67160. }
  67161. }
  67162. return destArray;
  67163. }
  67164. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  67165. };
  67166. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67167. if (DDSTools.StoreLODInAlphaChannel) {
  67168. var destArray = new Float32Array(dataLength);
  67169. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67170. var index = 0;
  67171. for (var y = 0; y < height; y++) {
  67172. for (var x = 0; x < width; x++) {
  67173. var srcPos = (x + y * width) * 4;
  67174. destArray[index] = srcData[srcPos];
  67175. destArray[index + 1] = srcData[srcPos + 1];
  67176. destArray[index + 2] = srcData[srcPos + 2];
  67177. destArray[index + 3] = lod;
  67178. index += 4;
  67179. }
  67180. }
  67181. return destArray;
  67182. }
  67183. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  67184. };
  67185. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67186. var destArray = new Uint8Array(dataLength);
  67187. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67188. var index = 0;
  67189. for (var y = 0; y < height; y++) {
  67190. for (var x = 0; x < width; x++) {
  67191. var srcPos = (x + y * width) * 4;
  67192. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67193. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67194. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67195. if (DDSTools.StoreLODInAlphaChannel) {
  67196. destArray[index + 3] = lod;
  67197. }
  67198. else {
  67199. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67200. }
  67201. index += 4;
  67202. }
  67203. }
  67204. return destArray;
  67205. };
  67206. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67207. var destArray = new Uint8Array(dataLength);
  67208. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67209. var index = 0;
  67210. for (var y = 0; y < height; y++) {
  67211. for (var x = 0; x < width; x++) {
  67212. var srcPos = (x + y * width) * 4;
  67213. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  67214. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  67215. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  67216. if (DDSTools.StoreLODInAlphaChannel) {
  67217. destArray[index + 3] = lod;
  67218. }
  67219. else {
  67220. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  67221. }
  67222. index += 4;
  67223. }
  67224. }
  67225. return destArray;
  67226. };
  67227. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67228. var byteArray = new Uint8Array(dataLength);
  67229. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67230. var index = 0;
  67231. for (var y = 0; y < height; y++) {
  67232. for (var x = 0; x < width; x++) {
  67233. var srcPos = (x + y * width) * 4;
  67234. byteArray[index] = srcData[srcPos + 2];
  67235. byteArray[index + 1] = srcData[srcPos + 1];
  67236. byteArray[index + 2] = srcData[srcPos];
  67237. byteArray[index + 3] = srcData[srcPos + 3];
  67238. index += 4;
  67239. }
  67240. }
  67241. return byteArray;
  67242. };
  67243. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67244. var byteArray = new Uint8Array(dataLength);
  67245. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67246. var index = 0;
  67247. for (var y = 0; y < height; y++) {
  67248. for (var x = 0; x < width; x++) {
  67249. var srcPos = (x + y * width) * 3;
  67250. byteArray[index] = srcData[srcPos + 2];
  67251. byteArray[index + 1] = srcData[srcPos + 1];
  67252. byteArray[index + 2] = srcData[srcPos];
  67253. index += 3;
  67254. }
  67255. }
  67256. return byteArray;
  67257. };
  67258. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67259. var byteArray = new Uint8Array(dataLength);
  67260. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67261. var index = 0;
  67262. for (var y = 0; y < height; y++) {
  67263. for (var x = 0; x < width; x++) {
  67264. var srcPos = (x + y * width);
  67265. byteArray[index] = srcData[srcPos];
  67266. index++;
  67267. }
  67268. }
  67269. return byteArray;
  67270. };
  67271. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  67272. if (lodIndex === void 0) { lodIndex = -1; }
  67273. var ext = engine.getCaps().s3tc;
  67274. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  67275. var internalFormat = 0;
  67276. var format = 0;
  67277. var blockBytes = 1;
  67278. if (header[off_magic] != DDS_MAGIC) {
  67279. BABYLON.Tools.Error("Invalid magic number in DDS header");
  67280. return;
  67281. }
  67282. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  67283. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  67284. return;
  67285. }
  67286. if (info.isCompressed && !ext) {
  67287. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  67288. return;
  67289. }
  67290. var bpp = header[off_RGBbpp];
  67291. dataOffset = header[off_size] + 4;
  67292. var computeFormats = false;
  67293. if (info.isFourCC) {
  67294. fourCC = header[off_pfFourCC];
  67295. switch (fourCC) {
  67296. case FOURCC_DXT1:
  67297. blockBytes = 8;
  67298. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  67299. break;
  67300. case FOURCC_DXT3:
  67301. blockBytes = 16;
  67302. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  67303. break;
  67304. case FOURCC_DXT5:
  67305. blockBytes = 16;
  67306. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  67307. break;
  67308. case FOURCC_D3DFMT_R16G16B16A16F:
  67309. computeFormats = true;
  67310. break;
  67311. case FOURCC_D3DFMT_R32G32B32A32F:
  67312. computeFormats = true;
  67313. break;
  67314. case FOURCC_DX10:
  67315. // There is an additionnal header so dataOffset need to be changed
  67316. dataOffset += 5 * 4; // 5 uints
  67317. var supported = false;
  67318. switch (info.dxgiFormat) {
  67319. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  67320. computeFormats = true;
  67321. supported = true;
  67322. break;
  67323. case DXGI_FORMAT_B8G8R8X8_UNORM:
  67324. info.isRGB = true;
  67325. info.isFourCC = false;
  67326. bpp = 32;
  67327. supported = true;
  67328. break;
  67329. }
  67330. if (supported) {
  67331. break;
  67332. }
  67333. default:
  67334. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  67335. return;
  67336. }
  67337. }
  67338. if (computeFormats) {
  67339. format = engine._getWebGLTextureType(info.textureType);
  67340. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67341. }
  67342. mipmapCount = 1;
  67343. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  67344. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67345. }
  67346. for (var face = 0; face < faces; face++) {
  67347. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67348. width = header[off_width];
  67349. height = header[off_height];
  67350. for (mip = 0; mip < mipmapCount; ++mip) {
  67351. if (lodIndex === -1 || lodIndex === mip) {
  67352. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  67353. var i = (lodIndex === -1) ? mip : 0;
  67354. if (!info.isCompressed && info.isFourCC) {
  67355. dataLength = width * height * 4;
  67356. var FloatArray = null;
  67357. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  67358. if (bpp === 128) {
  67359. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67360. }
  67361. else if (bpp === 64) {
  67362. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67363. }
  67364. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67365. format = engine._getWebGLTextureType(info.textureType);
  67366. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67367. }
  67368. else {
  67369. if (bpp === 128) {
  67370. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67371. }
  67372. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  67373. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67374. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67375. format = engine._getWebGLTextureType(info.textureType);
  67376. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67377. }
  67378. else {
  67379. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67380. }
  67381. }
  67382. if (FloatArray) {
  67383. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  67384. }
  67385. }
  67386. else if (info.isRGB) {
  67387. if (bpp === 24) {
  67388. dataLength = width * height * 3;
  67389. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67390. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  67391. }
  67392. else {
  67393. dataLength = width * height * 4;
  67394. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67395. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  67396. }
  67397. }
  67398. else if (info.isLuminance) {
  67399. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  67400. var unpaddedRowSize = width;
  67401. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  67402. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  67403. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67404. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  67405. }
  67406. else {
  67407. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  67408. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  67409. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  67410. }
  67411. }
  67412. dataOffset += width * height * (bpp / 8);
  67413. width *= 0.5;
  67414. height *= 0.5;
  67415. width = Math.max(1.0, width);
  67416. height = Math.max(1.0, height);
  67417. }
  67418. }
  67419. };
  67420. DDSTools.StoreLODInAlphaChannel = false;
  67421. return DDSTools;
  67422. }());
  67423. Internals.DDSTools = DDSTools;
  67424. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67425. })(BABYLON || (BABYLON = {}));
  67426. //# sourceMappingURL=babylon.dds.js.map
  67427. var BABYLON;
  67428. (function (BABYLON) {
  67429. var Internals;
  67430. (function (Internals) {
  67431. /**
  67432. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  67433. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  67434. */
  67435. var KhronosTextureContainer = /** @class */ (function () {
  67436. /**
  67437. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  67438. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  67439. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  67440. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  67441. */
  67442. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  67443. this.arrayBuffer = arrayBuffer;
  67444. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  67445. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  67446. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  67447. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  67448. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  67449. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  67450. BABYLON.Tools.Error("texture missing KTX identifier");
  67451. return;
  67452. }
  67453. // load the reset of the header in native 32 bit int
  67454. var header = new Int32Array(this.arrayBuffer, 12, 13);
  67455. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  67456. var oppositeEndianess = header[0] === 0x01020304;
  67457. // read all the header elements in order they exist in the file, without modification (sans endainness)
  67458. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  67459. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  67460. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  67461. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  67462. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  67463. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  67464. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  67465. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  67466. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  67467. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  67468. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  67469. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  67470. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  67471. if (this.glType !== 0) {
  67472. BABYLON.Tools.Error("only compressed formats currently supported");
  67473. return;
  67474. }
  67475. else {
  67476. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  67477. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  67478. }
  67479. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  67480. BABYLON.Tools.Error("only 2D textures currently supported");
  67481. return;
  67482. }
  67483. if (this.numberOfArrayElements !== 0) {
  67484. BABYLON.Tools.Error("texture arrays not currently supported");
  67485. return;
  67486. }
  67487. if (this.numberOfFaces !== facesExpected) {
  67488. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  67489. return;
  67490. }
  67491. // we now have a completely validated file, so could use existence of loadType as success
  67492. // would need to make this more elaborate & adjust checks above to support more than one load type
  67493. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  67494. }
  67495. // not as fast hardware based, but will probably never need to use
  67496. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  67497. return ((val & 0xFF) << 24)
  67498. | ((val & 0xFF00) << 8)
  67499. | ((val >> 8) & 0xFF00)
  67500. | ((val >> 24) & 0xFF);
  67501. };
  67502. /**
  67503. * It is assumed that the texture has already been created & is currently bound
  67504. */
  67505. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  67506. switch (this.loadType) {
  67507. case KhronosTextureContainer.COMPRESSED_2D:
  67508. this._upload2DCompressedLevels(gl, loadMipmaps);
  67509. break;
  67510. case KhronosTextureContainer.TEX_2D:
  67511. case KhronosTextureContainer.COMPRESSED_3D:
  67512. case KhronosTextureContainer.TEX_3D:
  67513. }
  67514. };
  67515. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  67516. // initialize width & height for level 1
  67517. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  67518. var width = this.pixelWidth;
  67519. var height = this.pixelHeight;
  67520. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  67521. for (var level = 0; level < mipmapCount; level++) {
  67522. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  67523. for (var face = 0; face < this.numberOfFaces; face++) {
  67524. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67525. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  67526. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  67527. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  67528. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  67529. }
  67530. width = Math.max(1.0, width * 0.5);
  67531. height = Math.max(1.0, height * 0.5);
  67532. }
  67533. };
  67534. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  67535. // load types
  67536. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  67537. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  67538. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  67539. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  67540. return KhronosTextureContainer;
  67541. }());
  67542. Internals.KhronosTextureContainer = KhronosTextureContainer;
  67543. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67544. })(BABYLON || (BABYLON = {}));
  67545. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  67546. var BABYLON;
  67547. (function (BABYLON) {
  67548. var Debug;
  67549. (function (Debug) {
  67550. /**
  67551. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  67552. */
  67553. var SkeletonViewer = /** @class */ (function () {
  67554. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  67555. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  67556. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  67557. this.skeleton = skeleton;
  67558. this.mesh = mesh;
  67559. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  67560. this.renderingGroupId = renderingGroupId;
  67561. this.color = BABYLON.Color3.White();
  67562. this._debugLines = new Array();
  67563. this._isEnabled = false;
  67564. this._scene = scene;
  67565. this.update();
  67566. this._renderFunction = this.update.bind(this);
  67567. }
  67568. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  67569. get: function () {
  67570. return this._isEnabled;
  67571. },
  67572. set: function (value) {
  67573. if (this._isEnabled === value) {
  67574. return;
  67575. }
  67576. this._isEnabled = value;
  67577. if (value) {
  67578. this._scene.registerBeforeRender(this._renderFunction);
  67579. }
  67580. else {
  67581. this._scene.unregisterBeforeRender(this._renderFunction);
  67582. }
  67583. },
  67584. enumerable: true,
  67585. configurable: true
  67586. });
  67587. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  67588. if (x === void 0) { x = 0; }
  67589. if (y === void 0) { y = 0; }
  67590. if (z === void 0) { z = 0; }
  67591. var tmat = BABYLON.Tmp.Matrix[0];
  67592. var parentBone = bone.getParent();
  67593. tmat.copyFrom(bone.getLocalMatrix());
  67594. if (x !== 0 || y !== 0 || z !== 0) {
  67595. var tmat2 = BABYLON.Tmp.Matrix[1];
  67596. BABYLON.Matrix.IdentityToRef(tmat2);
  67597. tmat2.m[12] = x;
  67598. tmat2.m[13] = y;
  67599. tmat2.m[14] = z;
  67600. tmat2.multiplyToRef(tmat, tmat);
  67601. }
  67602. if (parentBone) {
  67603. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  67604. }
  67605. tmat.multiplyToRef(meshMat, tmat);
  67606. position.x = tmat.m[12];
  67607. position.y = tmat.m[13];
  67608. position.z = tmat.m[14];
  67609. };
  67610. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  67611. var len = bones.length;
  67612. var meshPos = this.mesh.position;
  67613. for (var i = 0; i < len; i++) {
  67614. var bone = bones[i];
  67615. var points = this._debugLines[i];
  67616. if (!points) {
  67617. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67618. this._debugLines[i] = points;
  67619. }
  67620. this._getBonePosition(points[0], bone, meshMat);
  67621. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  67622. points[0].subtractInPlace(meshPos);
  67623. points[1].subtractInPlace(meshPos);
  67624. }
  67625. };
  67626. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  67627. var len = bones.length;
  67628. var boneNum = 0;
  67629. var meshPos = this.mesh.position;
  67630. for (var i = len - 1; i >= 0; i--) {
  67631. var childBone = bones[i];
  67632. var parentBone = childBone.getParent();
  67633. if (!parentBone) {
  67634. continue;
  67635. }
  67636. var points = this._debugLines[boneNum];
  67637. if (!points) {
  67638. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67639. this._debugLines[boneNum] = points;
  67640. }
  67641. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  67642. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  67643. points[0].subtractInPlace(meshPos);
  67644. points[1].subtractInPlace(meshPos);
  67645. boneNum++;
  67646. }
  67647. };
  67648. SkeletonViewer.prototype.update = function () {
  67649. if (this.autoUpdateBonesMatrices) {
  67650. this.skeleton.computeAbsoluteTransforms();
  67651. }
  67652. if (this.skeleton.bones[0].length === undefined) {
  67653. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67654. }
  67655. else {
  67656. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67657. }
  67658. if (!this._debugMesh) {
  67659. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  67660. this._debugMesh.renderingGroupId = this.renderingGroupId;
  67661. }
  67662. else {
  67663. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  67664. }
  67665. this._debugMesh.position.copyFrom(this.mesh.position);
  67666. this._debugMesh.color = this.color;
  67667. };
  67668. SkeletonViewer.prototype.dispose = function () {
  67669. if (this._debugMesh) {
  67670. this.isEnabled = false;
  67671. this._debugMesh.dispose();
  67672. this._debugMesh = null;
  67673. }
  67674. };
  67675. return SkeletonViewer;
  67676. }());
  67677. Debug.SkeletonViewer = SkeletonViewer;
  67678. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67679. })(BABYLON || (BABYLON = {}));
  67680. //# sourceMappingURL=babylon.skeletonViewer.js.map
  67681. var BABYLON;
  67682. (function (BABYLON) {
  67683. var Debug;
  67684. (function (Debug) {
  67685. var AxesViewer = /** @class */ (function () {
  67686. function AxesViewer(scene, scaleLines) {
  67687. if (scaleLines === void 0) { scaleLines = 1; }
  67688. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67689. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67690. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67691. this.scaleLines = 1;
  67692. this.scaleLines = scaleLines;
  67693. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  67694. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  67695. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  67696. this._xmesh.renderingGroupId = 2;
  67697. this._ymesh.renderingGroupId = 2;
  67698. this._zmesh.renderingGroupId = 2;
  67699. this._xmesh.material.checkReadyOnlyOnce = true;
  67700. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  67701. this._ymesh.material.checkReadyOnlyOnce = true;
  67702. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  67703. this._zmesh.material.checkReadyOnlyOnce = true;
  67704. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  67705. this.scene = scene;
  67706. }
  67707. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  67708. var scaleLines = this.scaleLines;
  67709. if (this._xmesh) {
  67710. this._xmesh.position.copyFrom(position);
  67711. }
  67712. if (this._ymesh) {
  67713. this._ymesh.position.copyFrom(position);
  67714. }
  67715. if (this._zmesh) {
  67716. this._zmesh.position.copyFrom(position);
  67717. }
  67718. var point2 = this._xline[1];
  67719. point2.x = xaxis.x * scaleLines;
  67720. point2.y = xaxis.y * scaleLines;
  67721. point2.z = xaxis.z * scaleLines;
  67722. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  67723. point2 = this._yline[1];
  67724. point2.x = yaxis.x * scaleLines;
  67725. point2.y = yaxis.y * scaleLines;
  67726. point2.z = yaxis.z * scaleLines;
  67727. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  67728. point2 = this._zline[1];
  67729. point2.x = zaxis.x * scaleLines;
  67730. point2.y = zaxis.y * scaleLines;
  67731. point2.z = zaxis.z * scaleLines;
  67732. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  67733. };
  67734. AxesViewer.prototype.dispose = function () {
  67735. if (this._xmesh) {
  67736. this._xmesh.dispose();
  67737. }
  67738. if (this._ymesh) {
  67739. this._ymesh.dispose();
  67740. }
  67741. if (this._zmesh) {
  67742. this._zmesh.dispose();
  67743. }
  67744. this._xmesh = null;
  67745. this._ymesh = null;
  67746. this._zmesh = null;
  67747. this.scene = null;
  67748. };
  67749. return AxesViewer;
  67750. }());
  67751. Debug.AxesViewer = AxesViewer;
  67752. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67753. })(BABYLON || (BABYLON = {}));
  67754. //# sourceMappingURL=babylon.axesViewer.js.map
  67755. var BABYLON;
  67756. (function (BABYLON) {
  67757. var Debug;
  67758. (function (Debug) {
  67759. var BoneAxesViewer = /** @class */ (function (_super) {
  67760. __extends(BoneAxesViewer, _super);
  67761. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  67762. if (scaleLines === void 0) { scaleLines = 1; }
  67763. var _this = _super.call(this, scene, scaleLines) || this;
  67764. _this.pos = BABYLON.Vector3.Zero();
  67765. _this.xaxis = BABYLON.Vector3.Zero();
  67766. _this.yaxis = BABYLON.Vector3.Zero();
  67767. _this.zaxis = BABYLON.Vector3.Zero();
  67768. _this.mesh = mesh;
  67769. _this.bone = bone;
  67770. return _this;
  67771. }
  67772. BoneAxesViewer.prototype.update = function () {
  67773. if (!this.mesh || !this.bone) {
  67774. return;
  67775. }
  67776. var bone = this.bone;
  67777. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  67778. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  67779. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  67780. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  67781. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  67782. };
  67783. BoneAxesViewer.prototype.dispose = function () {
  67784. if (this.mesh) {
  67785. this.mesh = null;
  67786. this.bone = null;
  67787. _super.prototype.dispose.call(this);
  67788. }
  67789. };
  67790. return BoneAxesViewer;
  67791. }(Debug.AxesViewer));
  67792. Debug.BoneAxesViewer = BoneAxesViewer;
  67793. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67794. })(BABYLON || (BABYLON = {}));
  67795. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  67796. var BABYLON;
  67797. (function (BABYLON) {
  67798. var RayHelper = /** @class */ (function () {
  67799. function RayHelper(ray) {
  67800. this.ray = ray;
  67801. }
  67802. RayHelper.CreateAndShow = function (ray, scene, color) {
  67803. var helper = new RayHelper(ray);
  67804. helper.show(scene, color);
  67805. return helper;
  67806. };
  67807. RayHelper.prototype.show = function (scene, color) {
  67808. if (!this._renderFunction && this.ray) {
  67809. var ray = this.ray;
  67810. this._renderFunction = this._render.bind(this);
  67811. this._scene = scene;
  67812. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  67813. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  67814. if (this._renderFunction) {
  67815. this._scene.registerBeforeRender(this._renderFunction);
  67816. }
  67817. }
  67818. if (color && this._renderLine) {
  67819. this._renderLine.color.copyFrom(color);
  67820. }
  67821. };
  67822. RayHelper.prototype.hide = function () {
  67823. if (this._renderFunction && this._scene) {
  67824. this._scene.unregisterBeforeRender(this._renderFunction);
  67825. this._scene = null;
  67826. this._renderFunction = null;
  67827. if (this._renderLine) {
  67828. this._renderLine.dispose();
  67829. this._renderLine = null;
  67830. }
  67831. this._renderPoints = [];
  67832. }
  67833. };
  67834. RayHelper.prototype._render = function () {
  67835. var ray = this.ray;
  67836. if (!ray) {
  67837. return;
  67838. }
  67839. var point = this._renderPoints[1];
  67840. var len = Math.min(ray.length, 1000000);
  67841. point.copyFrom(ray.direction);
  67842. point.scaleInPlace(len);
  67843. point.addInPlace(ray.origin);
  67844. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  67845. };
  67846. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  67847. this._attachedToMesh = mesh;
  67848. var ray = this.ray;
  67849. if (!ray) {
  67850. return;
  67851. }
  67852. if (!ray.direction) {
  67853. ray.direction = BABYLON.Vector3.Zero();
  67854. }
  67855. if (!ray.origin) {
  67856. ray.origin = BABYLON.Vector3.Zero();
  67857. }
  67858. if (length) {
  67859. ray.length = length;
  67860. }
  67861. if (!meshSpaceOrigin) {
  67862. meshSpaceOrigin = BABYLON.Vector3.Zero();
  67863. }
  67864. if (!meshSpaceDirection) {
  67865. // -1 so that this will work with Mesh.lookAt
  67866. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  67867. }
  67868. if (!this._meshSpaceDirection) {
  67869. this._meshSpaceDirection = meshSpaceDirection.clone();
  67870. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  67871. }
  67872. else {
  67873. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  67874. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  67875. }
  67876. if (!this._updateToMeshFunction) {
  67877. this._updateToMeshFunction = this._updateToMesh.bind(this);
  67878. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  67879. }
  67880. this._updateToMesh();
  67881. };
  67882. RayHelper.prototype.detachFromMesh = function () {
  67883. if (this._attachedToMesh) {
  67884. if (this._updateToMeshFunction) {
  67885. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  67886. }
  67887. this._attachedToMesh = null;
  67888. this._updateToMeshFunction = null;
  67889. }
  67890. };
  67891. RayHelper.prototype._updateToMesh = function () {
  67892. var ray = this.ray;
  67893. if (!this._attachedToMesh || !ray) {
  67894. return;
  67895. }
  67896. if (this._attachedToMesh._isDisposed) {
  67897. this.detachFromMesh();
  67898. return;
  67899. }
  67900. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  67901. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  67902. };
  67903. RayHelper.prototype.dispose = function () {
  67904. this.hide();
  67905. this.detachFromMesh();
  67906. this.ray = null;
  67907. };
  67908. return RayHelper;
  67909. }());
  67910. BABYLON.RayHelper = RayHelper;
  67911. })(BABYLON || (BABYLON = {}));
  67912. //# sourceMappingURL=babylon.rayHelper.js.map
  67913. var BABYLON;
  67914. (function (BABYLON) {
  67915. var DebugLayer = /** @class */ (function () {
  67916. function DebugLayer(scene) {
  67917. this._scene = scene;
  67918. }
  67919. /** Creates the inspector window. */
  67920. DebugLayer.prototype._createInspector = function (config) {
  67921. if (config === void 0) { config = {}; }
  67922. var popup = config.popup || false;
  67923. var initialTab = config.initialTab || 0;
  67924. var parentElement = config.parentElement || null;
  67925. if (!this._inspector) {
  67926. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  67927. } // else nothing to do,; instance is already existing
  67928. };
  67929. DebugLayer.prototype.isVisible = function () {
  67930. if (!this._inspector) {
  67931. return false;
  67932. }
  67933. return true;
  67934. };
  67935. DebugLayer.prototype.hide = function () {
  67936. if (this._inspector) {
  67937. try {
  67938. this._inspector.dispose();
  67939. }
  67940. catch (e) {
  67941. // If the inspector has been removed directly from the inspector tool
  67942. }
  67943. this._inspector = null;
  67944. }
  67945. };
  67946. DebugLayer.prototype.show = function (config) {
  67947. if (config === void 0) { config = {}; }
  67948. if (typeof INSPECTOR == 'undefined') {
  67949. // Load inspector and add it to the DOM
  67950. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  67951. }
  67952. else {
  67953. // Otherwise creates the inspector
  67954. this._createInspector(config);
  67955. }
  67956. };
  67957. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  67958. return DebugLayer;
  67959. }());
  67960. BABYLON.DebugLayer = DebugLayer;
  67961. })(BABYLON || (BABYLON = {}));
  67962. //# sourceMappingURL=babylon.debugLayer.js.map
  67963. var BABYLON;
  67964. (function (BABYLON) {
  67965. var Debug;
  67966. (function (Debug) {
  67967. var PhysicsViewer = /** @class */ (function () {
  67968. function PhysicsViewer(scene) {
  67969. this._impostors = [];
  67970. this._meshes = [];
  67971. this._numMeshes = 0;
  67972. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67973. var physicEngine = this._scene.getPhysicsEngine();
  67974. if (physicEngine) {
  67975. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  67976. }
  67977. }
  67978. PhysicsViewer.prototype._updateDebugMeshes = function () {
  67979. var plugin = this._physicsEnginePlugin;
  67980. for (var i = 0; i < this._numMeshes; i++) {
  67981. var impostor = this._impostors[i];
  67982. if (!impostor) {
  67983. continue;
  67984. }
  67985. if (impostor.isDisposed) {
  67986. this.hideImpostor(this._impostors[i--]);
  67987. }
  67988. else {
  67989. var mesh = this._meshes[i];
  67990. if (mesh && plugin) {
  67991. plugin.syncMeshWithImpostor(mesh, impostor);
  67992. }
  67993. }
  67994. }
  67995. };
  67996. PhysicsViewer.prototype.showImpostor = function (impostor) {
  67997. if (!this._scene) {
  67998. return;
  67999. }
  68000. for (var i = 0; i < this._numMeshes; i++) {
  68001. if (this._impostors[i] == impostor) {
  68002. return;
  68003. }
  68004. }
  68005. var debugMesh = this._getDebugMesh(impostor, this._scene);
  68006. if (debugMesh) {
  68007. this._impostors[this._numMeshes] = impostor;
  68008. this._meshes[this._numMeshes] = debugMesh;
  68009. if (this._numMeshes === 0) {
  68010. this._renderFunction = this._updateDebugMeshes.bind(this);
  68011. this._scene.registerBeforeRender(this._renderFunction);
  68012. }
  68013. this._numMeshes++;
  68014. }
  68015. };
  68016. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  68017. if (!impostor || !this._scene) {
  68018. return;
  68019. }
  68020. var removed = false;
  68021. for (var i = 0; i < this._numMeshes; i++) {
  68022. if (this._impostors[i] == impostor) {
  68023. var mesh = this._meshes[i];
  68024. if (!mesh) {
  68025. continue;
  68026. }
  68027. this._scene.removeMesh(mesh);
  68028. mesh.dispose();
  68029. this._numMeshes--;
  68030. if (this._numMeshes > 0) {
  68031. this._meshes[i] = this._meshes[this._numMeshes];
  68032. this._impostors[i] = this._impostors[this._numMeshes];
  68033. this._meshes[this._numMeshes] = null;
  68034. this._impostors[this._numMeshes] = null;
  68035. }
  68036. else {
  68037. this._meshes[0] = null;
  68038. this._impostors[0] = null;
  68039. }
  68040. removed = true;
  68041. break;
  68042. }
  68043. }
  68044. if (removed && this._numMeshes === 0) {
  68045. this._scene.unregisterBeforeRender(this._renderFunction);
  68046. }
  68047. };
  68048. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  68049. if (!this._debugMaterial) {
  68050. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  68051. this._debugMaterial.wireframe = true;
  68052. }
  68053. return this._debugMaterial;
  68054. };
  68055. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  68056. if (!this._debugBoxMesh) {
  68057. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  68058. this._debugBoxMesh.renderingGroupId = 1;
  68059. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68060. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  68061. scene.removeMesh(this._debugBoxMesh);
  68062. }
  68063. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  68064. };
  68065. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  68066. if (!this._debugSphereMesh) {
  68067. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  68068. this._debugSphereMesh.renderingGroupId = 1;
  68069. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68070. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  68071. scene.removeMesh(this._debugSphereMesh);
  68072. }
  68073. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  68074. };
  68075. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  68076. var mesh = null;
  68077. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  68078. mesh = this._getDebugBoxMesh(scene);
  68079. impostor.getBoxSizeToRef(mesh.scaling);
  68080. }
  68081. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  68082. mesh = this._getDebugSphereMesh(scene);
  68083. var radius = impostor.getRadius();
  68084. mesh.scaling.x = radius * 2;
  68085. mesh.scaling.y = radius * 2;
  68086. mesh.scaling.z = radius * 2;
  68087. }
  68088. return mesh;
  68089. };
  68090. PhysicsViewer.prototype.dispose = function () {
  68091. for (var i = 0; i < this._numMeshes; i++) {
  68092. this.hideImpostor(this._impostors[i]);
  68093. }
  68094. if (this._debugBoxMesh) {
  68095. this._debugBoxMesh.dispose();
  68096. }
  68097. if (this._debugSphereMesh) {
  68098. this._debugSphereMesh.dispose();
  68099. }
  68100. if (this._debugMaterial) {
  68101. this._debugMaterial.dispose();
  68102. }
  68103. this._impostors.length = 0;
  68104. this._scene = null;
  68105. this._physicsEnginePlugin = null;
  68106. };
  68107. return PhysicsViewer;
  68108. }());
  68109. Debug.PhysicsViewer = PhysicsViewer;
  68110. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68111. })(BABYLON || (BABYLON = {}));
  68112. //# sourceMappingURL=babylon.physicsViewer.js.map
  68113. var BABYLON;
  68114. (function (BABYLON) {
  68115. var BoundingBoxRenderer = /** @class */ (function () {
  68116. function BoundingBoxRenderer(scene) {
  68117. this.frontColor = new BABYLON.Color3(1, 1, 1);
  68118. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  68119. this.showBackLines = true;
  68120. this.renderList = new BABYLON.SmartArray(32);
  68121. this._vertexBuffers = {};
  68122. this._scene = scene;
  68123. }
  68124. BoundingBoxRenderer.prototype._prepareRessources = function () {
  68125. if (this._colorShader) {
  68126. return;
  68127. }
  68128. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  68129. attributes: [BABYLON.VertexBuffer.PositionKind],
  68130. uniforms: ["world", "viewProjection", "color"]
  68131. });
  68132. var engine = this._scene.getEngine();
  68133. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  68134. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  68135. this._createIndexBuffer();
  68136. };
  68137. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  68138. var engine = this._scene.getEngine();
  68139. 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]);
  68140. };
  68141. BoundingBoxRenderer.prototype._rebuild = function () {
  68142. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68143. if (vb) {
  68144. vb._rebuild();
  68145. }
  68146. this._createIndexBuffer();
  68147. };
  68148. BoundingBoxRenderer.prototype.reset = function () {
  68149. this.renderList.reset();
  68150. };
  68151. BoundingBoxRenderer.prototype.render = function () {
  68152. if (this.renderList.length === 0) {
  68153. return;
  68154. }
  68155. this._prepareRessources();
  68156. if (!this._colorShader.isReady()) {
  68157. return;
  68158. }
  68159. var engine = this._scene.getEngine();
  68160. engine.setDepthWrite(false);
  68161. this._colorShader._preBind();
  68162. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  68163. var boundingBox = this.renderList.data[boundingBoxIndex];
  68164. var min = boundingBox.minimum;
  68165. var max = boundingBox.maximum;
  68166. var diff = max.subtract(min);
  68167. var median = min.add(diff.scale(0.5));
  68168. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68169. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68170. .multiply(boundingBox.getWorldMatrix());
  68171. // VBOs
  68172. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68173. if (this.showBackLines) {
  68174. // Back
  68175. engine.setDepthFunctionToGreaterOrEqual();
  68176. this._scene.resetCachedMaterial();
  68177. this._colorShader.setColor4("color", this.backColor.toColor4());
  68178. this._colorShader.bind(worldMatrix);
  68179. // Draw order
  68180. engine.draw(false, 0, 24);
  68181. }
  68182. // Front
  68183. engine.setDepthFunctionToLess();
  68184. this._scene.resetCachedMaterial();
  68185. this._colorShader.setColor4("color", this.frontColor.toColor4());
  68186. this._colorShader.bind(worldMatrix);
  68187. // Draw order
  68188. engine.draw(false, 0, 24);
  68189. }
  68190. this._colorShader.unbind();
  68191. engine.setDepthFunctionToLessOrEqual();
  68192. engine.setDepthWrite(true);
  68193. };
  68194. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68195. this._prepareRessources();
  68196. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68197. return;
  68198. }
  68199. var engine = this._scene.getEngine();
  68200. engine.setDepthWrite(false);
  68201. engine.setColorWrite(false);
  68202. this._colorShader._preBind();
  68203. var boundingBox = mesh._boundingInfo.boundingBox;
  68204. var min = boundingBox.minimum;
  68205. var max = boundingBox.maximum;
  68206. var diff = max.subtract(min);
  68207. var median = min.add(diff.scale(0.5));
  68208. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68209. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68210. .multiply(boundingBox.getWorldMatrix());
  68211. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68212. engine.setDepthFunctionToLess();
  68213. this._scene.resetCachedMaterial();
  68214. this._colorShader.bind(worldMatrix);
  68215. engine.draw(false, 0, 24);
  68216. this._colorShader.unbind();
  68217. engine.setDepthFunctionToLessOrEqual();
  68218. engine.setDepthWrite(true);
  68219. engine.setColorWrite(true);
  68220. };
  68221. BoundingBoxRenderer.prototype.dispose = function () {
  68222. if (!this._colorShader) {
  68223. return;
  68224. }
  68225. this.renderList.dispose();
  68226. this._colorShader.dispose();
  68227. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68228. if (buffer) {
  68229. buffer.dispose();
  68230. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68231. }
  68232. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68233. };
  68234. return BoundingBoxRenderer;
  68235. }());
  68236. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  68237. })(BABYLON || (BABYLON = {}));
  68238. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  68239. var BABYLON;
  68240. (function (BABYLON) {
  68241. var MorphTarget = /** @class */ (function () {
  68242. function MorphTarget(name, influence) {
  68243. if (influence === void 0) { influence = 0; }
  68244. this.name = name;
  68245. this.animations = new Array();
  68246. this._positions = null;
  68247. this._normals = null;
  68248. this._tangents = null;
  68249. this.onInfluenceChanged = new BABYLON.Observable();
  68250. this.influence = influence;
  68251. }
  68252. Object.defineProperty(MorphTarget.prototype, "influence", {
  68253. get: function () {
  68254. return this._influence;
  68255. },
  68256. set: function (influence) {
  68257. if (this._influence === influence) {
  68258. return;
  68259. }
  68260. var previous = this._influence;
  68261. this._influence = influence;
  68262. if (this.onInfluenceChanged.hasObservers) {
  68263. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  68264. }
  68265. },
  68266. enumerable: true,
  68267. configurable: true
  68268. });
  68269. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  68270. get: function () {
  68271. return !!this._positions;
  68272. },
  68273. enumerable: true,
  68274. configurable: true
  68275. });
  68276. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  68277. get: function () {
  68278. return !!this._normals;
  68279. },
  68280. enumerable: true,
  68281. configurable: true
  68282. });
  68283. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  68284. get: function () {
  68285. return !!this._tangents;
  68286. },
  68287. enumerable: true,
  68288. configurable: true
  68289. });
  68290. MorphTarget.prototype.setPositions = function (data) {
  68291. this._positions = data;
  68292. };
  68293. MorphTarget.prototype.getPositions = function () {
  68294. return this._positions;
  68295. };
  68296. MorphTarget.prototype.setNormals = function (data) {
  68297. this._normals = data;
  68298. };
  68299. MorphTarget.prototype.getNormals = function () {
  68300. return this._normals;
  68301. };
  68302. MorphTarget.prototype.setTangents = function (data) {
  68303. this._tangents = data;
  68304. };
  68305. MorphTarget.prototype.getTangents = function () {
  68306. return this._tangents;
  68307. };
  68308. /**
  68309. * Serializes the current target into a Serialization object.
  68310. * Returns the serialized object.
  68311. */
  68312. MorphTarget.prototype.serialize = function () {
  68313. var serializationObject = {};
  68314. serializationObject.name = this.name;
  68315. serializationObject.influence = this.influence;
  68316. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  68317. if (this.hasNormals) {
  68318. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  68319. }
  68320. if (this.hasTangents) {
  68321. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  68322. }
  68323. // Animations
  68324. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  68325. return serializationObject;
  68326. };
  68327. // Statics
  68328. MorphTarget.Parse = function (serializationObject) {
  68329. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  68330. result.setPositions(serializationObject.positions);
  68331. if (serializationObject.normals) {
  68332. result.setNormals(serializationObject.normals);
  68333. }
  68334. if (serializationObject.tangents) {
  68335. result.setTangents(serializationObject.tangents);
  68336. }
  68337. // Animations
  68338. if (serializationObject.animations) {
  68339. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  68340. var parsedAnimation = serializationObject.animations[animationIndex];
  68341. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68342. }
  68343. }
  68344. return result;
  68345. };
  68346. MorphTarget.FromMesh = function (mesh, name, influence) {
  68347. if (!name) {
  68348. name = mesh.name;
  68349. }
  68350. var result = new MorphTarget(name, influence);
  68351. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68352. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68353. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  68354. }
  68355. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  68356. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  68357. }
  68358. return result;
  68359. };
  68360. return MorphTarget;
  68361. }());
  68362. BABYLON.MorphTarget = MorphTarget;
  68363. })(BABYLON || (BABYLON = {}));
  68364. //# sourceMappingURL=babylon.morphTarget.js.map
  68365. var BABYLON;
  68366. (function (BABYLON) {
  68367. var MorphTargetManager = /** @class */ (function () {
  68368. function MorphTargetManager(scene) {
  68369. if (scene === void 0) { scene = null; }
  68370. this._targets = new Array();
  68371. this._targetObservable = new Array();
  68372. this._activeTargets = new BABYLON.SmartArray(16);
  68373. this._supportsNormals = false;
  68374. this._supportsTangents = false;
  68375. this._vertexCount = 0;
  68376. this._uniqueId = 0;
  68377. this._tempInfluences = new Array();
  68378. if (!scene) {
  68379. scene = BABYLON.Engine.LastCreatedScene;
  68380. }
  68381. this._scene = scene;
  68382. if (this._scene) {
  68383. this._scene.morphTargetManagers.push(this);
  68384. this._uniqueId = this._scene.getUniqueId();
  68385. }
  68386. }
  68387. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  68388. get: function () {
  68389. return this._uniqueId;
  68390. },
  68391. enumerable: true,
  68392. configurable: true
  68393. });
  68394. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  68395. get: function () {
  68396. return this._vertexCount;
  68397. },
  68398. enumerable: true,
  68399. configurable: true
  68400. });
  68401. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  68402. get: function () {
  68403. return this._supportsNormals;
  68404. },
  68405. enumerable: true,
  68406. configurable: true
  68407. });
  68408. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  68409. get: function () {
  68410. return this._supportsTangents;
  68411. },
  68412. enumerable: true,
  68413. configurable: true
  68414. });
  68415. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  68416. get: function () {
  68417. return this._targets.length;
  68418. },
  68419. enumerable: true,
  68420. configurable: true
  68421. });
  68422. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  68423. get: function () {
  68424. return this._activeTargets.length;
  68425. },
  68426. enumerable: true,
  68427. configurable: true
  68428. });
  68429. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  68430. get: function () {
  68431. return this._influences;
  68432. },
  68433. enumerable: true,
  68434. configurable: true
  68435. });
  68436. MorphTargetManager.prototype.getActiveTarget = function (index) {
  68437. return this._activeTargets.data[index];
  68438. };
  68439. MorphTargetManager.prototype.getTarget = function (index) {
  68440. return this._targets[index];
  68441. };
  68442. MorphTargetManager.prototype.addTarget = function (target) {
  68443. var _this = this;
  68444. this._targets.push(target);
  68445. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  68446. _this._syncActiveTargets(needUpdate);
  68447. }));
  68448. this._syncActiveTargets(true);
  68449. };
  68450. MorphTargetManager.prototype.removeTarget = function (target) {
  68451. var index = this._targets.indexOf(target);
  68452. if (index >= 0) {
  68453. this._targets.splice(index, 1);
  68454. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  68455. this._syncActiveTargets(true);
  68456. }
  68457. };
  68458. /**
  68459. * Serializes the current manager into a Serialization object.
  68460. * Returns the serialized object.
  68461. */
  68462. MorphTargetManager.prototype.serialize = function () {
  68463. var serializationObject = {};
  68464. serializationObject.id = this.uniqueId;
  68465. serializationObject.targets = [];
  68466. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68467. var target = _a[_i];
  68468. serializationObject.targets.push(target.serialize());
  68469. }
  68470. return serializationObject;
  68471. };
  68472. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  68473. var influenceCount = 0;
  68474. this._activeTargets.reset();
  68475. this._supportsNormals = true;
  68476. this._supportsTangents = true;
  68477. this._vertexCount = 0;
  68478. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68479. var target = _a[_i];
  68480. if (target.influence > 0) {
  68481. this._activeTargets.push(target);
  68482. this._tempInfluences[influenceCount++] = target.influence;
  68483. this._supportsNormals = this._supportsNormals && target.hasNormals;
  68484. this._supportsTangents = this._supportsTangents && target.hasTangents;
  68485. var positions = target.getPositions();
  68486. if (!positions) {
  68487. BABYLON.Tools.Error("Invalid target. Target must positions.");
  68488. return;
  68489. }
  68490. var vertexCount = positions.length / 3;
  68491. if (this._vertexCount === 0) {
  68492. this._vertexCount = vertexCount;
  68493. }
  68494. else if (this._vertexCount !== vertexCount) {
  68495. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  68496. return;
  68497. }
  68498. }
  68499. }
  68500. if (!this._influences || this._influences.length !== influenceCount) {
  68501. this._influences = new Float32Array(influenceCount);
  68502. }
  68503. for (var index = 0; index < influenceCount; index++) {
  68504. this._influences[index] = this._tempInfluences[index];
  68505. }
  68506. if (needUpdate && this._scene) {
  68507. // Flag meshes as dirty to resync with the active targets
  68508. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  68509. var mesh = _c[_b];
  68510. if (mesh.morphTargetManager === this) {
  68511. mesh._syncGeometryWithMorphTargetManager();
  68512. }
  68513. }
  68514. }
  68515. };
  68516. // Statics
  68517. MorphTargetManager.Parse = function (serializationObject, scene) {
  68518. var result = new MorphTargetManager(scene);
  68519. result._uniqueId = serializationObject.id;
  68520. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  68521. var targetData = _a[_i];
  68522. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  68523. }
  68524. return result;
  68525. };
  68526. return MorphTargetManager;
  68527. }());
  68528. BABYLON.MorphTargetManager = MorphTargetManager;
  68529. })(BABYLON || (BABYLON = {}));
  68530. //# sourceMappingURL=babylon.morphTargetManager.js.map
  68531. var BABYLON;
  68532. (function (BABYLON) {
  68533. var Octree = /** @class */ (function () {
  68534. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  68535. if (maxDepth === void 0) { maxDepth = 2; }
  68536. this.maxDepth = maxDepth;
  68537. this.dynamicContent = new Array();
  68538. this._maxBlockCapacity = maxBlockCapacity || 64;
  68539. this._selectionContent = new BABYLON.SmartArray(1024);
  68540. this._creationFunc = creationFunc;
  68541. }
  68542. // Methods
  68543. Octree.prototype.update = function (worldMin, worldMax, entries) {
  68544. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  68545. };
  68546. Octree.prototype.addMesh = function (entry) {
  68547. for (var index = 0; index < this.blocks.length; index++) {
  68548. var block = this.blocks[index];
  68549. block.addEntry(entry);
  68550. }
  68551. };
  68552. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  68553. this._selectionContent.reset();
  68554. for (var index = 0; index < this.blocks.length; index++) {
  68555. var block = this.blocks[index];
  68556. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  68557. }
  68558. if (allowDuplicate) {
  68559. this._selectionContent.concat(this.dynamicContent);
  68560. }
  68561. else {
  68562. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68563. }
  68564. return this._selectionContent;
  68565. };
  68566. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  68567. this._selectionContent.reset();
  68568. for (var index = 0; index < this.blocks.length; index++) {
  68569. var block = this.blocks[index];
  68570. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  68571. }
  68572. if (allowDuplicate) {
  68573. this._selectionContent.concat(this.dynamicContent);
  68574. }
  68575. else {
  68576. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68577. }
  68578. return this._selectionContent;
  68579. };
  68580. Octree.prototype.intersectsRay = function (ray) {
  68581. this._selectionContent.reset();
  68582. for (var index = 0; index < this.blocks.length; index++) {
  68583. var block = this.blocks[index];
  68584. block.intersectsRay(ray, this._selectionContent);
  68585. }
  68586. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68587. return this._selectionContent;
  68588. };
  68589. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  68590. target.blocks = new Array();
  68591. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  68592. // Segmenting space
  68593. for (var x = 0; x < 2; x++) {
  68594. for (var y = 0; y < 2; y++) {
  68595. for (var z = 0; z < 2; z++) {
  68596. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  68597. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  68598. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  68599. block.addEntries(entries);
  68600. target.blocks.push(block);
  68601. }
  68602. }
  68603. }
  68604. };
  68605. Octree.CreationFuncForMeshes = function (entry, block) {
  68606. var boundingInfo = entry.getBoundingInfo();
  68607. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68608. block.entries.push(entry);
  68609. }
  68610. };
  68611. Octree.CreationFuncForSubMeshes = function (entry, block) {
  68612. var boundingInfo = entry.getBoundingInfo();
  68613. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68614. block.entries.push(entry);
  68615. }
  68616. };
  68617. return Octree;
  68618. }());
  68619. BABYLON.Octree = Octree;
  68620. })(BABYLON || (BABYLON = {}));
  68621. //# sourceMappingURL=babylon.octree.js.map
  68622. var BABYLON;
  68623. (function (BABYLON) {
  68624. var OctreeBlock = /** @class */ (function () {
  68625. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  68626. this.entries = new Array();
  68627. this._boundingVectors = new Array();
  68628. this._capacity = capacity;
  68629. this._depth = depth;
  68630. this._maxDepth = maxDepth;
  68631. this._creationFunc = creationFunc;
  68632. this._minPoint = minPoint;
  68633. this._maxPoint = maxPoint;
  68634. this._boundingVectors.push(minPoint.clone());
  68635. this._boundingVectors.push(maxPoint.clone());
  68636. this._boundingVectors.push(minPoint.clone());
  68637. this._boundingVectors[2].x = maxPoint.x;
  68638. this._boundingVectors.push(minPoint.clone());
  68639. this._boundingVectors[3].y = maxPoint.y;
  68640. this._boundingVectors.push(minPoint.clone());
  68641. this._boundingVectors[4].z = maxPoint.z;
  68642. this._boundingVectors.push(maxPoint.clone());
  68643. this._boundingVectors[5].z = minPoint.z;
  68644. this._boundingVectors.push(maxPoint.clone());
  68645. this._boundingVectors[6].x = minPoint.x;
  68646. this._boundingVectors.push(maxPoint.clone());
  68647. this._boundingVectors[7].y = minPoint.y;
  68648. }
  68649. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  68650. // Property
  68651. get: function () {
  68652. return this._capacity;
  68653. },
  68654. enumerable: true,
  68655. configurable: true
  68656. });
  68657. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  68658. get: function () {
  68659. return this._minPoint;
  68660. },
  68661. enumerable: true,
  68662. configurable: true
  68663. });
  68664. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  68665. get: function () {
  68666. return this._maxPoint;
  68667. },
  68668. enumerable: true,
  68669. configurable: true
  68670. });
  68671. // Methods
  68672. OctreeBlock.prototype.addEntry = function (entry) {
  68673. if (this.blocks) {
  68674. for (var index = 0; index < this.blocks.length; index++) {
  68675. var block = this.blocks[index];
  68676. block.addEntry(entry);
  68677. }
  68678. return;
  68679. }
  68680. this._creationFunc(entry, this);
  68681. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  68682. this.createInnerBlocks();
  68683. }
  68684. };
  68685. OctreeBlock.prototype.addEntries = function (entries) {
  68686. for (var index = 0; index < entries.length; index++) {
  68687. var mesh = entries[index];
  68688. this.addEntry(mesh);
  68689. }
  68690. };
  68691. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  68692. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  68693. if (this.blocks) {
  68694. for (var index = 0; index < this.blocks.length; index++) {
  68695. var block = this.blocks[index];
  68696. block.select(frustumPlanes, selection, allowDuplicate);
  68697. }
  68698. return;
  68699. }
  68700. if (allowDuplicate) {
  68701. selection.concat(this.entries);
  68702. }
  68703. else {
  68704. selection.concatWithNoDuplicate(this.entries);
  68705. }
  68706. }
  68707. };
  68708. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  68709. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  68710. if (this.blocks) {
  68711. for (var index = 0; index < this.blocks.length; index++) {
  68712. var block = this.blocks[index];
  68713. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  68714. }
  68715. return;
  68716. }
  68717. if (allowDuplicate) {
  68718. selection.concat(this.entries);
  68719. }
  68720. else {
  68721. selection.concatWithNoDuplicate(this.entries);
  68722. }
  68723. }
  68724. };
  68725. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  68726. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  68727. if (this.blocks) {
  68728. for (var index = 0; index < this.blocks.length; index++) {
  68729. var block = this.blocks[index];
  68730. block.intersectsRay(ray, selection);
  68731. }
  68732. return;
  68733. }
  68734. selection.concatWithNoDuplicate(this.entries);
  68735. }
  68736. };
  68737. OctreeBlock.prototype.createInnerBlocks = function () {
  68738. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  68739. };
  68740. return OctreeBlock;
  68741. }());
  68742. BABYLON.OctreeBlock = OctreeBlock;
  68743. })(BABYLON || (BABYLON = {}));
  68744. //# sourceMappingURL=babylon.octreeBlock.js.map
  68745. var BABYLON;
  68746. (function (BABYLON) {
  68747. var SIMDVector3 = /** @class */ (function () {
  68748. function SIMDVector3() {
  68749. }
  68750. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  68751. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  68752. };
  68753. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  68754. var m = transformation.m;
  68755. var m0 = SIMD.Float32x4.load(m, 0);
  68756. var m1 = SIMD.Float32x4.load(m, 4);
  68757. var m2 = SIMD.Float32x4.load(m, 8);
  68758. var m3 = SIMD.Float32x4.load(m, 12);
  68759. 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));
  68760. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  68761. result.x = SIMD.Float32x4.extractLane(r, 0);
  68762. result.y = SIMD.Float32x4.extractLane(r, 1);
  68763. result.z = SIMD.Float32x4.extractLane(r, 2);
  68764. };
  68765. return SIMDVector3;
  68766. }());
  68767. var SIMDMatrix = /** @class */ (function () {
  68768. function SIMDMatrix() {
  68769. }
  68770. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  68771. var tm = this.m;
  68772. var om = other.m;
  68773. var m0 = SIMD.Float32x4.load(om, 0);
  68774. var m1 = SIMD.Float32x4.load(om, 4);
  68775. var m2 = SIMD.Float32x4.load(om, 8);
  68776. var m3 = SIMD.Float32x4.load(om, 12);
  68777. for (var i = 0; i < 16; i += 4) {
  68778. 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)))));
  68779. }
  68780. return this;
  68781. };
  68782. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  68783. var src = this.m;
  68784. var dest = other.m;
  68785. // Load the 4 rows
  68786. var src0 = SIMD.Float32x4.load(src, 0);
  68787. var src1 = SIMD.Float32x4.load(src, 4);
  68788. var src2 = SIMD.Float32x4.load(src, 8);
  68789. var src3 = SIMD.Float32x4.load(src, 12);
  68790. // Transpose the source matrix. Sort of. Not a true transpose operation
  68791. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  68792. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  68793. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  68794. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  68795. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  68796. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  68797. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  68798. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  68799. // This is a true transposition, but it will lead to an incorrect result
  68800. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  68801. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  68802. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68803. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68804. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  68805. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  68806. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68807. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68808. // ----
  68809. tmp1 = SIMD.Float32x4.mul(row2, row3);
  68810. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68811. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  68812. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  68813. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68814. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  68815. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  68816. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  68817. // ----
  68818. tmp1 = SIMD.Float32x4.mul(row1, row2);
  68819. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68820. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  68821. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  68822. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68823. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  68824. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  68825. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  68826. // ----
  68827. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  68828. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68829. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  68830. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  68831. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  68832. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68833. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  68834. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  68835. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  68836. // ----
  68837. tmp1 = SIMD.Float32x4.mul(row0, row1);
  68838. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68839. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68840. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  68841. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68842. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68843. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  68844. // ----
  68845. tmp1 = SIMD.Float32x4.mul(row0, row3);
  68846. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68847. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  68848. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  68849. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68850. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  68851. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  68852. // ----
  68853. tmp1 = SIMD.Float32x4.mul(row0, row2);
  68854. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68855. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  68856. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  68857. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68858. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  68859. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  68860. // Compute determinant
  68861. var det = SIMD.Float32x4.mul(row0, minor0);
  68862. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  68863. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  68864. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  68865. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  68866. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  68867. // These shuffles aren't necessary if the faulty transposition is done
  68868. // up at the top of this function.
  68869. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  68870. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  68871. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  68872. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  68873. // Compute final values by multiplying with 1/det
  68874. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  68875. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  68876. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  68877. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  68878. return this;
  68879. };
  68880. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  68881. var out = result.m;
  68882. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  68883. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  68884. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  68885. // cc.kmVec3Subtract(f, pCenter, pEye);
  68886. var f = SIMD.Float32x4.sub(center, eye);
  68887. // cc.kmVec3Normalize(f, f);
  68888. var tmp = SIMD.Float32x4.mul(f, f);
  68889. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68890. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68891. // cc.kmVec3Assign(up, pUp);
  68892. // cc.kmVec3Normalize(up, up);
  68893. tmp = SIMD.Float32x4.mul(up, up);
  68894. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68895. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68896. // cc.kmVec3Cross(s, f, up);
  68897. 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)));
  68898. // cc.kmVec3Normalize(s, s);
  68899. tmp = SIMD.Float32x4.mul(s, s);
  68900. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68901. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68902. // cc.kmVec3Cross(u, s, f);
  68903. 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)));
  68904. // cc.kmVec3Normalize(s, s);
  68905. tmp = SIMD.Float32x4.mul(s, s);
  68906. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68907. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68908. var zero = SIMD.Float32x4.splat(0.0);
  68909. s = SIMD.Float32x4.neg(s);
  68910. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  68911. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  68912. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  68913. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  68914. 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);
  68915. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  68916. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  68917. 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)))));
  68918. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  68919. 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)))));
  68920. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  68921. 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)))));
  68922. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  68923. 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)))));
  68924. };
  68925. return SIMDMatrix;
  68926. }());
  68927. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  68928. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  68929. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  68930. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  68931. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  68932. var SIMDHelper = /** @class */ (function () {
  68933. function SIMDHelper() {
  68934. }
  68935. Object.defineProperty(SIMDHelper, "IsEnabled", {
  68936. get: function () {
  68937. return SIMDHelper._isEnabled;
  68938. },
  68939. enumerable: true,
  68940. configurable: true
  68941. });
  68942. SIMDHelper.DisableSIMD = function () {
  68943. // Replace functions
  68944. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  68945. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  68946. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  68947. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  68948. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  68949. SIMDHelper._isEnabled = false;
  68950. };
  68951. SIMDHelper.EnableSIMD = function () {
  68952. if (self.SIMD === undefined) {
  68953. return;
  68954. }
  68955. // check if polyfills needed
  68956. if (!self.Math.fround) {
  68957. self.Math.fround = (function (array) { return function (x) {
  68958. return array[0] = x, array[0];
  68959. }; })(new Float32Array(1));
  68960. }
  68961. if (!self.Math.imul) {
  68962. self.Math.imul = function (a, b) {
  68963. var ah = (a >>> 16) & 0xffff;
  68964. var al = a & 0xffff;
  68965. var bh = (b >>> 16) & 0xffff;
  68966. var bl = b & 0xffff;
  68967. // the shift by 0 fixes the sign on the high part
  68968. // the final |0 converts the unsigned value into a signed value
  68969. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  68970. };
  68971. }
  68972. // Replace functions
  68973. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  68974. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  68975. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  68976. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  68977. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  68978. SIMDHelper._isEnabled = true;
  68979. };
  68980. SIMDHelper._isEnabled = false;
  68981. return SIMDHelper;
  68982. }());
  68983. BABYLON.SIMDHelper = SIMDHelper;
  68984. })(BABYLON || (BABYLON = {}));
  68985. //# sourceMappingURL=babylon.math.SIMD.js.map
  68986. var BABYLON;
  68987. (function (BABYLON) {
  68988. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  68989. __extends(VRDistortionCorrectionPostProcess, _super);
  68990. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  68991. var _this = _super.call(this, name, "vrDistortionCorrection", [
  68992. 'LensCenter',
  68993. 'Scale',
  68994. 'ScaleIn',
  68995. 'HmdWarpParam'
  68996. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  68997. _this._isRightEye = isRightEye;
  68998. _this._distortionFactors = vrMetrics.distortionK;
  68999. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  69000. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  69001. _this.adaptScaleToCurrentViewport = true;
  69002. _this.onSizeChangedObservable.add(function () {
  69003. _this.aspectRatio = _this.width * .5 / _this.height;
  69004. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  69005. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  69006. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  69007. });
  69008. _this.onApplyObservable.add(function (effect) {
  69009. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  69010. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  69011. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  69012. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  69013. });
  69014. return _this;
  69015. }
  69016. return VRDistortionCorrectionPostProcess;
  69017. }(BABYLON.PostProcess));
  69018. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  69019. })(BABYLON || (BABYLON = {}));
  69020. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  69021. var BABYLON;
  69022. (function (BABYLON) {
  69023. var AnaglyphPostProcess = /** @class */ (function (_super) {
  69024. __extends(AnaglyphPostProcess, _super);
  69025. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  69026. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  69027. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69028. _this.onApplyObservable.add(function (effect) {
  69029. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  69030. });
  69031. return _this;
  69032. }
  69033. return AnaglyphPostProcess;
  69034. }(BABYLON.PostProcess));
  69035. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  69036. })(BABYLON || (BABYLON = {}));
  69037. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  69038. var BABYLON;
  69039. (function (BABYLON) {
  69040. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  69041. __extends(StereoscopicInterlacePostProcess, _super);
  69042. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  69043. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  69044. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69045. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69046. _this.onSizeChangedObservable.add(function () {
  69047. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69048. });
  69049. _this.onApplyObservable.add(function (effect) {
  69050. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  69051. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  69052. });
  69053. return _this;
  69054. }
  69055. return StereoscopicInterlacePostProcess;
  69056. }(BABYLON.PostProcess));
  69057. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  69058. })(BABYLON || (BABYLON = {}));
  69059. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  69060. var BABYLON;
  69061. (function (BABYLON) {
  69062. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  69063. function FreeCameraDeviceOrientationInput() {
  69064. var _this = this;
  69065. this._screenOrientationAngle = 0;
  69066. this._screenQuaternion = new BABYLON.Quaternion();
  69067. this._alpha = 0;
  69068. this._beta = 0;
  69069. this._gamma = 0;
  69070. this._orientationChanged = function () {
  69071. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  69072. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  69073. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  69074. };
  69075. this._deviceOrientation = function (evt) {
  69076. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  69077. _this._beta = evt.beta !== null ? evt.beta : 0;
  69078. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  69079. };
  69080. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  69081. this._orientationChanged();
  69082. }
  69083. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  69084. get: function () {
  69085. return this._camera;
  69086. },
  69087. set: function (camera) {
  69088. this._camera = camera;
  69089. if (this._camera != null && !this._camera.rotationQuaternion) {
  69090. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  69091. }
  69092. },
  69093. enumerable: true,
  69094. configurable: true
  69095. });
  69096. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69097. window.addEventListener("orientationchange", this._orientationChanged);
  69098. window.addEventListener("deviceorientation", this._deviceOrientation);
  69099. //In certain cases, the attach control is called AFTER orientation was changed,
  69100. //So this is needed.
  69101. this._orientationChanged();
  69102. };
  69103. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  69104. window.removeEventListener("orientationchange", this._orientationChanged);
  69105. window.removeEventListener("deviceorientation", this._deviceOrientation);
  69106. };
  69107. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  69108. //if no device orientation provided, don't update the rotation.
  69109. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  69110. if (!this._alpha)
  69111. return;
  69112. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  69113. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  69114. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  69115. //Mirror on XY Plane
  69116. this._camera.rotationQuaternion.z *= -1;
  69117. this._camera.rotationQuaternion.w *= -1;
  69118. };
  69119. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  69120. return "FreeCameraDeviceOrientationInput";
  69121. };
  69122. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  69123. return "deviceOrientation";
  69124. };
  69125. return FreeCameraDeviceOrientationInput;
  69126. }());
  69127. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  69128. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  69129. })(BABYLON || (BABYLON = {}));
  69130. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  69131. var BABYLON;
  69132. (function (BABYLON) {
  69133. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  69134. function ArcRotateCameraVRDeviceOrientationInput() {
  69135. this.alphaCorrection = 1;
  69136. this.betaCorrection = 1;
  69137. this.gammaCorrection = 1;
  69138. this._alpha = 0;
  69139. this._beta = 0;
  69140. this._gamma = 0;
  69141. this._dirty = false;
  69142. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  69143. }
  69144. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69145. this.camera.attachControl(element, noPreventDefault);
  69146. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  69147. };
  69148. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  69149. if (evt.alpha !== null) {
  69150. this._alpha = +evt.alpha | 0;
  69151. }
  69152. if (evt.beta !== null) {
  69153. this._beta = +evt.beta | 0;
  69154. }
  69155. if (evt.gamma !== null) {
  69156. this._gamma = +evt.gamma | 0;
  69157. }
  69158. this._dirty = true;
  69159. };
  69160. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  69161. if (this._dirty) {
  69162. this._dirty = false;
  69163. if (this._gamma < 0) {
  69164. this._gamma = 180 + this._gamma;
  69165. }
  69166. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  69167. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  69168. }
  69169. };
  69170. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  69171. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  69172. };
  69173. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  69174. return "ArcRotateCameraVRDeviceOrientationInput";
  69175. };
  69176. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  69177. return "VRDeviceOrientation";
  69178. };
  69179. return ArcRotateCameraVRDeviceOrientationInput;
  69180. }());
  69181. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  69182. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  69183. })(BABYLON || (BABYLON = {}));
  69184. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  69185. var BABYLON;
  69186. (function (BABYLON) {
  69187. var VRCameraMetrics = /** @class */ (function () {
  69188. function VRCameraMetrics() {
  69189. this.compensateDistortion = true;
  69190. }
  69191. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  69192. get: function () {
  69193. return this.hResolution / (2 * this.vResolution);
  69194. },
  69195. enumerable: true,
  69196. configurable: true
  69197. });
  69198. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  69199. get: function () {
  69200. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  69201. },
  69202. enumerable: true,
  69203. configurable: true
  69204. });
  69205. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  69206. get: function () {
  69207. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69208. var h = (4 * meters) / this.hScreenSize;
  69209. return BABYLON.Matrix.Translation(h, 0, 0);
  69210. },
  69211. enumerable: true,
  69212. configurable: true
  69213. });
  69214. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  69215. get: function () {
  69216. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69217. var h = (4 * meters) / this.hScreenSize;
  69218. return BABYLON.Matrix.Translation(-h, 0, 0);
  69219. },
  69220. enumerable: true,
  69221. configurable: true
  69222. });
  69223. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  69224. get: function () {
  69225. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  69226. },
  69227. enumerable: true,
  69228. configurable: true
  69229. });
  69230. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  69231. get: function () {
  69232. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  69233. },
  69234. enumerable: true,
  69235. configurable: true
  69236. });
  69237. VRCameraMetrics.GetDefault = function () {
  69238. var result = new VRCameraMetrics();
  69239. result.hResolution = 1280;
  69240. result.vResolution = 800;
  69241. result.hScreenSize = 0.149759993;
  69242. result.vScreenSize = 0.0935999975;
  69243. result.vScreenCenter = 0.0467999987;
  69244. result.eyeToScreenDistance = 0.0410000011;
  69245. result.lensSeparationDistance = 0.0635000020;
  69246. result.interpupillaryDistance = 0.0640000030;
  69247. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  69248. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  69249. result.postProcessScaleFactor = 1.714605507808412;
  69250. result.lensCenterOffset = 0.151976421;
  69251. return result;
  69252. };
  69253. return VRCameraMetrics;
  69254. }());
  69255. BABYLON.VRCameraMetrics = VRCameraMetrics;
  69256. })(BABYLON || (BABYLON = {}));
  69257. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  69258. var BABYLON;
  69259. (function (BABYLON) {
  69260. var WebVRFreeCamera = /** @class */ (function (_super) {
  69261. __extends(WebVRFreeCamera, _super);
  69262. function WebVRFreeCamera(name, position, scene, webVROptions) {
  69263. if (webVROptions === void 0) { webVROptions = {}; }
  69264. var _this = _super.call(this, name, position, scene) || this;
  69265. _this.webVROptions = webVROptions;
  69266. _this._vrDevice = null;
  69267. _this.rawPose = null;
  69268. _this._specsVersion = "1.1";
  69269. _this._attached = false;
  69270. _this._descendants = [];
  69271. _this.devicePosition = BABYLON.Vector3.Zero();
  69272. _this.deviceScaleFactor = 1;
  69273. _this.controllers = [];
  69274. _this.onControllersAttachedObservable = new BABYLON.Observable();
  69275. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  69276. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  69277. _this.minZ = 0.1;
  69278. //legacy support - the compensation boolean was removed.
  69279. if (arguments.length === 5) {
  69280. _this.webVROptions = arguments[4];
  69281. }
  69282. // default webVR options
  69283. if (_this.webVROptions.trackPosition == undefined) {
  69284. _this.webVROptions.trackPosition = true;
  69285. }
  69286. if (_this.webVROptions.controllerMeshes == undefined) {
  69287. _this.webVROptions.controllerMeshes = true;
  69288. }
  69289. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  69290. _this.webVROptions.defaultLightingOnControllers = true;
  69291. }
  69292. _this.rotationQuaternion = new BABYLON.Quaternion();
  69293. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69294. if (_this.webVROptions && _this.webVROptions.positionScale) {
  69295. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  69296. }
  69297. //enable VR
  69298. var engine = _this.getEngine();
  69299. _this._onVREnabled = function (success) { if (success) {
  69300. _this.initControllers();
  69301. } };
  69302. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  69303. engine.initWebVR().add(function (event) {
  69304. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  69305. return;
  69306. }
  69307. _this._vrDevice = event.vrDisplay;
  69308. //reset the rig parameters.
  69309. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  69310. if (_this._attached) {
  69311. _this.getEngine().enableVR();
  69312. }
  69313. });
  69314. if (typeof (VRFrameData) !== "undefined")
  69315. _this._frameData = new VRFrameData();
  69316. /**
  69317. * The idea behind the following lines:
  69318. * objects that have the camera as parent should actually have the rig cameras as a parent.
  69319. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  69320. * the second will not show it correctly.
  69321. *
  69322. * To solve this - each object that has the camera as parent will be added to a protected array.
  69323. * When the rig camera renders, it will take this array and set all of those to be its children.
  69324. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  69325. * Amazing!
  69326. */
  69327. scene.onBeforeCameraRenderObservable.add(function (camera) {
  69328. if (camera.parent === _this && _this.rigParenting) {
  69329. _this._descendants = _this.getDescendants(true, function (n) {
  69330. // don't take the cameras or the controllers!
  69331. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  69332. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  69333. return !isController && !isRigCamera;
  69334. });
  69335. _this._descendants.forEach(function (node) {
  69336. node.parent = camera;
  69337. });
  69338. }
  69339. });
  69340. scene.onAfterCameraRenderObservable.add(function (camera) {
  69341. if (camera.parent === _this && _this.rigParenting) {
  69342. _this._descendants.forEach(function (node) {
  69343. node.parent = _this;
  69344. });
  69345. }
  69346. });
  69347. return _this;
  69348. }
  69349. WebVRFreeCamera.prototype.dispose = function () {
  69350. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  69351. _super.prototype.dispose.call(this);
  69352. };
  69353. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  69354. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  69355. var gp = _a[_i];
  69356. if (gp.hand === name) {
  69357. return gp;
  69358. }
  69359. }
  69360. return null;
  69361. };
  69362. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  69363. get: function () {
  69364. if (!this._leftController) {
  69365. this._leftController = this.getControllerByName("left");
  69366. }
  69367. return this._leftController;
  69368. },
  69369. enumerable: true,
  69370. configurable: true
  69371. });
  69372. ;
  69373. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  69374. get: function () {
  69375. if (!this._rightController) {
  69376. this._rightController = this.getControllerByName("right");
  69377. }
  69378. return this._rightController;
  69379. },
  69380. enumerable: true,
  69381. configurable: true
  69382. });
  69383. ;
  69384. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  69385. if (length === void 0) { length = 100; }
  69386. if (this.leftCamera) {
  69387. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  69388. }
  69389. else {
  69390. return _super.prototype.getForwardRay.call(this, length);
  69391. }
  69392. };
  69393. WebVRFreeCamera.prototype._checkInputs = function () {
  69394. if (this._vrDevice && this._vrDevice.isPresenting) {
  69395. this._vrDevice.getFrameData(this._frameData);
  69396. this.updateFromDevice(this._frameData.pose);
  69397. }
  69398. _super.prototype._checkInputs.call(this);
  69399. };
  69400. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  69401. if (poseData && poseData.orientation) {
  69402. this.rawPose = poseData;
  69403. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  69404. if (this.getScene().useRightHandedSystem) {
  69405. this.deviceRotationQuaternion.z *= -1;
  69406. this.deviceRotationQuaternion.w *= -1;
  69407. }
  69408. if (this.webVROptions.trackPosition && this.rawPose.position) {
  69409. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  69410. if (this.getScene().useRightHandedSystem) {
  69411. this.devicePosition.z *= -1;
  69412. }
  69413. }
  69414. }
  69415. };
  69416. /**
  69417. * WebVR's attach control will start broadcasting frames to the device.
  69418. * Note that in certain browsers (chrome for example) this function must be called
  69419. * within a user-interaction callback. Example:
  69420. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  69421. *
  69422. * @param {HTMLElement} element
  69423. * @param {boolean} [noPreventDefault]
  69424. *
  69425. * @memberOf WebVRFreeCamera
  69426. */
  69427. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  69428. _super.prototype.attachControl.call(this, element, noPreventDefault);
  69429. this._attached = true;
  69430. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  69431. if (this._vrDevice) {
  69432. this.getEngine().enableVR();
  69433. }
  69434. };
  69435. WebVRFreeCamera.prototype.detachControl = function (element) {
  69436. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69437. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69438. _super.prototype.detachControl.call(this, element);
  69439. this._attached = false;
  69440. this.getEngine().disableVR();
  69441. };
  69442. WebVRFreeCamera.prototype.getClassName = function () {
  69443. return "WebVRFreeCamera";
  69444. };
  69445. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  69446. //uses the vrDisplay's "resetPose()".
  69447. //pitch and roll won't be affected.
  69448. this._vrDevice.resetPose();
  69449. };
  69450. WebVRFreeCamera.prototype._updateRigCameras = function () {
  69451. var camLeft = this._rigCameras[0];
  69452. var camRight = this._rigCameras[1];
  69453. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69454. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69455. camLeft.position.copyFrom(this.devicePosition);
  69456. camRight.position.copyFrom(this.devicePosition);
  69457. };
  69458. /**
  69459. * This function is called by the two RIG cameras.
  69460. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  69461. */
  69462. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  69463. var _this = this;
  69464. //WebVR 1.1
  69465. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  69466. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  69467. if (!this.getScene().useRightHandedSystem) {
  69468. [2, 6, 8, 9, 14].forEach(function (num) {
  69469. _this._webvrViewMatrix.m[num] *= -1;
  69470. });
  69471. }
  69472. // update the camera rotation matrix
  69473. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  69474. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  69475. // Computing target and final matrix
  69476. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  69477. var parentCamera = this._cameraRigParams["parentCamera"];
  69478. // should the view matrix be updated with scale and position offset?
  69479. if (parentCamera.deviceScaleFactor !== 1) {
  69480. this._webvrViewMatrix.invert();
  69481. // scale the position, if set
  69482. if (parentCamera.deviceScaleFactor) {
  69483. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  69484. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  69485. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  69486. }
  69487. this._webvrViewMatrix.invert();
  69488. }
  69489. return this._webvrViewMatrix;
  69490. };
  69491. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  69492. var _this = this;
  69493. var parentCamera = this.parent;
  69494. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  69495. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  69496. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  69497. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  69498. //babylon compatible matrix
  69499. if (!this.getScene().useRightHandedSystem) {
  69500. [8, 9, 10, 11].forEach(function (num) {
  69501. _this._projectionMatrix.m[num] *= -1;
  69502. });
  69503. }
  69504. return this._projectionMatrix;
  69505. };
  69506. WebVRFreeCamera.prototype.initControllers = function () {
  69507. var _this = this;
  69508. this.controllers = [];
  69509. var manager = this.getScene().gamepadManager;
  69510. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69511. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69512. var webVrController = gamepad;
  69513. if (webVrController.defaultModel) {
  69514. webVrController.defaultModel.setEnabled(false);
  69515. }
  69516. }
  69517. });
  69518. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69519. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69520. var webVrController_1 = gamepad;
  69521. if (_this.webVROptions.controllerMeshes) {
  69522. if (webVrController_1.defaultModel) {
  69523. webVrController_1.defaultModel.setEnabled(true);
  69524. }
  69525. else {
  69526. // Load the meshes
  69527. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  69528. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  69529. if (_this.webVROptions.defaultLightingOnControllers) {
  69530. if (!_this._lightOnControllers) {
  69531. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  69532. }
  69533. var activateLightOnSubMeshes_1 = function (mesh, light) {
  69534. var children = mesh.getChildren();
  69535. if (children.length !== 0) {
  69536. children.forEach(function (mesh) {
  69537. light.includedOnlyMeshes.push(mesh);
  69538. activateLightOnSubMeshes_1(mesh, light);
  69539. });
  69540. }
  69541. };
  69542. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  69543. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  69544. }
  69545. });
  69546. }
  69547. }
  69548. webVrController_1.attachToPoseControlledCamera(_this);
  69549. // since this is async - sanity check. Is the controller already stored?
  69550. if (_this.controllers.indexOf(webVrController_1) === -1) {
  69551. //add to the controllers array
  69552. _this.controllers.push(webVrController_1);
  69553. //did we find enough controllers? Great! let the developer know.
  69554. if (_this.controllers.length >= 2) {
  69555. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  69556. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  69557. // So we're overriding setting left & right manually to be sure
  69558. var firstViveWandDetected = false;
  69559. for (var i = 0; i < _this.controllers.length; i++) {
  69560. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  69561. if (!firstViveWandDetected) {
  69562. firstViveWandDetected = true;
  69563. _this.controllers[i].hand = "left";
  69564. }
  69565. else {
  69566. _this.controllers[i].hand = "right";
  69567. }
  69568. }
  69569. }
  69570. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  69571. }
  69572. }
  69573. }
  69574. });
  69575. };
  69576. return WebVRFreeCamera;
  69577. }(BABYLON.FreeCamera));
  69578. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  69579. })(BABYLON || (BABYLON = {}));
  69580. //# sourceMappingURL=babylon.webVRCamera.js.map
  69581. var BABYLON;
  69582. (function (BABYLON) {
  69583. // We're mainly based on the logic defined into the FreeCamera code
  69584. var DeviceOrientationCamera = /** @class */ (function (_super) {
  69585. __extends(DeviceOrientationCamera, _super);
  69586. function DeviceOrientationCamera(name, position, scene) {
  69587. var _this = _super.call(this, name, position, scene) || this;
  69588. _this._quaternionCache = new BABYLON.Quaternion();
  69589. _this.inputs.addDeviceOrientation();
  69590. return _this;
  69591. }
  69592. DeviceOrientationCamera.prototype.getClassName = function () {
  69593. return "DeviceOrientationCamera";
  69594. };
  69595. DeviceOrientationCamera.prototype._checkInputs = function () {
  69596. _super.prototype._checkInputs.call(this);
  69597. this._quaternionCache.copyFrom(this.rotationQuaternion);
  69598. if (this._initialQuaternion) {
  69599. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69600. }
  69601. };
  69602. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  69603. var _this = this;
  69604. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  69605. //can only work if this camera has a rotation quaternion already.
  69606. if (!this.rotationQuaternion)
  69607. return;
  69608. if (!this._initialQuaternion) {
  69609. this._initialQuaternion = new BABYLON.Quaternion();
  69610. }
  69611. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  69612. ['x', 'y', 'z'].forEach(function (axisName) {
  69613. if (!axis[axisName]) {
  69614. _this._initialQuaternion[axisName] = 0;
  69615. }
  69616. else {
  69617. _this._initialQuaternion[axisName] *= -1;
  69618. }
  69619. });
  69620. this._initialQuaternion.normalize();
  69621. //force rotation update
  69622. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69623. };
  69624. return DeviceOrientationCamera;
  69625. }(BABYLON.FreeCamera));
  69626. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  69627. })(BABYLON || (BABYLON = {}));
  69628. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  69629. var BABYLON;
  69630. (function (BABYLON) {
  69631. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  69632. __extends(VRDeviceOrientationFreeCamera, _super);
  69633. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69634. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69635. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69636. var _this = _super.call(this, name, position, scene) || this;
  69637. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69638. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69639. return _this;
  69640. }
  69641. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  69642. return "VRDeviceOrientationFreeCamera";
  69643. };
  69644. return VRDeviceOrientationFreeCamera;
  69645. }(BABYLON.DeviceOrientationCamera));
  69646. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  69647. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  69648. __extends(VRDeviceOrientationGamepadCamera, _super);
  69649. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69650. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69651. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69652. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  69653. _this.inputs.addGamepad();
  69654. return _this;
  69655. }
  69656. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  69657. return "VRDeviceOrientationGamepadCamera";
  69658. };
  69659. return VRDeviceOrientationGamepadCamera;
  69660. }(VRDeviceOrientationFreeCamera));
  69661. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  69662. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  69663. __extends(VRDeviceOrientationArcRotateCamera, _super);
  69664. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  69665. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69666. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69667. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69668. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69669. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69670. _this.inputs.addVRDeviceOrientation();
  69671. return _this;
  69672. }
  69673. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  69674. return "VRDeviceOrientationArcRotateCamera";
  69675. };
  69676. return VRDeviceOrientationArcRotateCamera;
  69677. }(BABYLON.ArcRotateCamera));
  69678. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  69679. })(BABYLON || (BABYLON = {}));
  69680. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  69681. var BABYLON;
  69682. (function (BABYLON) {
  69683. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  69684. __extends(AnaglyphFreeCamera, _super);
  69685. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  69686. var _this = _super.call(this, name, position, scene) || this;
  69687. _this.interaxialDistance = interaxialDistance;
  69688. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69689. return _this;
  69690. }
  69691. AnaglyphFreeCamera.prototype.getClassName = function () {
  69692. return "AnaglyphFreeCamera";
  69693. };
  69694. return AnaglyphFreeCamera;
  69695. }(BABYLON.FreeCamera));
  69696. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  69697. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  69698. __extends(AnaglyphArcRotateCamera, _super);
  69699. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  69700. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69701. _this.interaxialDistance = interaxialDistance;
  69702. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69703. return _this;
  69704. }
  69705. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  69706. return "AnaglyphArcRotateCamera";
  69707. };
  69708. return AnaglyphArcRotateCamera;
  69709. }(BABYLON.ArcRotateCamera));
  69710. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  69711. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  69712. __extends(AnaglyphGamepadCamera, _super);
  69713. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  69714. var _this = _super.call(this, name, position, scene) || this;
  69715. _this.interaxialDistance = interaxialDistance;
  69716. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69717. return _this;
  69718. }
  69719. AnaglyphGamepadCamera.prototype.getClassName = function () {
  69720. return "AnaglyphGamepadCamera";
  69721. };
  69722. return AnaglyphGamepadCamera;
  69723. }(BABYLON.GamepadCamera));
  69724. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  69725. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  69726. __extends(AnaglyphUniversalCamera, _super);
  69727. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  69728. var _this = _super.call(this, name, position, scene) || this;
  69729. _this.interaxialDistance = interaxialDistance;
  69730. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69731. return _this;
  69732. }
  69733. AnaglyphUniversalCamera.prototype.getClassName = function () {
  69734. return "AnaglyphUniversalCamera";
  69735. };
  69736. return AnaglyphUniversalCamera;
  69737. }(BABYLON.UniversalCamera));
  69738. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  69739. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  69740. __extends(StereoscopicFreeCamera, _super);
  69741. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69742. var _this = _super.call(this, name, position, scene) || this;
  69743. _this.interaxialDistance = interaxialDistance;
  69744. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69745. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69746. return _this;
  69747. }
  69748. StereoscopicFreeCamera.prototype.getClassName = function () {
  69749. return "StereoscopicFreeCamera";
  69750. };
  69751. return StereoscopicFreeCamera;
  69752. }(BABYLON.FreeCamera));
  69753. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  69754. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  69755. __extends(StereoscopicArcRotateCamera, _super);
  69756. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  69757. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69758. _this.interaxialDistance = interaxialDistance;
  69759. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69760. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69761. return _this;
  69762. }
  69763. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  69764. return "StereoscopicArcRotateCamera";
  69765. };
  69766. return StereoscopicArcRotateCamera;
  69767. }(BABYLON.ArcRotateCamera));
  69768. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  69769. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  69770. __extends(StereoscopicGamepadCamera, _super);
  69771. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69772. var _this = _super.call(this, name, position, scene) || this;
  69773. _this.interaxialDistance = interaxialDistance;
  69774. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69775. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69776. return _this;
  69777. }
  69778. StereoscopicGamepadCamera.prototype.getClassName = function () {
  69779. return "StereoscopicGamepadCamera";
  69780. };
  69781. return StereoscopicGamepadCamera;
  69782. }(BABYLON.GamepadCamera));
  69783. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  69784. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  69785. __extends(StereoscopicUniversalCamera, _super);
  69786. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69787. var _this = _super.call(this, name, position, scene) || this;
  69788. _this.interaxialDistance = interaxialDistance;
  69789. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69790. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69791. return _this;
  69792. }
  69793. StereoscopicUniversalCamera.prototype.getClassName = function () {
  69794. return "StereoscopicUniversalCamera";
  69795. };
  69796. return StereoscopicUniversalCamera;
  69797. }(BABYLON.UniversalCamera));
  69798. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  69799. })(BABYLON || (BABYLON = {}));
  69800. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  69801. var BABYLON;
  69802. (function (BABYLON) {
  69803. var VRExperienceHelper = /** @class */ (function () {
  69804. function VRExperienceHelper(scene, webVROptions) {
  69805. if (webVROptions === void 0) { webVROptions = {}; }
  69806. var _this = this;
  69807. this.webVROptions = webVROptions;
  69808. // Can the system support WebVR, even if a headset isn't plugged in?
  69809. this._webVRsupported = false;
  69810. // If WebVR is supported, is a headset plugged in and are we ready to present?
  69811. this._webVRready = false;
  69812. // Are we waiting for the requestPresent callback to complete?
  69813. this._webVRrequesting = false;
  69814. // Are we presenting to the headset right now?
  69815. this._webVRpresenting = false;
  69816. // Are we presenting in the fullscreen fallback?
  69817. this._fullscreenVRpresenting = false;
  69818. this._scene = scene;
  69819. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  69820. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  69821. }
  69822. else {
  69823. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  69824. if (scene.activeCamera.rotation) {
  69825. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  69826. }
  69827. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  69828. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  69829. }
  69830. this._scene.activeCamera = this._deviceOrientationCamera;
  69831. this._position = this._scene.activeCamera.position;
  69832. this._canvas = scene.getEngine().getRenderingCanvas();
  69833. if (this._canvas) {
  69834. this._scene.activeCamera.attachControl(this._canvas);
  69835. }
  69836. this._btnVR = document.createElement("BUTTON");
  69837. this._btnVR.className = "babylonVRicon";
  69838. this._btnVR.id = "babylonVRiconbtn";
  69839. this._btnVR.title = "Click to switch to VR";
  69840. 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) }";
  69841. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  69842. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  69843. // css += ".babylonVRicon.vrdisplaysupported { }";
  69844. // css += ".babylonVRicon.vrdisplayready { }";
  69845. // css += ".babylonVRicon.vrdisplayrequesting { }";
  69846. var style = document.createElement('style');
  69847. style.appendChild(document.createTextNode(css));
  69848. document.getElementsByTagName('head')[0].appendChild(style);
  69849. if (this._canvas) {
  69850. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69851. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69852. this._btnVR.addEventListener("click", function () {
  69853. _this.enterVR();
  69854. });
  69855. window.addEventListener("resize", function () {
  69856. if (_this._canvas) {
  69857. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  69858. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  69859. }
  69860. if (_this._fullscreenVRpresenting && _this._webVRready) {
  69861. _this.exitVR();
  69862. }
  69863. });
  69864. }
  69865. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69866. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69867. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69868. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69869. document.body.appendChild(this._btnVR);
  69870. // Exiting VR mode using 'ESC' key on desktop
  69871. this._onKeyDown = function (event) {
  69872. if (event.keyCode === 27 && _this.isInVRMode()) {
  69873. _this.exitVR();
  69874. }
  69875. };
  69876. document.addEventListener("keydown", this._onKeyDown);
  69877. // Exiting VR mode double tapping the touch screen
  69878. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  69879. if (_this.isInVRMode()) {
  69880. _this.exitVR();
  69881. if (_this._fullscreenVRpresenting) {
  69882. _this._scene.getEngine().switchFullscreen(true);
  69883. }
  69884. }
  69885. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  69886. // Listen for WebVR display changes
  69887. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  69888. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  69889. this._onVRRequestPresentStart = function () {
  69890. _this._webVRrequesting = true;
  69891. _this.updateButtonVisibility();
  69892. };
  69893. this._onVRRequestPresentComplete = function (success) {
  69894. _this._webVRrequesting = false;
  69895. _this.updateButtonVisibility();
  69896. };
  69897. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  69898. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  69899. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  69900. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69901. // Create the cameras
  69902. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  69903. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  69904. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  69905. this.updateButtonVisibility();
  69906. }
  69907. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  69908. if (this.onControllerMeshLoaded) {
  69909. this.onControllerMeshLoaded(webVRController);
  69910. }
  69911. };
  69912. VRExperienceHelper.prototype._onFullscreenChange = function () {
  69913. if (document.fullscreen !== undefined) {
  69914. this._fullscreenVRpresenting = document.fullscreen;
  69915. }
  69916. else if (document.mozFullScreen !== undefined) {
  69917. this._fullscreenVRpresenting = document.mozFullScreen;
  69918. }
  69919. else if (document.webkitIsFullScreen !== undefined) {
  69920. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  69921. }
  69922. else if (document.msIsFullScreen !== undefined) {
  69923. this._fullscreenVRpresenting = document.msIsFullScreen;
  69924. }
  69925. if (!this._fullscreenVRpresenting && this._canvas) {
  69926. this.exitVR();
  69927. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69928. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69929. }
  69930. };
  69931. VRExperienceHelper.prototype.isInVRMode = function () {
  69932. return this._webVRpresenting || this._fullscreenVRpresenting;
  69933. };
  69934. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  69935. var vrDisplay = this._scene.getEngine().getVRDevice();
  69936. if (vrDisplay) {
  69937. var wasPresenting = this._webVRpresenting;
  69938. // A VR display is connected
  69939. this._webVRpresenting = vrDisplay.isPresenting;
  69940. if (wasPresenting && !this._webVRpresenting)
  69941. this.exitVR();
  69942. }
  69943. else {
  69944. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  69945. }
  69946. this.updateButtonVisibility();
  69947. };
  69948. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  69949. this._webVRsupported = eventArgs.vrSupported;
  69950. this._webVRready = !!eventArgs.vrDisplay;
  69951. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  69952. this.updateButtonVisibility();
  69953. };
  69954. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  69955. if (!this._btnVR) {
  69956. return;
  69957. }
  69958. this._btnVR.className = "babylonVRicon";
  69959. if (this.isInVRMode()) {
  69960. this._btnVR.className += " vrdisplaypresenting";
  69961. }
  69962. else {
  69963. if (this._webVRready)
  69964. this._btnVR.className += " vrdisplayready";
  69965. if (this._webVRsupported)
  69966. this._btnVR.className += " vrdisplaysupported";
  69967. if (this._webVRrequesting)
  69968. this._btnVR.className += " vrdisplayrequesting";
  69969. }
  69970. };
  69971. /**
  69972. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  69973. * Otherwise, will use the fullscreen API.
  69974. */
  69975. VRExperienceHelper.prototype.enterVR = function () {
  69976. if (this.onEnteringVR) {
  69977. this.onEnteringVR();
  69978. }
  69979. if (this._webVRrequesting)
  69980. return;
  69981. // If WebVR is supported and a headset is connected
  69982. if (this._webVRready) {
  69983. if (!this._webVRpresenting) {
  69984. this._webVRCamera.position = this._position;
  69985. this._scene.activeCamera = this._webVRCamera;
  69986. }
  69987. }
  69988. else {
  69989. this._vrDeviceOrientationCamera.position = this._position;
  69990. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  69991. this._scene.getEngine().switchFullscreen(true);
  69992. this.updateButtonVisibility();
  69993. }
  69994. if (this._scene.activeCamera && this._canvas) {
  69995. this._scene.activeCamera.attachControl(this._canvas);
  69996. }
  69997. };
  69998. /**
  69999. * Attempt to exit VR, or fullscreen.
  70000. */
  70001. VRExperienceHelper.prototype.exitVR = function () {
  70002. if (this.onExitingVR) {
  70003. this.onExitingVR();
  70004. }
  70005. if (this._webVRpresenting) {
  70006. this._scene.getEngine().disableVR();
  70007. }
  70008. if (this._scene.activeCamera) {
  70009. this._position = this._scene.activeCamera.position;
  70010. }
  70011. this._deviceOrientationCamera.position = this._position;
  70012. this._scene.activeCamera = this._deviceOrientationCamera;
  70013. if (this._canvas) {
  70014. this._scene.activeCamera.attachControl(this._canvas);
  70015. }
  70016. this.updateButtonVisibility();
  70017. };
  70018. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  70019. get: function () {
  70020. return this._position;
  70021. },
  70022. set: function (value) {
  70023. this._position = value;
  70024. if (this._scene.activeCamera) {
  70025. this._scene.activeCamera.position = value;
  70026. }
  70027. },
  70028. enumerable: true,
  70029. configurable: true
  70030. });
  70031. VRExperienceHelper.prototype.dispose = function () {
  70032. if (this.isInVRMode()) {
  70033. this.exitVR();
  70034. }
  70035. this._deviceOrientationCamera.dispose();
  70036. if (this._webVRCamera) {
  70037. this._webVRCamera.dispose();
  70038. }
  70039. if (this._vrDeviceOrientationCamera) {
  70040. this._vrDeviceOrientationCamera.dispose();
  70041. }
  70042. document.body.removeChild(this._btnVR);
  70043. document.removeEventListener("keydown", this._onKeyDown);
  70044. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70045. };
  70046. VRExperienceHelper.prototype.getClassName = function () {
  70047. return "VRExperienceHelper";
  70048. };
  70049. return VRExperienceHelper;
  70050. }());
  70051. BABYLON.VRExperienceHelper = VRExperienceHelper;
  70052. })(BABYLON || (BABYLON = {}));
  70053. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  70054. // Mainly based on these 2 articles :
  70055. // 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
  70056. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  70057. var BABYLON;
  70058. (function (BABYLON) {
  70059. var JoystickAxis;
  70060. (function (JoystickAxis) {
  70061. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  70062. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  70063. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  70064. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  70065. var VirtualJoystick = /** @class */ (function () {
  70066. function VirtualJoystick(leftJoystick) {
  70067. var _this = this;
  70068. if (leftJoystick) {
  70069. this._leftJoystick = true;
  70070. }
  70071. else {
  70072. this._leftJoystick = false;
  70073. }
  70074. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  70075. VirtualJoystick._globalJoystickIndex++;
  70076. // By default left & right arrow keys are moving the X
  70077. // and up & down keys are moving the Y
  70078. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70079. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70080. this.reverseLeftRight = false;
  70081. this.reverseUpDown = false;
  70082. // collections of pointers
  70083. this._touches = new BABYLON.StringDictionary();
  70084. this.deltaPosition = BABYLON.Vector3.Zero();
  70085. this._joystickSensibility = 25;
  70086. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70087. this._rotationSpeed = 25;
  70088. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  70089. this._rotateOnAxisRelativeToMesh = false;
  70090. this._onResize = function (evt) {
  70091. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70092. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70093. if (VirtualJoystick.vjCanvas) {
  70094. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  70095. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  70096. }
  70097. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  70098. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  70099. };
  70100. // injecting a canvas element on top of the canvas 3D game
  70101. if (!VirtualJoystick.vjCanvas) {
  70102. window.addEventListener("resize", this._onResize, false);
  70103. VirtualJoystick.vjCanvas = document.createElement("canvas");
  70104. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70105. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70106. VirtualJoystick.vjCanvas.width = window.innerWidth;
  70107. VirtualJoystick.vjCanvas.height = window.innerHeight;
  70108. VirtualJoystick.vjCanvas.style.width = "100%";
  70109. VirtualJoystick.vjCanvas.style.height = "100%";
  70110. VirtualJoystick.vjCanvas.style.position = "absolute";
  70111. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  70112. VirtualJoystick.vjCanvas.style.top = "0px";
  70113. VirtualJoystick.vjCanvas.style.left = "0px";
  70114. VirtualJoystick.vjCanvas.style.zIndex = "5";
  70115. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  70116. // Support for jQuery PEP polyfill
  70117. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  70118. var context = VirtualJoystick.vjCanvas.getContext('2d');
  70119. if (!context) {
  70120. throw new Error("Unable to create canvas for virtual joystick");
  70121. }
  70122. VirtualJoystick.vjCanvasContext = context;
  70123. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  70124. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70125. document.body.appendChild(VirtualJoystick.vjCanvas);
  70126. }
  70127. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  70128. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  70129. this.pressed = false;
  70130. // default joystick color
  70131. this._joystickColor = "cyan";
  70132. this._joystickPointerID = -1;
  70133. // current joystick position
  70134. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  70135. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  70136. // origin joystick position
  70137. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  70138. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  70139. this._onPointerDownHandlerRef = function (evt) {
  70140. _this._onPointerDown(evt);
  70141. };
  70142. this._onPointerMoveHandlerRef = function (evt) {
  70143. _this._onPointerMove(evt);
  70144. };
  70145. this._onPointerOutHandlerRef = function (evt) {
  70146. _this._onPointerUp(evt);
  70147. };
  70148. this._onPointerUpHandlerRef = function (evt) {
  70149. _this._onPointerUp(evt);
  70150. };
  70151. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  70152. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  70153. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  70154. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  70155. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  70156. evt.preventDefault(); // Disables system menu
  70157. }, false);
  70158. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70159. }
  70160. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  70161. this._joystickSensibility = newJoystickSensibility;
  70162. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70163. };
  70164. VirtualJoystick.prototype._onPointerDown = function (e) {
  70165. var positionOnScreenCondition;
  70166. e.preventDefault();
  70167. if (this._leftJoystick === true) {
  70168. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  70169. }
  70170. else {
  70171. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  70172. }
  70173. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  70174. // First contact will be dedicated to the virtual joystick
  70175. this._joystickPointerID = e.pointerId;
  70176. this._joystickPointerStartPos.x = e.clientX;
  70177. this._joystickPointerStartPos.y = e.clientY;
  70178. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  70179. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  70180. this._deltaJoystickVector.x = 0;
  70181. this._deltaJoystickVector.y = 0;
  70182. this.pressed = true;
  70183. this._touches.add(e.pointerId.toString(), e);
  70184. }
  70185. else {
  70186. // You can only trigger the action buttons with a joystick declared
  70187. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  70188. this._action();
  70189. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  70190. }
  70191. }
  70192. };
  70193. VirtualJoystick.prototype._onPointerMove = function (e) {
  70194. // If the current pointer is the one associated to the joystick (first touch contact)
  70195. if (this._joystickPointerID == e.pointerId) {
  70196. this._joystickPointerPos.x = e.clientX;
  70197. this._joystickPointerPos.y = e.clientY;
  70198. this._deltaJoystickVector = this._joystickPointerPos.clone();
  70199. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  70200. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  70201. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  70202. switch (this._axisTargetedByLeftAndRight) {
  70203. case JoystickAxis.X:
  70204. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  70205. break;
  70206. case JoystickAxis.Y:
  70207. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  70208. break;
  70209. case JoystickAxis.Z:
  70210. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  70211. break;
  70212. }
  70213. var directionUpDown = this.reverseUpDown ? 1 : -1;
  70214. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  70215. switch (this._axisTargetedByUpAndDown) {
  70216. case JoystickAxis.X:
  70217. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  70218. break;
  70219. case JoystickAxis.Y:
  70220. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  70221. break;
  70222. case JoystickAxis.Z:
  70223. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  70224. break;
  70225. }
  70226. }
  70227. else {
  70228. var data = this._touches.get(e.pointerId.toString());
  70229. if (data) {
  70230. data.x = e.clientX;
  70231. data.y = e.clientY;
  70232. }
  70233. }
  70234. };
  70235. VirtualJoystick.prototype._onPointerUp = function (e) {
  70236. if (this._joystickPointerID == e.pointerId) {
  70237. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  70238. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  70239. this._joystickPointerID = -1;
  70240. this.pressed = false;
  70241. }
  70242. else {
  70243. var touch = this._touches.get(e.pointerId.toString());
  70244. if (touch) {
  70245. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70246. }
  70247. }
  70248. this._deltaJoystickVector.x = 0;
  70249. this._deltaJoystickVector.y = 0;
  70250. this._touches.remove(e.pointerId.toString());
  70251. };
  70252. /**
  70253. * Change the color of the virtual joystick
  70254. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  70255. */
  70256. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  70257. this._joystickColor = newColor;
  70258. };
  70259. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  70260. this._action = action;
  70261. };
  70262. // Define which axis you'd like to control for left & right
  70263. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  70264. switch (axis) {
  70265. case JoystickAxis.X:
  70266. case JoystickAxis.Y:
  70267. case JoystickAxis.Z:
  70268. this._axisTargetedByLeftAndRight = axis;
  70269. break;
  70270. default:
  70271. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70272. break;
  70273. }
  70274. };
  70275. // Define which axis you'd like to control for up & down
  70276. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  70277. switch (axis) {
  70278. case JoystickAxis.X:
  70279. case JoystickAxis.Y:
  70280. case JoystickAxis.Z:
  70281. this._axisTargetedByUpAndDown = axis;
  70282. break;
  70283. default:
  70284. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70285. break;
  70286. }
  70287. };
  70288. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  70289. var _this = this;
  70290. if (this.pressed) {
  70291. this._touches.forEach(function (key, touch) {
  70292. if (touch.pointerId === _this._joystickPointerID) {
  70293. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  70294. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  70295. VirtualJoystick.vjCanvasContext.beginPath();
  70296. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70297. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70298. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  70299. VirtualJoystick.vjCanvasContext.stroke();
  70300. VirtualJoystick.vjCanvasContext.closePath();
  70301. VirtualJoystick.vjCanvasContext.beginPath();
  70302. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70303. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70304. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  70305. VirtualJoystick.vjCanvasContext.stroke();
  70306. VirtualJoystick.vjCanvasContext.closePath();
  70307. VirtualJoystick.vjCanvasContext.beginPath();
  70308. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70309. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  70310. VirtualJoystick.vjCanvasContext.stroke();
  70311. VirtualJoystick.vjCanvasContext.closePath();
  70312. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  70313. }
  70314. else {
  70315. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70316. VirtualJoystick.vjCanvasContext.beginPath();
  70317. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  70318. VirtualJoystick.vjCanvasContext.beginPath();
  70319. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  70320. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70321. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  70322. VirtualJoystick.vjCanvasContext.stroke();
  70323. VirtualJoystick.vjCanvasContext.closePath();
  70324. touch.prevX = touch.x;
  70325. touch.prevY = touch.y;
  70326. }
  70327. ;
  70328. });
  70329. }
  70330. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70331. };
  70332. VirtualJoystick.prototype.releaseCanvas = function () {
  70333. if (VirtualJoystick.vjCanvas) {
  70334. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  70335. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  70336. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  70337. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  70338. window.removeEventListener("resize", this._onResize);
  70339. document.body.removeChild(VirtualJoystick.vjCanvas);
  70340. VirtualJoystick.vjCanvas = null;
  70341. }
  70342. };
  70343. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  70344. VirtualJoystick._globalJoystickIndex = 0;
  70345. return VirtualJoystick;
  70346. }());
  70347. BABYLON.VirtualJoystick = VirtualJoystick;
  70348. })(BABYLON || (BABYLON = {}));
  70349. //# sourceMappingURL=babylon.virtualJoystick.js.map
  70350. var BABYLON;
  70351. (function (BABYLON) {
  70352. // We're mainly based on the logic defined into the FreeCamera code
  70353. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  70354. __extends(VirtualJoysticksCamera, _super);
  70355. function VirtualJoysticksCamera(name, position, scene) {
  70356. var _this = _super.call(this, name, position, scene) || this;
  70357. _this.inputs.addVirtualJoystick();
  70358. return _this;
  70359. }
  70360. VirtualJoysticksCamera.prototype.getClassName = function () {
  70361. return "VirtualJoysticksCamera";
  70362. };
  70363. return VirtualJoysticksCamera;
  70364. }(BABYLON.FreeCamera));
  70365. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  70366. })(BABYLON || (BABYLON = {}));
  70367. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  70368. var BABYLON;
  70369. (function (BABYLON) {
  70370. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  70371. function FreeCameraVirtualJoystickInput() {
  70372. }
  70373. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  70374. return this._leftjoystick;
  70375. };
  70376. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  70377. return this._rightjoystick;
  70378. };
  70379. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  70380. if (this._leftjoystick) {
  70381. var camera = this.camera;
  70382. var speed = camera._computeLocalCameraSpeed() * 50;
  70383. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  70384. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  70385. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  70386. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  70387. if (!this._leftjoystick.pressed) {
  70388. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  70389. }
  70390. if (!this._rightjoystick.pressed) {
  70391. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  70392. }
  70393. }
  70394. };
  70395. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  70396. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  70397. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  70398. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  70399. this._leftjoystick.setJoystickSensibility(0.15);
  70400. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  70401. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  70402. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  70403. this._rightjoystick.reverseUpDown = true;
  70404. this._rightjoystick.setJoystickSensibility(0.05);
  70405. this._rightjoystick.setJoystickColor("yellow");
  70406. };
  70407. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  70408. this._leftjoystick.releaseCanvas();
  70409. this._rightjoystick.releaseCanvas();
  70410. };
  70411. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  70412. return "FreeCameraVirtualJoystickInput";
  70413. };
  70414. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  70415. return "virtualJoystick";
  70416. };
  70417. return FreeCameraVirtualJoystickInput;
  70418. }());
  70419. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  70420. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  70421. })(BABYLON || (BABYLON = {}));
  70422. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  70423. var BABYLON;
  70424. (function (BABYLON) {
  70425. var SimplificationSettings = /** @class */ (function () {
  70426. function SimplificationSettings(quality, distance, optimizeMesh) {
  70427. this.quality = quality;
  70428. this.distance = distance;
  70429. this.optimizeMesh = optimizeMesh;
  70430. }
  70431. return SimplificationSettings;
  70432. }());
  70433. BABYLON.SimplificationSettings = SimplificationSettings;
  70434. var SimplificationQueue = /** @class */ (function () {
  70435. function SimplificationQueue() {
  70436. this.running = false;
  70437. this._simplificationArray = [];
  70438. }
  70439. SimplificationQueue.prototype.addTask = function (task) {
  70440. this._simplificationArray.push(task);
  70441. };
  70442. SimplificationQueue.prototype.executeNext = function () {
  70443. var task = this._simplificationArray.pop();
  70444. if (task) {
  70445. this.running = true;
  70446. this.runSimplification(task);
  70447. }
  70448. else {
  70449. this.running = false;
  70450. }
  70451. };
  70452. SimplificationQueue.prototype.runSimplification = function (task) {
  70453. var _this = this;
  70454. if (task.parallelProcessing) {
  70455. //parallel simplifier
  70456. task.settings.forEach(function (setting) {
  70457. var simplifier = _this.getSimplifier(task);
  70458. simplifier.simplify(setting, function (newMesh) {
  70459. task.mesh.addLODLevel(setting.distance, newMesh);
  70460. newMesh.isVisible = true;
  70461. //check if it is the last
  70462. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  70463. //all done, run the success callback.
  70464. task.successCallback();
  70465. }
  70466. _this.executeNext();
  70467. });
  70468. });
  70469. }
  70470. else {
  70471. //single simplifier.
  70472. var simplifier = this.getSimplifier(task);
  70473. var runDecimation = function (setting, callback) {
  70474. simplifier.simplify(setting, function (newMesh) {
  70475. task.mesh.addLODLevel(setting.distance, newMesh);
  70476. newMesh.isVisible = true;
  70477. //run the next quality level
  70478. callback();
  70479. });
  70480. };
  70481. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  70482. runDecimation(task.settings[loop.index], function () {
  70483. loop.executeNext();
  70484. });
  70485. }, function () {
  70486. //execution ended, run the success callback.
  70487. if (task.successCallback) {
  70488. task.successCallback();
  70489. }
  70490. _this.executeNext();
  70491. });
  70492. }
  70493. };
  70494. SimplificationQueue.prototype.getSimplifier = function (task) {
  70495. switch (task.simplificationType) {
  70496. case SimplificationType.QUADRATIC:
  70497. default:
  70498. return new QuadraticErrorSimplification(task.mesh);
  70499. }
  70500. };
  70501. return SimplificationQueue;
  70502. }());
  70503. BABYLON.SimplificationQueue = SimplificationQueue;
  70504. /**
  70505. * The implemented types of simplification.
  70506. * At the moment only Quadratic Error Decimation is implemented.
  70507. */
  70508. var SimplificationType;
  70509. (function (SimplificationType) {
  70510. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  70511. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  70512. var DecimationTriangle = /** @class */ (function () {
  70513. function DecimationTriangle(vertices) {
  70514. this.vertices = vertices;
  70515. this.error = new Array(4);
  70516. this.deleted = false;
  70517. this.isDirty = false;
  70518. this.deletePending = false;
  70519. this.borderFactor = 0;
  70520. }
  70521. return DecimationTriangle;
  70522. }());
  70523. BABYLON.DecimationTriangle = DecimationTriangle;
  70524. var DecimationVertex = /** @class */ (function () {
  70525. function DecimationVertex(position, id) {
  70526. this.position = position;
  70527. this.id = id;
  70528. this.isBorder = true;
  70529. this.q = new QuadraticMatrix();
  70530. this.triangleCount = 0;
  70531. this.triangleStart = 0;
  70532. this.originalOffsets = [];
  70533. }
  70534. DecimationVertex.prototype.updatePosition = function (newPosition) {
  70535. this.position.copyFrom(newPosition);
  70536. };
  70537. return DecimationVertex;
  70538. }());
  70539. BABYLON.DecimationVertex = DecimationVertex;
  70540. var QuadraticMatrix = /** @class */ (function () {
  70541. function QuadraticMatrix(data) {
  70542. this.data = new Array(10);
  70543. for (var i = 0; i < 10; ++i) {
  70544. if (data && data[i]) {
  70545. this.data[i] = data[i];
  70546. }
  70547. else {
  70548. this.data[i] = 0;
  70549. }
  70550. }
  70551. }
  70552. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  70553. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  70554. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  70555. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  70556. return det;
  70557. };
  70558. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  70559. for (var i = 0; i < 10; ++i) {
  70560. this.data[i] += matrix.data[i];
  70561. }
  70562. };
  70563. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  70564. for (var i = 0; i < 10; ++i) {
  70565. this.data[i] += data[i];
  70566. }
  70567. };
  70568. QuadraticMatrix.prototype.add = function (matrix) {
  70569. var m = new QuadraticMatrix();
  70570. for (var i = 0; i < 10; ++i) {
  70571. m.data[i] = this.data[i] + matrix.data[i];
  70572. }
  70573. return m;
  70574. };
  70575. QuadraticMatrix.FromData = function (a, b, c, d) {
  70576. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  70577. };
  70578. //returning an array to avoid garbage collection
  70579. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  70580. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  70581. };
  70582. return QuadraticMatrix;
  70583. }());
  70584. BABYLON.QuadraticMatrix = QuadraticMatrix;
  70585. var Reference = /** @class */ (function () {
  70586. function Reference(vertexId, triangleId) {
  70587. this.vertexId = vertexId;
  70588. this.triangleId = triangleId;
  70589. }
  70590. return Reference;
  70591. }());
  70592. BABYLON.Reference = Reference;
  70593. /**
  70594. * An implementation of the Quadratic Error simplification algorithm.
  70595. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  70596. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  70597. * @author RaananW
  70598. */
  70599. var QuadraticErrorSimplification = /** @class */ (function () {
  70600. function QuadraticErrorSimplification(_mesh) {
  70601. this._mesh = _mesh;
  70602. this.initialized = false;
  70603. this.syncIterations = 5000;
  70604. this.aggressiveness = 7;
  70605. this.decimationIterations = 100;
  70606. this.boundingBoxEpsilon = BABYLON.Epsilon;
  70607. }
  70608. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  70609. var _this = this;
  70610. this.initDecimatedMesh();
  70611. //iterating through the submeshes array, one after the other.
  70612. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  70613. _this.initWithMesh(loop.index, function () {
  70614. _this.runDecimation(settings, loop.index, function () {
  70615. loop.executeNext();
  70616. });
  70617. }, settings.optimizeMesh);
  70618. }, function () {
  70619. setTimeout(function () {
  70620. successCallback(_this._reconstructedMesh);
  70621. }, 0);
  70622. });
  70623. };
  70624. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  70625. var _this = this;
  70626. var targetCount = ~~(this.triangles.length * settings.quality);
  70627. var deletedTriangles = 0;
  70628. var triangleCount = this.triangles.length;
  70629. var iterationFunction = function (iteration, callback) {
  70630. setTimeout(function () {
  70631. if (iteration % 5 === 0) {
  70632. _this.updateMesh(iteration === 0);
  70633. }
  70634. for (var i = 0; i < _this.triangles.length; ++i) {
  70635. _this.triangles[i].isDirty = false;
  70636. }
  70637. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  70638. var trianglesIterator = function (i) {
  70639. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  70640. var t = _this.triangles[tIdx];
  70641. if (!t)
  70642. return;
  70643. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  70644. return;
  70645. }
  70646. for (var j = 0; j < 3; ++j) {
  70647. if (t.error[j] < threshold) {
  70648. var deleted0 = [];
  70649. var deleted1 = [];
  70650. var v0 = t.vertices[j];
  70651. var v1 = t.vertices[(j + 1) % 3];
  70652. if (v0.isBorder || v1.isBorder)
  70653. continue;
  70654. var p = BABYLON.Vector3.Zero();
  70655. var n = BABYLON.Vector3.Zero();
  70656. var uv = BABYLON.Vector2.Zero();
  70657. var color = new BABYLON.Color4(0, 0, 0, 1);
  70658. _this.calculateError(v0, v1, p, n, uv, color);
  70659. var delTr = new Array();
  70660. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  70661. continue;
  70662. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  70663. continue;
  70664. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  70665. continue;
  70666. var uniqueArray = new Array();
  70667. delTr.forEach(function (deletedT) {
  70668. if (uniqueArray.indexOf(deletedT) === -1) {
  70669. deletedT.deletePending = true;
  70670. uniqueArray.push(deletedT);
  70671. }
  70672. });
  70673. if (uniqueArray.length % 2 !== 0) {
  70674. continue;
  70675. }
  70676. v0.q = v1.q.add(v0.q);
  70677. v0.updatePosition(p);
  70678. var tStart = _this.references.length;
  70679. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  70680. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  70681. var tCount = _this.references.length - tStart;
  70682. if (tCount <= v0.triangleCount) {
  70683. if (tCount) {
  70684. for (var c = 0; c < tCount; c++) {
  70685. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  70686. }
  70687. }
  70688. }
  70689. else {
  70690. v0.triangleStart = tStart;
  70691. }
  70692. v0.triangleCount = tCount;
  70693. break;
  70694. }
  70695. }
  70696. };
  70697. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  70698. }, 0);
  70699. };
  70700. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  70701. if (triangleCount - deletedTriangles <= targetCount)
  70702. loop.breakLoop();
  70703. else {
  70704. iterationFunction(loop.index, function () {
  70705. loop.executeNext();
  70706. });
  70707. }
  70708. }, function () {
  70709. setTimeout(function () {
  70710. //reconstruct this part of the mesh
  70711. _this.reconstructMesh(submeshIndex);
  70712. successCallback();
  70713. }, 0);
  70714. });
  70715. };
  70716. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  70717. var _this = this;
  70718. this.vertices = [];
  70719. this.triangles = [];
  70720. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70721. var indices = this._mesh.getIndices();
  70722. var submesh = this._mesh.subMeshes[submeshIndex];
  70723. var findInVertices = function (positionToSearch) {
  70724. if (optimizeMesh) {
  70725. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  70726. if (_this.vertices[ii].position.equals(positionToSearch)) {
  70727. return _this.vertices[ii];
  70728. }
  70729. }
  70730. }
  70731. return null;
  70732. };
  70733. var vertexReferences = [];
  70734. var vertexInit = function (i) {
  70735. if (!positionData) {
  70736. return;
  70737. }
  70738. var offset = i + submesh.verticesStart;
  70739. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  70740. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  70741. vertex.originalOffsets.push(offset);
  70742. if (vertex.id === _this.vertices.length) {
  70743. _this.vertices.push(vertex);
  70744. }
  70745. vertexReferences.push(vertex.id);
  70746. };
  70747. //var totalVertices = mesh.getTotalVertices();
  70748. var totalVertices = submesh.verticesCount;
  70749. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  70750. var indicesInit = function (i) {
  70751. if (!indices) {
  70752. return;
  70753. }
  70754. var offset = (submesh.indexStart / 3) + i;
  70755. var pos = (offset * 3);
  70756. var i0 = indices[pos + 0];
  70757. var i1 = indices[pos + 1];
  70758. var i2 = indices[pos + 2];
  70759. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  70760. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  70761. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  70762. var triangle = new DecimationTriangle([v0, v1, v2]);
  70763. triangle.originalOffset = pos;
  70764. _this.triangles.push(triangle);
  70765. };
  70766. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  70767. _this.init(callback);
  70768. });
  70769. });
  70770. };
  70771. QuadraticErrorSimplification.prototype.init = function (callback) {
  70772. var _this = this;
  70773. var triangleInit1 = function (i) {
  70774. var t = _this.triangles[i];
  70775. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  70776. for (var j = 0; j < 3; j++) {
  70777. 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))));
  70778. }
  70779. };
  70780. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  70781. var triangleInit2 = function (i) {
  70782. var t = _this.triangles[i];
  70783. for (var j = 0; j < 3; ++j) {
  70784. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  70785. }
  70786. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70787. };
  70788. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  70789. _this.initialized = true;
  70790. callback();
  70791. });
  70792. });
  70793. };
  70794. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  70795. var newTriangles = [];
  70796. var i;
  70797. for (i = 0; i < this.vertices.length; ++i) {
  70798. this.vertices[i].triangleCount = 0;
  70799. }
  70800. var t;
  70801. var j;
  70802. for (i = 0; i < this.triangles.length; ++i) {
  70803. if (!this.triangles[i].deleted) {
  70804. t = this.triangles[i];
  70805. for (j = 0; j < 3; ++j) {
  70806. t.vertices[j].triangleCount = 1;
  70807. }
  70808. newTriangles.push(t);
  70809. }
  70810. }
  70811. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  70812. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  70813. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  70814. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  70815. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70816. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70817. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  70818. var vertexCount = 0;
  70819. for (i = 0; i < this.vertices.length; ++i) {
  70820. var vertex = this.vertices[i];
  70821. vertex.id = vertexCount;
  70822. if (vertex.triangleCount) {
  70823. vertex.originalOffsets.forEach(function (originalOffset) {
  70824. if (!normalData) {
  70825. return;
  70826. }
  70827. newPositionData.push(vertex.position.x);
  70828. newPositionData.push(vertex.position.y);
  70829. newPositionData.push(vertex.position.z);
  70830. newNormalData.push(normalData[originalOffset * 3]);
  70831. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  70832. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  70833. if (uvs && uvs.length) {
  70834. newUVsData.push(uvs[(originalOffset * 2)]);
  70835. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  70836. }
  70837. else if (colorsData && colorsData.length) {
  70838. newColorsData.push(colorsData[(originalOffset * 4)]);
  70839. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  70840. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  70841. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  70842. }
  70843. ++vertexCount;
  70844. });
  70845. }
  70846. }
  70847. var startingIndex = this._reconstructedMesh.getTotalIndices();
  70848. var startingVertex = this._reconstructedMesh.getTotalVertices();
  70849. var submeshesArray = this._reconstructedMesh.subMeshes;
  70850. this._reconstructedMesh.subMeshes = [];
  70851. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  70852. var originalIndices = this._mesh.getIndices();
  70853. for (i = 0; i < newTriangles.length; ++i) {
  70854. t = newTriangles[i]; //now get the new referencing point for each vertex
  70855. [0, 1, 2].forEach(function (idx) {
  70856. var id = originalIndices[t.originalOffset + idx];
  70857. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  70858. if (offset < 0)
  70859. offset = 0;
  70860. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  70861. });
  70862. }
  70863. //overwriting the old vertex buffers and indices.
  70864. this._reconstructedMesh.setIndices(newIndicesArray);
  70865. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  70866. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  70867. if (newUVsData.length > 0)
  70868. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  70869. if (newColorsData.length > 0)
  70870. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  70871. //create submesh
  70872. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  70873. if (submeshIndex > 0) {
  70874. this._reconstructedMesh.subMeshes = [];
  70875. submeshesArray.forEach(function (submesh) {
  70876. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  70877. });
  70878. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  70879. }
  70880. };
  70881. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  70882. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  70883. this._reconstructedMesh.material = this._mesh.material;
  70884. this._reconstructedMesh.parent = this._mesh.parent;
  70885. this._reconstructedMesh.isVisible = false;
  70886. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  70887. };
  70888. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  70889. for (var i = 0; i < vertex1.triangleCount; ++i) {
  70890. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  70891. if (t.deleted)
  70892. continue;
  70893. var s = this.references[vertex1.triangleStart + i].vertexId;
  70894. var v1 = t.vertices[(s + 1) % 3];
  70895. var v2 = t.vertices[(s + 2) % 3];
  70896. if ((v1 === vertex2 || v2 === vertex2)) {
  70897. deletedArray[i] = true;
  70898. delTr.push(t);
  70899. continue;
  70900. }
  70901. var d1 = v1.position.subtract(point);
  70902. d1 = d1.normalize();
  70903. var d2 = v2.position.subtract(point);
  70904. d2 = d2.normalize();
  70905. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  70906. return true;
  70907. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  70908. deletedArray[i] = false;
  70909. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  70910. return true;
  70911. }
  70912. return false;
  70913. };
  70914. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  70915. var newDeleted = deletedTriangles;
  70916. for (var i = 0; i < vertex.triangleCount; ++i) {
  70917. var ref = this.references[vertex.triangleStart + i];
  70918. var t = this.triangles[ref.triangleId];
  70919. if (t.deleted)
  70920. continue;
  70921. if (deletedArray[i] && t.deletePending) {
  70922. t.deleted = true;
  70923. newDeleted++;
  70924. continue;
  70925. }
  70926. t.vertices[ref.vertexId] = origVertex;
  70927. t.isDirty = true;
  70928. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  70929. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  70930. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  70931. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70932. this.references.push(ref);
  70933. }
  70934. return newDeleted;
  70935. };
  70936. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  70937. for (var i = 0; i < this.vertices.length; ++i) {
  70938. var vCount = [];
  70939. var vId = [];
  70940. var v = this.vertices[i];
  70941. var j;
  70942. for (j = 0; j < v.triangleCount; ++j) {
  70943. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  70944. for (var ii = 0; ii < 3; ii++) {
  70945. var ofs = 0;
  70946. var vv = triangle.vertices[ii];
  70947. while (ofs < vCount.length) {
  70948. if (vId[ofs] === vv.id)
  70949. break;
  70950. ++ofs;
  70951. }
  70952. if (ofs === vCount.length) {
  70953. vCount.push(1);
  70954. vId.push(vv.id);
  70955. }
  70956. else {
  70957. vCount[ofs]++;
  70958. }
  70959. }
  70960. }
  70961. for (j = 0; j < vCount.length; ++j) {
  70962. if (vCount[j] === 1) {
  70963. this.vertices[vId[j]].isBorder = true;
  70964. }
  70965. else {
  70966. this.vertices[vId[j]].isBorder = false;
  70967. }
  70968. }
  70969. }
  70970. };
  70971. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  70972. if (identifyBorders === void 0) { identifyBorders = false; }
  70973. var i;
  70974. if (!identifyBorders) {
  70975. var newTrianglesVector = [];
  70976. for (i = 0; i < this.triangles.length; ++i) {
  70977. if (!this.triangles[i].deleted) {
  70978. newTrianglesVector.push(this.triangles[i]);
  70979. }
  70980. }
  70981. this.triangles = newTrianglesVector;
  70982. }
  70983. for (i = 0; i < this.vertices.length; ++i) {
  70984. this.vertices[i].triangleCount = 0;
  70985. this.vertices[i].triangleStart = 0;
  70986. }
  70987. var t;
  70988. var j;
  70989. var v;
  70990. for (i = 0; i < this.triangles.length; ++i) {
  70991. t = this.triangles[i];
  70992. for (j = 0; j < 3; ++j) {
  70993. v = t.vertices[j];
  70994. v.triangleCount++;
  70995. }
  70996. }
  70997. var tStart = 0;
  70998. for (i = 0; i < this.vertices.length; ++i) {
  70999. this.vertices[i].triangleStart = tStart;
  71000. tStart += this.vertices[i].triangleCount;
  71001. this.vertices[i].triangleCount = 0;
  71002. }
  71003. var newReferences = new Array(this.triangles.length * 3);
  71004. for (i = 0; i < this.triangles.length; ++i) {
  71005. t = this.triangles[i];
  71006. for (j = 0; j < 3; ++j) {
  71007. v = t.vertices[j];
  71008. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  71009. v.triangleCount++;
  71010. }
  71011. }
  71012. this.references = newReferences;
  71013. if (identifyBorders) {
  71014. this.identifyBorder();
  71015. }
  71016. };
  71017. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  71018. var x = point.x;
  71019. var y = point.y;
  71020. var z = point.z;
  71021. 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
  71022. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  71023. };
  71024. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  71025. var q = vertex1.q.add(vertex2.q);
  71026. var border = vertex1.isBorder && vertex2.isBorder;
  71027. var error = 0;
  71028. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  71029. if (qDet !== 0 && !border) {
  71030. if (!pointResult) {
  71031. pointResult = BABYLON.Vector3.Zero();
  71032. }
  71033. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  71034. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  71035. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  71036. error = this.vertexError(q, pointResult);
  71037. }
  71038. else {
  71039. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  71040. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  71041. var error1 = this.vertexError(q, vertex1.position);
  71042. var error2 = this.vertexError(q, vertex2.position);
  71043. var error3 = this.vertexError(q, p3);
  71044. error = Math.min(error1, error2, error3);
  71045. if (error === error1) {
  71046. if (pointResult) {
  71047. pointResult.copyFrom(vertex1.position);
  71048. }
  71049. }
  71050. else if (error === error2) {
  71051. if (pointResult) {
  71052. pointResult.copyFrom(vertex2.position);
  71053. }
  71054. }
  71055. else {
  71056. if (pointResult) {
  71057. pointResult.copyFrom(p3);
  71058. }
  71059. }
  71060. }
  71061. return error;
  71062. };
  71063. return QuadraticErrorSimplification;
  71064. }());
  71065. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  71066. })(BABYLON || (BABYLON = {}));
  71067. //# sourceMappingURL=babylon.meshSimplification.js.map
  71068. var BABYLON;
  71069. (function (BABYLON) {
  71070. var Internals;
  71071. (function (Internals) {
  71072. var MeshLODLevel = /** @class */ (function () {
  71073. function MeshLODLevel(distance, mesh) {
  71074. this.distance = distance;
  71075. this.mesh = mesh;
  71076. }
  71077. return MeshLODLevel;
  71078. }());
  71079. Internals.MeshLODLevel = MeshLODLevel;
  71080. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  71081. })(BABYLON || (BABYLON = {}));
  71082. //# sourceMappingURL=babylon.meshLODLevel.js.map
  71083. var BABYLON;
  71084. (function (BABYLON) {
  71085. // Standard optimizations
  71086. var SceneOptimization = /** @class */ (function () {
  71087. function SceneOptimization(priority) {
  71088. if (priority === void 0) { priority = 0; }
  71089. this.priority = priority;
  71090. this.apply = function (scene) {
  71091. return true; // Return true if everything that can be done was applied
  71092. };
  71093. }
  71094. return SceneOptimization;
  71095. }());
  71096. BABYLON.SceneOptimization = SceneOptimization;
  71097. var TextureOptimization = /** @class */ (function (_super) {
  71098. __extends(TextureOptimization, _super);
  71099. function TextureOptimization(priority, maximumSize) {
  71100. if (priority === void 0) { priority = 0; }
  71101. if (maximumSize === void 0) { maximumSize = 1024; }
  71102. var _this = _super.call(this, priority) || this;
  71103. _this.priority = priority;
  71104. _this.maximumSize = maximumSize;
  71105. _this.apply = function (scene) {
  71106. var allDone = true;
  71107. for (var index = 0; index < scene.textures.length; index++) {
  71108. var texture = scene.textures[index];
  71109. if (!texture.canRescale || texture.getContext) {
  71110. continue;
  71111. }
  71112. var currentSize = texture.getSize();
  71113. var maxDimension = Math.max(currentSize.width, currentSize.height);
  71114. if (maxDimension > _this.maximumSize) {
  71115. texture.scale(0.5);
  71116. allDone = false;
  71117. }
  71118. }
  71119. return allDone;
  71120. };
  71121. return _this;
  71122. }
  71123. return TextureOptimization;
  71124. }(SceneOptimization));
  71125. BABYLON.TextureOptimization = TextureOptimization;
  71126. var HardwareScalingOptimization = /** @class */ (function (_super) {
  71127. __extends(HardwareScalingOptimization, _super);
  71128. function HardwareScalingOptimization(priority, maximumScale) {
  71129. if (priority === void 0) { priority = 0; }
  71130. if (maximumScale === void 0) { maximumScale = 2; }
  71131. var _this = _super.call(this, priority) || this;
  71132. _this.priority = priority;
  71133. _this.maximumScale = maximumScale;
  71134. _this._currentScale = 1;
  71135. _this.apply = function (scene) {
  71136. _this._currentScale++;
  71137. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  71138. return _this._currentScale >= _this.maximumScale;
  71139. };
  71140. return _this;
  71141. }
  71142. return HardwareScalingOptimization;
  71143. }(SceneOptimization));
  71144. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  71145. var ShadowsOptimization = /** @class */ (function (_super) {
  71146. __extends(ShadowsOptimization, _super);
  71147. function ShadowsOptimization() {
  71148. var _this = _super !== null && _super.apply(this, arguments) || this;
  71149. _this.apply = function (scene) {
  71150. scene.shadowsEnabled = false;
  71151. return true;
  71152. };
  71153. return _this;
  71154. }
  71155. return ShadowsOptimization;
  71156. }(SceneOptimization));
  71157. BABYLON.ShadowsOptimization = ShadowsOptimization;
  71158. var PostProcessesOptimization = /** @class */ (function (_super) {
  71159. __extends(PostProcessesOptimization, _super);
  71160. function PostProcessesOptimization() {
  71161. var _this = _super !== null && _super.apply(this, arguments) || this;
  71162. _this.apply = function (scene) {
  71163. scene.postProcessesEnabled = false;
  71164. return true;
  71165. };
  71166. return _this;
  71167. }
  71168. return PostProcessesOptimization;
  71169. }(SceneOptimization));
  71170. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  71171. var LensFlaresOptimization = /** @class */ (function (_super) {
  71172. __extends(LensFlaresOptimization, _super);
  71173. function LensFlaresOptimization() {
  71174. var _this = _super !== null && _super.apply(this, arguments) || this;
  71175. _this.apply = function (scene) {
  71176. scene.lensFlaresEnabled = false;
  71177. return true;
  71178. };
  71179. return _this;
  71180. }
  71181. return LensFlaresOptimization;
  71182. }(SceneOptimization));
  71183. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  71184. var ParticlesOptimization = /** @class */ (function (_super) {
  71185. __extends(ParticlesOptimization, _super);
  71186. function ParticlesOptimization() {
  71187. var _this = _super !== null && _super.apply(this, arguments) || this;
  71188. _this.apply = function (scene) {
  71189. scene.particlesEnabled = false;
  71190. return true;
  71191. };
  71192. return _this;
  71193. }
  71194. return ParticlesOptimization;
  71195. }(SceneOptimization));
  71196. BABYLON.ParticlesOptimization = ParticlesOptimization;
  71197. var RenderTargetsOptimization = /** @class */ (function (_super) {
  71198. __extends(RenderTargetsOptimization, _super);
  71199. function RenderTargetsOptimization() {
  71200. var _this = _super !== null && _super.apply(this, arguments) || this;
  71201. _this.apply = function (scene) {
  71202. scene.renderTargetsEnabled = false;
  71203. return true;
  71204. };
  71205. return _this;
  71206. }
  71207. return RenderTargetsOptimization;
  71208. }(SceneOptimization));
  71209. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  71210. var MergeMeshesOptimization = /** @class */ (function (_super) {
  71211. __extends(MergeMeshesOptimization, _super);
  71212. function MergeMeshesOptimization() {
  71213. var _this = _super !== null && _super.apply(this, arguments) || this;
  71214. _this._canBeMerged = function (abstractMesh) {
  71215. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  71216. return false;
  71217. }
  71218. var mesh = abstractMesh;
  71219. if (!mesh.isVisible || !mesh.isEnabled()) {
  71220. return false;
  71221. }
  71222. if (mesh.instances.length > 0) {
  71223. return false;
  71224. }
  71225. if (mesh.skeleton || mesh.hasLODLevels) {
  71226. return false;
  71227. }
  71228. if (mesh.parent) {
  71229. return false;
  71230. }
  71231. return true;
  71232. };
  71233. _this.apply = function (scene, updateSelectionTree) {
  71234. var globalPool = scene.meshes.slice(0);
  71235. var globalLength = globalPool.length;
  71236. for (var index = 0; index < globalLength; index++) {
  71237. var currentPool = new Array();
  71238. var current = globalPool[index];
  71239. // Checks
  71240. if (!_this._canBeMerged(current)) {
  71241. continue;
  71242. }
  71243. currentPool.push(current);
  71244. // Find compatible meshes
  71245. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  71246. var otherMesh = globalPool[subIndex];
  71247. if (!_this._canBeMerged(otherMesh)) {
  71248. continue;
  71249. }
  71250. if (otherMesh.material !== current.material) {
  71251. continue;
  71252. }
  71253. if (otherMesh.checkCollisions !== current.checkCollisions) {
  71254. continue;
  71255. }
  71256. currentPool.push(otherMesh);
  71257. globalLength--;
  71258. globalPool.splice(subIndex, 1);
  71259. subIndex--;
  71260. }
  71261. if (currentPool.length < 2) {
  71262. continue;
  71263. }
  71264. // Merge meshes
  71265. BABYLON.Mesh.MergeMeshes(currentPool);
  71266. }
  71267. if (updateSelectionTree != undefined) {
  71268. if (updateSelectionTree) {
  71269. scene.createOrUpdateSelectionOctree();
  71270. }
  71271. }
  71272. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  71273. scene.createOrUpdateSelectionOctree();
  71274. }
  71275. return true;
  71276. };
  71277. return _this;
  71278. }
  71279. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  71280. get: function () {
  71281. return MergeMeshesOptimization._UpdateSelectionTree;
  71282. },
  71283. set: function (value) {
  71284. MergeMeshesOptimization._UpdateSelectionTree = value;
  71285. },
  71286. enumerable: true,
  71287. configurable: true
  71288. });
  71289. MergeMeshesOptimization._UpdateSelectionTree = false;
  71290. return MergeMeshesOptimization;
  71291. }(SceneOptimization));
  71292. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  71293. // Options
  71294. var SceneOptimizerOptions = /** @class */ (function () {
  71295. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  71296. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  71297. if (trackerDuration === void 0) { trackerDuration = 2000; }
  71298. this.targetFrameRate = targetFrameRate;
  71299. this.trackerDuration = trackerDuration;
  71300. this.optimizations = new Array();
  71301. }
  71302. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  71303. var result = new SceneOptimizerOptions(targetFrameRate);
  71304. var priority = 0;
  71305. result.optimizations.push(new MergeMeshesOptimization(priority));
  71306. result.optimizations.push(new ShadowsOptimization(priority));
  71307. result.optimizations.push(new LensFlaresOptimization(priority));
  71308. // Next priority
  71309. priority++;
  71310. result.optimizations.push(new PostProcessesOptimization(priority));
  71311. result.optimizations.push(new ParticlesOptimization(priority));
  71312. // Next priority
  71313. priority++;
  71314. result.optimizations.push(new TextureOptimization(priority, 1024));
  71315. return result;
  71316. };
  71317. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  71318. var result = new SceneOptimizerOptions(targetFrameRate);
  71319. var priority = 0;
  71320. result.optimizations.push(new MergeMeshesOptimization(priority));
  71321. result.optimizations.push(new ShadowsOptimization(priority));
  71322. result.optimizations.push(new LensFlaresOptimization(priority));
  71323. // Next priority
  71324. priority++;
  71325. result.optimizations.push(new PostProcessesOptimization(priority));
  71326. result.optimizations.push(new ParticlesOptimization(priority));
  71327. // Next priority
  71328. priority++;
  71329. result.optimizations.push(new TextureOptimization(priority, 512));
  71330. // Next priority
  71331. priority++;
  71332. result.optimizations.push(new RenderTargetsOptimization(priority));
  71333. // Next priority
  71334. priority++;
  71335. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  71336. return result;
  71337. };
  71338. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  71339. var result = new SceneOptimizerOptions(targetFrameRate);
  71340. var priority = 0;
  71341. result.optimizations.push(new MergeMeshesOptimization(priority));
  71342. result.optimizations.push(new ShadowsOptimization(priority));
  71343. result.optimizations.push(new LensFlaresOptimization(priority));
  71344. // Next priority
  71345. priority++;
  71346. result.optimizations.push(new PostProcessesOptimization(priority));
  71347. result.optimizations.push(new ParticlesOptimization(priority));
  71348. // Next priority
  71349. priority++;
  71350. result.optimizations.push(new TextureOptimization(priority, 256));
  71351. // Next priority
  71352. priority++;
  71353. result.optimizations.push(new RenderTargetsOptimization(priority));
  71354. // Next priority
  71355. priority++;
  71356. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  71357. return result;
  71358. };
  71359. return SceneOptimizerOptions;
  71360. }());
  71361. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  71362. // Scene optimizer tool
  71363. var SceneOptimizer = /** @class */ (function () {
  71364. function SceneOptimizer() {
  71365. }
  71366. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  71367. // TODO: add an epsilon
  71368. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  71369. if (onSuccess) {
  71370. onSuccess();
  71371. }
  71372. return;
  71373. }
  71374. // Apply current level of optimizations
  71375. var allDone = true;
  71376. var noOptimizationApplied = true;
  71377. for (var index = 0; index < options.optimizations.length; index++) {
  71378. var optimization = options.optimizations[index];
  71379. if (optimization.priority === currentPriorityLevel) {
  71380. noOptimizationApplied = false;
  71381. allDone = allDone && optimization.apply(scene);
  71382. }
  71383. }
  71384. // If no optimization was applied, this is a failure :(
  71385. if (noOptimizationApplied) {
  71386. if (onFailure) {
  71387. onFailure();
  71388. }
  71389. return;
  71390. }
  71391. // If all optimizations were done, move to next level
  71392. if (allDone) {
  71393. currentPriorityLevel++;
  71394. }
  71395. // Let's the system running for a specific amount of time before checking FPS
  71396. scene.executeWhenReady(function () {
  71397. setTimeout(function () {
  71398. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  71399. }, options.trackerDuration);
  71400. });
  71401. };
  71402. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  71403. if (!options) {
  71404. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  71405. }
  71406. // Let's the system running for a specific amount of time before checking FPS
  71407. scene.executeWhenReady(function () {
  71408. setTimeout(function () {
  71409. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  71410. }, options.trackerDuration);
  71411. });
  71412. };
  71413. return SceneOptimizer;
  71414. }());
  71415. BABYLON.SceneOptimizer = SceneOptimizer;
  71416. })(BABYLON || (BABYLON = {}));
  71417. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  71418. var BABYLON;
  71419. (function (BABYLON) {
  71420. var OutlineRenderer = /** @class */ (function () {
  71421. function OutlineRenderer(scene) {
  71422. this.zOffset = 1;
  71423. this._scene = scene;
  71424. }
  71425. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  71426. var _this = this;
  71427. if (useOverlay === void 0) { useOverlay = false; }
  71428. var scene = this._scene;
  71429. var engine = this._scene.getEngine();
  71430. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71431. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  71432. return;
  71433. }
  71434. var mesh = subMesh.getRenderingMesh();
  71435. var material = subMesh.getMaterial();
  71436. if (!material || !scene.activeCamera) {
  71437. return;
  71438. }
  71439. engine.enableEffect(this._effect);
  71440. // Logarithmic depth
  71441. if (material.useLogarithmicDepth) {
  71442. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  71443. }
  71444. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  71445. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  71446. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71447. // Bones
  71448. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71449. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71450. }
  71451. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71452. // Alpha test
  71453. if (material && material.needAlphaTesting()) {
  71454. var alphaTexture = material.getAlphaTestTexture();
  71455. if (alphaTexture) {
  71456. this._effect.setTexture("diffuseSampler", alphaTexture);
  71457. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71458. }
  71459. }
  71460. engine.setZOffset(-this.zOffset);
  71461. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  71462. engine.setZOffset(0);
  71463. };
  71464. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  71465. var defines = [];
  71466. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71467. var mesh = subMesh.getMesh();
  71468. var material = subMesh.getMaterial();
  71469. if (material) {
  71470. // Alpha test
  71471. if (material.needAlphaTesting()) {
  71472. defines.push("#define ALPHATEST");
  71473. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71474. attribs.push(BABYLON.VertexBuffer.UVKind);
  71475. defines.push("#define UV1");
  71476. }
  71477. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71478. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71479. defines.push("#define UV2");
  71480. }
  71481. }
  71482. //Logarithmic depth
  71483. if (material.useLogarithmicDepth) {
  71484. defines.push("#define LOGARITHMICDEPTH");
  71485. }
  71486. }
  71487. // Bones
  71488. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71489. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71490. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71491. if (mesh.numBoneInfluencers > 4) {
  71492. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71493. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71494. }
  71495. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71496. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71497. }
  71498. else {
  71499. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71500. }
  71501. // Instances
  71502. if (useInstances) {
  71503. defines.push("#define INSTANCES");
  71504. attribs.push("world0");
  71505. attribs.push("world1");
  71506. attribs.push("world2");
  71507. attribs.push("world3");
  71508. }
  71509. // Get correct effect
  71510. var join = defines.join("\n");
  71511. if (this._cachedDefines !== join) {
  71512. this._cachedDefines = join;
  71513. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  71514. }
  71515. return this._effect.isReady();
  71516. };
  71517. return OutlineRenderer;
  71518. }());
  71519. BABYLON.OutlineRenderer = OutlineRenderer;
  71520. })(BABYLON || (BABYLON = {}));
  71521. //# sourceMappingURL=babylon.outlineRenderer.js.map
  71522. var BABYLON;
  71523. (function (BABYLON) {
  71524. var FaceAdjacencies = /** @class */ (function () {
  71525. function FaceAdjacencies() {
  71526. this.edges = new Array();
  71527. this.edgesConnectedCount = 0;
  71528. }
  71529. return FaceAdjacencies;
  71530. }());
  71531. var EdgesRenderer = /** @class */ (function () {
  71532. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  71533. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  71534. if (epsilon === void 0) { epsilon = 0.95; }
  71535. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  71536. this.edgesWidthScalerForOrthographic = 1000.0;
  71537. this.edgesWidthScalerForPerspective = 50.0;
  71538. this._linesPositions = new Array();
  71539. this._linesNormals = new Array();
  71540. this._linesIndices = new Array();
  71541. this._buffers = {};
  71542. this._checkVerticesInsteadOfIndices = false;
  71543. this._source = source;
  71544. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  71545. this._epsilon = epsilon;
  71546. this._prepareRessources();
  71547. this._generateEdgesLines();
  71548. }
  71549. EdgesRenderer.prototype._prepareRessources = function () {
  71550. if (this._lineShader) {
  71551. return;
  71552. }
  71553. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  71554. attributes: ["position", "normal"],
  71555. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  71556. });
  71557. this._lineShader.disableDepthWrite = true;
  71558. this._lineShader.backFaceCulling = false;
  71559. };
  71560. EdgesRenderer.prototype._rebuild = function () {
  71561. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71562. if (buffer) {
  71563. buffer._rebuild();
  71564. }
  71565. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71566. if (buffer) {
  71567. buffer._rebuild();
  71568. }
  71569. var scene = this._source.getScene();
  71570. var engine = scene.getEngine();
  71571. this._ib = engine.createIndexBuffer(this._linesIndices);
  71572. };
  71573. EdgesRenderer.prototype.dispose = function () {
  71574. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71575. if (buffer) {
  71576. buffer.dispose();
  71577. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  71578. }
  71579. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71580. if (buffer) {
  71581. buffer.dispose();
  71582. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  71583. }
  71584. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  71585. this._lineShader.dispose();
  71586. };
  71587. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  71588. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  71589. return 0;
  71590. }
  71591. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  71592. return 1;
  71593. }
  71594. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  71595. return 2;
  71596. }
  71597. return -1;
  71598. };
  71599. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  71600. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  71601. return 0;
  71602. }
  71603. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  71604. return 1;
  71605. }
  71606. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  71607. return 2;
  71608. }
  71609. return -1;
  71610. };
  71611. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  71612. var needToCreateLine;
  71613. if (edge === undefined) {
  71614. needToCreateLine = true;
  71615. }
  71616. else {
  71617. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  71618. needToCreateLine = dotProduct < this._epsilon;
  71619. }
  71620. if (needToCreateLine) {
  71621. var offset = this._linesPositions.length / 3;
  71622. var normal = p0.subtract(p1);
  71623. normal.normalize();
  71624. // Positions
  71625. this._linesPositions.push(p0.x);
  71626. this._linesPositions.push(p0.y);
  71627. this._linesPositions.push(p0.z);
  71628. this._linesPositions.push(p0.x);
  71629. this._linesPositions.push(p0.y);
  71630. this._linesPositions.push(p0.z);
  71631. this._linesPositions.push(p1.x);
  71632. this._linesPositions.push(p1.y);
  71633. this._linesPositions.push(p1.z);
  71634. this._linesPositions.push(p1.x);
  71635. this._linesPositions.push(p1.y);
  71636. this._linesPositions.push(p1.z);
  71637. // Normals
  71638. this._linesNormals.push(p1.x);
  71639. this._linesNormals.push(p1.y);
  71640. this._linesNormals.push(p1.z);
  71641. this._linesNormals.push(-1);
  71642. this._linesNormals.push(p1.x);
  71643. this._linesNormals.push(p1.y);
  71644. this._linesNormals.push(p1.z);
  71645. this._linesNormals.push(1);
  71646. this._linesNormals.push(p0.x);
  71647. this._linesNormals.push(p0.y);
  71648. this._linesNormals.push(p0.z);
  71649. this._linesNormals.push(-1);
  71650. this._linesNormals.push(p0.x);
  71651. this._linesNormals.push(p0.y);
  71652. this._linesNormals.push(p0.z);
  71653. this._linesNormals.push(1);
  71654. // Indices
  71655. this._linesIndices.push(offset);
  71656. this._linesIndices.push(offset + 1);
  71657. this._linesIndices.push(offset + 2);
  71658. this._linesIndices.push(offset);
  71659. this._linesIndices.push(offset + 2);
  71660. this._linesIndices.push(offset + 3);
  71661. }
  71662. };
  71663. EdgesRenderer.prototype._generateEdgesLines = function () {
  71664. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71665. var indices = this._source.getIndices();
  71666. if (!indices || !positions) {
  71667. return;
  71668. }
  71669. // First let's find adjacencies
  71670. var adjacencies = new Array();
  71671. var faceNormals = new Array();
  71672. var index;
  71673. var faceAdjacencies;
  71674. // Prepare faces
  71675. for (index = 0; index < indices.length; index += 3) {
  71676. faceAdjacencies = new FaceAdjacencies();
  71677. var p0Index = indices[index];
  71678. var p1Index = indices[index + 1];
  71679. var p2Index = indices[index + 2];
  71680. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  71681. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  71682. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  71683. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  71684. faceNormal.normalize();
  71685. faceNormals.push(faceNormal);
  71686. adjacencies.push(faceAdjacencies);
  71687. }
  71688. // Scan
  71689. for (index = 0; index < adjacencies.length; index++) {
  71690. faceAdjacencies = adjacencies[index];
  71691. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  71692. var otherFaceAdjacencies = adjacencies[otherIndex];
  71693. if (faceAdjacencies.edgesConnectedCount === 3) {
  71694. break;
  71695. }
  71696. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  71697. continue;
  71698. }
  71699. var otherP0 = indices[otherIndex * 3];
  71700. var otherP1 = indices[otherIndex * 3 + 1];
  71701. var otherP2 = indices[otherIndex * 3 + 2];
  71702. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  71703. var otherEdgeIndex = 0;
  71704. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  71705. continue;
  71706. }
  71707. switch (edgeIndex) {
  71708. case 0:
  71709. if (this._checkVerticesInsteadOfIndices) {
  71710. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71711. }
  71712. else {
  71713. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  71714. }
  71715. break;
  71716. case 1:
  71717. if (this._checkVerticesInsteadOfIndices) {
  71718. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71719. }
  71720. else {
  71721. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  71722. }
  71723. break;
  71724. case 2:
  71725. if (this._checkVerticesInsteadOfIndices) {
  71726. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71727. }
  71728. else {
  71729. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  71730. }
  71731. break;
  71732. }
  71733. if (otherEdgeIndex === -1) {
  71734. continue;
  71735. }
  71736. faceAdjacencies.edges[edgeIndex] = otherIndex;
  71737. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  71738. faceAdjacencies.edgesConnectedCount++;
  71739. otherFaceAdjacencies.edgesConnectedCount++;
  71740. if (faceAdjacencies.edgesConnectedCount === 3) {
  71741. break;
  71742. }
  71743. }
  71744. }
  71745. }
  71746. // Create lines
  71747. for (index = 0; index < adjacencies.length; index++) {
  71748. // 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
  71749. var current = adjacencies[index];
  71750. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  71751. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  71752. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  71753. }
  71754. // Merge into a single mesh
  71755. var engine = this._source.getScene().getEngine();
  71756. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  71757. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  71758. this._ib = engine.createIndexBuffer(this._linesIndices);
  71759. this._indicesCount = this._linesIndices.length;
  71760. };
  71761. EdgesRenderer.prototype.render = function () {
  71762. var scene = this._source.getScene();
  71763. if (!this._lineShader.isReady() || !scene.activeCamera) {
  71764. return;
  71765. }
  71766. var engine = scene.getEngine();
  71767. this._lineShader._preBind();
  71768. // VBOs
  71769. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  71770. scene.resetCachedMaterial();
  71771. this._lineShader.setColor4("color", this._source.edgesColor);
  71772. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  71773. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  71774. }
  71775. else {
  71776. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  71777. }
  71778. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  71779. this._lineShader.bind(this._source.getWorldMatrix());
  71780. // Draw order
  71781. engine.draw(true, 0, this._indicesCount);
  71782. this._lineShader.unbind();
  71783. engine.setDepthWrite(true);
  71784. };
  71785. return EdgesRenderer;
  71786. }());
  71787. BABYLON.EdgesRenderer = EdgesRenderer;
  71788. })(BABYLON || (BABYLON = {}));
  71789. //# sourceMappingURL=babylon.edgesRenderer.js.map
  71790. var BABYLON;
  71791. (function (BABYLON) {
  71792. /**
  71793. * Special Glow Blur post process only blurring the alpha channel
  71794. * It enforces keeping the most luminous color in the color channel.
  71795. */
  71796. var GlowBlurPostProcess = /** @class */ (function (_super) {
  71797. __extends(GlowBlurPostProcess, _super);
  71798. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  71799. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71800. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  71801. _this.direction = direction;
  71802. _this.kernel = kernel;
  71803. _this.onApplyObservable.add(function (effect) {
  71804. effect.setFloat2("screenSize", _this.width, _this.height);
  71805. effect.setVector2("direction", _this.direction);
  71806. effect.setFloat("blurWidth", _this.kernel);
  71807. });
  71808. return _this;
  71809. }
  71810. return GlowBlurPostProcess;
  71811. }(BABYLON.PostProcess));
  71812. /**
  71813. * The highlight layer Helps adding a glow effect around a mesh.
  71814. *
  71815. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  71816. * glowy meshes to your scene.
  71817. *
  71818. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  71819. */
  71820. var HighlightLayer = /** @class */ (function () {
  71821. /**
  71822. * Instantiates a new highlight Layer and references it to the scene..
  71823. * @param name The name of the layer
  71824. * @param scene The scene to use the layer in
  71825. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  71826. */
  71827. function HighlightLayer(name, scene, options) {
  71828. this.name = name;
  71829. this._vertexBuffers = {};
  71830. this._mainTextureDesiredSize = { width: 0, height: 0 };
  71831. this._meshes = {};
  71832. this._maxSize = 0;
  71833. this._shouldRender = false;
  71834. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  71835. this._excludedMeshes = {};
  71836. /**
  71837. * Specifies whether or not the inner glow is ACTIVE in the layer.
  71838. */
  71839. this.innerGlow = true;
  71840. /**
  71841. * Specifies whether or not the outer glow is ACTIVE in the layer.
  71842. */
  71843. this.outerGlow = true;
  71844. /**
  71845. * Specifies wether the highlight layer is enabled or not.
  71846. */
  71847. this.isEnabled = true;
  71848. /**
  71849. * An event triggered when the highlight layer has been disposed.
  71850. * @type {BABYLON.Observable}
  71851. */
  71852. this.onDisposeObservable = new BABYLON.Observable();
  71853. /**
  71854. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  71855. * @type {BABYLON.Observable}
  71856. */
  71857. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  71858. /**
  71859. * An event triggered when the highlight layer is being blurred.
  71860. * @type {BABYLON.Observable}
  71861. */
  71862. this.onBeforeBlurObservable = new BABYLON.Observable();
  71863. /**
  71864. * An event triggered when the highlight layer has been blurred.
  71865. * @type {BABYLON.Observable}
  71866. */
  71867. this.onAfterBlurObservable = new BABYLON.Observable();
  71868. /**
  71869. * An event triggered when the glowing blurred texture is being merged in the scene.
  71870. * @type {BABYLON.Observable}
  71871. */
  71872. this.onBeforeComposeObservable = new BABYLON.Observable();
  71873. /**
  71874. * An event triggered when the glowing blurred texture has been merged in the scene.
  71875. * @type {BABYLON.Observable}
  71876. */
  71877. this.onAfterComposeObservable = new BABYLON.Observable();
  71878. /**
  71879. * An event triggered when the highlight layer changes its size.
  71880. * @type {BABYLON.Observable}
  71881. */
  71882. this.onSizeChangedObservable = new BABYLON.Observable();
  71883. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71884. var engine = scene.getEngine();
  71885. this._engine = engine;
  71886. this._maxSize = this._engine.getCaps().maxTextureSize;
  71887. this._scene.highlightLayers.push(this);
  71888. // Warn on stencil.
  71889. if (!this._engine.isStencilEnable) {
  71890. 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 }");
  71891. }
  71892. // Adapt options
  71893. this._options = options || {
  71894. mainTextureRatio: 0.5,
  71895. blurTextureSizeRatio: 0.5,
  71896. blurHorizontalSize: 1.0,
  71897. blurVerticalSize: 1.0,
  71898. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  71899. camera: null
  71900. };
  71901. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  71902. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  71903. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  71904. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  71905. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  71906. // VBO
  71907. var vertices = [];
  71908. vertices.push(1, 1);
  71909. vertices.push(-1, 1);
  71910. vertices.push(-1, -1);
  71911. vertices.push(1, -1);
  71912. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71913. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71914. this._createIndexBuffer();
  71915. // Effect
  71916. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  71917. // Render target
  71918. this.setMainTextureSize();
  71919. // Create Textures and post processes
  71920. this.createTextureAndPostProcesses();
  71921. }
  71922. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  71923. /**
  71924. * Gets the horizontal size of the blur.
  71925. */
  71926. get: function () {
  71927. return this._horizontalBlurPostprocess.kernel;
  71928. },
  71929. /**
  71930. * Specifies the horizontal size of the blur.
  71931. */
  71932. set: function (value) {
  71933. this._horizontalBlurPostprocess.kernel = value;
  71934. },
  71935. enumerable: true,
  71936. configurable: true
  71937. });
  71938. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  71939. /**
  71940. * Gets the vertical size of the blur.
  71941. */
  71942. get: function () {
  71943. return this._verticalBlurPostprocess.kernel;
  71944. },
  71945. /**
  71946. * Specifies the vertical size of the blur.
  71947. */
  71948. set: function (value) {
  71949. this._verticalBlurPostprocess.kernel = value;
  71950. },
  71951. enumerable: true,
  71952. configurable: true
  71953. });
  71954. Object.defineProperty(HighlightLayer.prototype, "camera", {
  71955. /**
  71956. * Gets the camera attached to the layer.
  71957. */
  71958. get: function () {
  71959. return this._options.camera;
  71960. },
  71961. enumerable: true,
  71962. configurable: true
  71963. });
  71964. HighlightLayer.prototype._createIndexBuffer = function () {
  71965. var engine = this._scene.getEngine();
  71966. // Indices
  71967. var indices = [];
  71968. indices.push(0);
  71969. indices.push(1);
  71970. indices.push(2);
  71971. indices.push(0);
  71972. indices.push(2);
  71973. indices.push(3);
  71974. this._indexBuffer = engine.createIndexBuffer(indices);
  71975. };
  71976. HighlightLayer.prototype._rebuild = function () {
  71977. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71978. if (vb) {
  71979. vb._rebuild();
  71980. }
  71981. this._createIndexBuffer();
  71982. };
  71983. /**
  71984. * Creates the render target textures and post processes used in the highlight layer.
  71985. */
  71986. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  71987. var _this = this;
  71988. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  71989. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  71990. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  71991. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  71992. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  71993. width: this._mainTextureDesiredSize.width,
  71994. height: this._mainTextureDesiredSize.height
  71995. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71996. this._mainTexture.activeCamera = this._options.camera;
  71997. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71998. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71999. this._mainTexture.anisotropicFilteringLevel = 1;
  72000. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72001. this._mainTexture.renderParticles = false;
  72002. this._mainTexture.renderList = null;
  72003. this._mainTexture.ignoreCameraViewport = true;
  72004. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  72005. width: blurTextureWidth,
  72006. height: blurTextureHeight
  72007. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72008. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72009. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72010. this._blurTexture.anisotropicFilteringLevel = 16;
  72011. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72012. this._blurTexture.renderParticles = false;
  72013. this._blurTexture.ignoreCameraViewport = true;
  72014. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72015. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  72016. effect.setTexture("textureSampler", _this._mainTexture);
  72017. });
  72018. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  72019. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72020. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72021. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72022. });
  72023. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72024. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72025. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72026. });
  72027. }
  72028. else {
  72029. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72030. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72031. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72032. });
  72033. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72034. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72035. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72036. });
  72037. }
  72038. this._mainTexture.onAfterUnbindObservable.add(function () {
  72039. _this.onBeforeBlurObservable.notifyObservers(_this);
  72040. var internalTexture = _this._blurTexture.getInternalTexture();
  72041. if (internalTexture) {
  72042. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  72043. }
  72044. _this.onAfterBlurObservable.notifyObservers(_this);
  72045. });
  72046. // Custom render function
  72047. var renderSubMesh = function (subMesh) {
  72048. if (!_this._meshes) {
  72049. return;
  72050. }
  72051. var material = subMesh.getMaterial();
  72052. var mesh = subMesh.getRenderingMesh();
  72053. var scene = _this._scene;
  72054. var engine = scene.getEngine();
  72055. if (!material) {
  72056. return;
  72057. }
  72058. // Culling
  72059. engine.setState(material.backFaceCulling);
  72060. // Managing instances
  72061. var batch = mesh._getInstancesRenderList(subMesh._id);
  72062. if (batch.mustReturn) {
  72063. return;
  72064. }
  72065. // Excluded Mesh
  72066. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72067. return;
  72068. }
  72069. ;
  72070. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72071. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  72072. var emissiveTexture = null;
  72073. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  72074. emissiveTexture = material.emissiveTexture;
  72075. }
  72076. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  72077. engine.enableEffect(_this._glowMapGenerationEffect);
  72078. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  72079. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  72080. if (highlightLayerMesh) {
  72081. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  72082. }
  72083. else {
  72084. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  72085. }
  72086. // Alpha test
  72087. if (material && material.needAlphaTesting()) {
  72088. var alphaTexture = material.getAlphaTestTexture();
  72089. if (alphaTexture) {
  72090. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  72091. var textureMatrix = alphaTexture.getTextureMatrix();
  72092. if (textureMatrix) {
  72093. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  72094. }
  72095. }
  72096. }
  72097. // Glow emissive only
  72098. if (emissiveTexture) {
  72099. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  72100. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  72101. }
  72102. // Bones
  72103. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72104. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72105. }
  72106. // Draw
  72107. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  72108. }
  72109. else {
  72110. // Need to reset refresh rate of the shadowMap
  72111. _this._mainTexture.resetRefreshCounter();
  72112. }
  72113. };
  72114. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72115. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  72116. var index;
  72117. var engine = _this._scene.getEngine();
  72118. if (depthOnlySubMeshes.length) {
  72119. engine.setColorWrite(false);
  72120. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72121. renderSubMesh(depthOnlySubMeshes.data[index]);
  72122. }
  72123. engine.setColorWrite(true);
  72124. }
  72125. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72126. renderSubMesh(opaqueSubMeshes.data[index]);
  72127. }
  72128. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72129. renderSubMesh(alphaTestSubMeshes.data[index]);
  72130. }
  72131. for (index = 0; index < transparentSubMeshes.length; index++) {
  72132. renderSubMesh(transparentSubMeshes.data[index]);
  72133. }
  72134. };
  72135. this._mainTexture.onClearObservable.add(function (engine) {
  72136. engine.clear(HighlightLayer.neutralColor, true, true, true);
  72137. });
  72138. };
  72139. /**
  72140. * Checks for the readiness of the element composing the layer.
  72141. * @param subMesh the mesh to check for
  72142. * @param useInstances specify wether or not to use instances to render the mesh
  72143. * @param emissiveTexture the associated emissive texture used to generate the glow
  72144. * @return true if ready otherwise, false
  72145. */
  72146. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  72147. var material = subMesh.getMaterial();
  72148. if (!material) {
  72149. return false;
  72150. }
  72151. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  72152. return false;
  72153. }
  72154. var defines = [];
  72155. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72156. var mesh = subMesh.getMesh();
  72157. var uv1 = false;
  72158. var uv2 = false;
  72159. // Alpha test
  72160. if (material && material.needAlphaTesting()) {
  72161. var alphaTexture = material.getAlphaTestTexture();
  72162. if (alphaTexture) {
  72163. defines.push("#define ALPHATEST");
  72164. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72165. alphaTexture.coordinatesIndex === 1) {
  72166. defines.push("#define DIFFUSEUV2");
  72167. uv2 = true;
  72168. }
  72169. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72170. defines.push("#define DIFFUSEUV1");
  72171. uv1 = true;
  72172. }
  72173. }
  72174. }
  72175. // Emissive
  72176. if (emissiveTexture) {
  72177. defines.push("#define EMISSIVE");
  72178. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72179. emissiveTexture.coordinatesIndex === 1) {
  72180. defines.push("#define EMISSIVEUV2");
  72181. uv2 = true;
  72182. }
  72183. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72184. defines.push("#define EMISSIVEUV1");
  72185. uv1 = true;
  72186. }
  72187. }
  72188. if (uv1) {
  72189. attribs.push(BABYLON.VertexBuffer.UVKind);
  72190. defines.push("#define UV1");
  72191. }
  72192. if (uv2) {
  72193. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72194. defines.push("#define UV2");
  72195. }
  72196. // Bones
  72197. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72198. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72199. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72200. if (mesh.numBoneInfluencers > 4) {
  72201. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72202. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72203. }
  72204. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72205. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72206. }
  72207. else {
  72208. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72209. }
  72210. // Instances
  72211. if (useInstances) {
  72212. defines.push("#define INSTANCES");
  72213. attribs.push("world0");
  72214. attribs.push("world1");
  72215. attribs.push("world2");
  72216. attribs.push("world3");
  72217. }
  72218. // Get correct effect
  72219. var join = defines.join("\n");
  72220. if (this._cachedDefines !== join) {
  72221. this._cachedDefines = join;
  72222. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  72223. }
  72224. return this._glowMapGenerationEffect.isReady();
  72225. };
  72226. /**
  72227. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  72228. */
  72229. HighlightLayer.prototype.render = function () {
  72230. var currentEffect = this._glowMapMergeEffect;
  72231. // Check
  72232. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  72233. return;
  72234. var engine = this._scene.getEngine();
  72235. this.onBeforeComposeObservable.notifyObservers(this);
  72236. // Render
  72237. engine.enableEffect(currentEffect);
  72238. engine.setState(false);
  72239. // Cache
  72240. var previousStencilBuffer = engine.getStencilBuffer();
  72241. var previousStencilFunction = engine.getStencilFunction();
  72242. var previousStencilMask = engine.getStencilMask();
  72243. var previousStencilOperationPass = engine.getStencilOperationPass();
  72244. var previousStencilOperationFail = engine.getStencilOperationFail();
  72245. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  72246. var previousAlphaMode = engine.getAlphaMode();
  72247. // Texture
  72248. currentEffect.setTexture("textureSampler", this._blurTexture);
  72249. // VBOs
  72250. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72251. // Stencil operations
  72252. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  72253. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  72254. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  72255. // Draw order
  72256. engine.setAlphaMode(this._options.alphaBlendingMode);
  72257. engine.setStencilMask(0x00);
  72258. engine.setStencilBuffer(true);
  72259. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  72260. if (this.outerGlow) {
  72261. currentEffect.setFloat("offset", 0);
  72262. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  72263. engine.draw(true, 0, 6);
  72264. }
  72265. if (this.innerGlow) {
  72266. currentEffect.setFloat("offset", 1);
  72267. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  72268. engine.draw(true, 0, 6);
  72269. }
  72270. // Restore Cache
  72271. engine.setStencilFunction(previousStencilFunction);
  72272. engine.setStencilMask(previousStencilMask);
  72273. engine.setAlphaMode(previousAlphaMode);
  72274. engine.setStencilBuffer(previousStencilBuffer);
  72275. engine.setStencilOperationPass(previousStencilOperationPass);
  72276. engine.setStencilOperationFail(previousStencilOperationFail);
  72277. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  72278. engine._stencilState.reset();
  72279. this.onAfterComposeObservable.notifyObservers(this);
  72280. // Handle size changes.
  72281. var size = this._mainTexture.getSize();
  72282. this.setMainTextureSize();
  72283. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  72284. // Recreate RTT and post processes on size change.
  72285. this.onSizeChangedObservable.notifyObservers(this);
  72286. this.disposeTextureAndPostProcesses();
  72287. this.createTextureAndPostProcesses();
  72288. }
  72289. };
  72290. /**
  72291. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  72292. * @param mesh The mesh to exclude from the highlight layer
  72293. */
  72294. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  72295. if (!this._excludedMeshes) {
  72296. return;
  72297. }
  72298. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72299. if (!meshExcluded) {
  72300. this._excludedMeshes[mesh.uniqueId] = {
  72301. mesh: mesh,
  72302. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  72303. mesh.getEngine().setStencilBuffer(false);
  72304. }),
  72305. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  72306. mesh.getEngine().setStencilBuffer(true);
  72307. }),
  72308. };
  72309. }
  72310. };
  72311. /**
  72312. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  72313. * @param mesh The mesh to highlight
  72314. */
  72315. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  72316. if (!this._excludedMeshes) {
  72317. return;
  72318. }
  72319. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72320. if (meshExcluded) {
  72321. if (meshExcluded.beforeRender) {
  72322. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  72323. }
  72324. if (meshExcluded.afterRender) {
  72325. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  72326. }
  72327. }
  72328. this._excludedMeshes[mesh.uniqueId] = null;
  72329. };
  72330. /**
  72331. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  72332. * @param mesh The mesh to highlight
  72333. * @param color The color of the highlight
  72334. * @param glowEmissiveOnly Extract the glow from the emissive texture
  72335. */
  72336. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  72337. var _this = this;
  72338. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  72339. if (!this._meshes) {
  72340. return;
  72341. }
  72342. var meshHighlight = this._meshes[mesh.uniqueId];
  72343. if (meshHighlight) {
  72344. meshHighlight.color = color;
  72345. }
  72346. else {
  72347. this._meshes[mesh.uniqueId] = {
  72348. mesh: mesh,
  72349. color: color,
  72350. // Lambda required for capture due to Observable this context
  72351. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  72352. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72353. _this.defaultStencilReference(mesh);
  72354. }
  72355. else {
  72356. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  72357. }
  72358. }),
  72359. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  72360. glowEmissiveOnly: glowEmissiveOnly
  72361. };
  72362. }
  72363. this._shouldRender = true;
  72364. };
  72365. /**
  72366. * Remove a mesh from the highlight layer in order to make it stop glowing.
  72367. * @param mesh The mesh to highlight
  72368. */
  72369. HighlightLayer.prototype.removeMesh = function (mesh) {
  72370. if (!this._meshes) {
  72371. return;
  72372. }
  72373. var meshHighlight = this._meshes[mesh.uniqueId];
  72374. if (meshHighlight) {
  72375. if (meshHighlight.observerHighlight) {
  72376. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72377. }
  72378. if (meshHighlight.observerDefault) {
  72379. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72380. }
  72381. }
  72382. this._meshes[mesh.uniqueId] = null;
  72383. this._shouldRender = false;
  72384. for (var meshHighlightToCheck in this._meshes) {
  72385. if (meshHighlightToCheck) {
  72386. this._shouldRender = true;
  72387. break;
  72388. }
  72389. }
  72390. };
  72391. /**
  72392. * Returns true if the layer contains information to display, otherwise false.
  72393. */
  72394. HighlightLayer.prototype.shouldRender = function () {
  72395. return this.isEnabled && this._shouldRender;
  72396. };
  72397. /**
  72398. * Sets the main texture desired size which is the closest power of two
  72399. * of the engine canvas size.
  72400. */
  72401. HighlightLayer.prototype.setMainTextureSize = function () {
  72402. if (this._options.mainTextureFixedSize) {
  72403. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  72404. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  72405. }
  72406. else {
  72407. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  72408. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  72409. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  72410. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  72411. }
  72412. };
  72413. /**
  72414. * Force the stencil to the normal expected value for none glowing parts
  72415. */
  72416. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  72417. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  72418. };
  72419. /**
  72420. * Dispose only the render target textures and post process.
  72421. */
  72422. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  72423. this._blurTexture.dispose();
  72424. this._mainTexture.dispose();
  72425. this._downSamplePostprocess.dispose();
  72426. this._horizontalBlurPostprocess.dispose();
  72427. this._verticalBlurPostprocess.dispose();
  72428. };
  72429. /**
  72430. * Dispose the highlight layer and free resources.
  72431. */
  72432. HighlightLayer.prototype.dispose = function () {
  72433. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72434. if (vertexBuffer) {
  72435. vertexBuffer.dispose();
  72436. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72437. }
  72438. if (this._indexBuffer) {
  72439. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72440. this._indexBuffer = null;
  72441. }
  72442. // Clean textures and post processes
  72443. this.disposeTextureAndPostProcesses();
  72444. if (this._meshes) {
  72445. // Clean mesh references
  72446. for (var id in this._meshes) {
  72447. var meshHighlight = this._meshes[id];
  72448. if (meshHighlight && meshHighlight.mesh) {
  72449. if (meshHighlight.observerHighlight) {
  72450. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72451. }
  72452. if (meshHighlight.observerDefault) {
  72453. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72454. }
  72455. }
  72456. }
  72457. this._meshes = null;
  72458. }
  72459. if (this._excludedMeshes) {
  72460. for (var id in this._excludedMeshes) {
  72461. var meshHighlight = this._excludedMeshes[id];
  72462. if (meshHighlight) {
  72463. if (meshHighlight.beforeRender) {
  72464. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  72465. }
  72466. if (meshHighlight.afterRender) {
  72467. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  72468. }
  72469. }
  72470. }
  72471. this._excludedMeshes = null;
  72472. }
  72473. // Remove from scene
  72474. var index = this._scene.highlightLayers.indexOf(this, 0);
  72475. if (index > -1) {
  72476. this._scene.highlightLayers.splice(index, 1);
  72477. }
  72478. // Callback
  72479. this.onDisposeObservable.notifyObservers(this);
  72480. this.onDisposeObservable.clear();
  72481. this.onBeforeRenderMainTextureObservable.clear();
  72482. this.onBeforeBlurObservable.clear();
  72483. this.onBeforeComposeObservable.clear();
  72484. this.onAfterComposeObservable.clear();
  72485. this.onSizeChangedObservable.clear();
  72486. };
  72487. /**
  72488. * The neutral color used during the preparation of the glow effect.
  72489. * This is black by default as the blend operation is a blend operation.
  72490. */
  72491. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  72492. /**
  72493. * Stencil value used for glowing meshes.
  72494. */
  72495. HighlightLayer.glowingMeshStencilReference = 0x02;
  72496. /**
  72497. * Stencil value used for the other meshes in the scene.
  72498. */
  72499. HighlightLayer.normalMeshStencilReference = 0x01;
  72500. return HighlightLayer;
  72501. }());
  72502. BABYLON.HighlightLayer = HighlightLayer;
  72503. })(BABYLON || (BABYLON = {}));
  72504. //# sourceMappingURL=babylon.highlightlayer.js.map
  72505. var BABYLON;
  72506. (function (BABYLON) {
  72507. var AssetTaskState;
  72508. (function (AssetTaskState) {
  72509. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  72510. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  72511. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  72512. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  72513. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  72514. var AbstractAssetTask = /** @class */ (function () {
  72515. function AbstractAssetTask(name) {
  72516. this.name = name;
  72517. this.isCompleted = false;
  72518. this.taskState = AssetTaskState.INIT;
  72519. }
  72520. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72521. var _this = this;
  72522. this.taskState = AssetTaskState.RUNNING;
  72523. this.runTask(scene, function () {
  72524. _this.onDoneCallback(onSuccess, onError);
  72525. }, function (msg, exception) {
  72526. _this.onErrorCallback(onError, msg, exception);
  72527. });
  72528. };
  72529. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72530. throw new Error("runTask is not implemented");
  72531. };
  72532. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  72533. this.taskState = AssetTaskState.ERROR;
  72534. this.errorObject = {
  72535. message: message,
  72536. exception: exception
  72537. };
  72538. if (this.onError) {
  72539. this.onError(this, message, exception);
  72540. }
  72541. onError();
  72542. };
  72543. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  72544. try {
  72545. this.taskState = AssetTaskState.DONE;
  72546. this.isCompleted = true;
  72547. if (this.onSuccess) {
  72548. this.onSuccess(this);
  72549. }
  72550. onSuccess();
  72551. }
  72552. catch (e) {
  72553. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  72554. }
  72555. };
  72556. return AbstractAssetTask;
  72557. }());
  72558. BABYLON.AbstractAssetTask = AbstractAssetTask;
  72559. var AssetsProgressEvent = /** @class */ (function () {
  72560. function AssetsProgressEvent(remainingCount, totalCount, task) {
  72561. this.remainingCount = remainingCount;
  72562. this.totalCount = totalCount;
  72563. this.task = task;
  72564. }
  72565. return AssetsProgressEvent;
  72566. }());
  72567. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  72568. var MeshAssetTask = /** @class */ (function (_super) {
  72569. __extends(MeshAssetTask, _super);
  72570. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  72571. var _this = _super.call(this, name) || this;
  72572. _this.name = name;
  72573. _this.meshesNames = meshesNames;
  72574. _this.rootUrl = rootUrl;
  72575. _this.sceneFilename = sceneFilename;
  72576. return _this;
  72577. }
  72578. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72579. var _this = this;
  72580. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  72581. _this.loadedMeshes = meshes;
  72582. _this.loadedParticleSystems = particleSystems;
  72583. _this.loadedSkeletons = skeletons;
  72584. onSuccess();
  72585. }, null, function (scene, message, exception) {
  72586. onError(message, exception);
  72587. });
  72588. };
  72589. return MeshAssetTask;
  72590. }(AbstractAssetTask));
  72591. BABYLON.MeshAssetTask = MeshAssetTask;
  72592. var TextFileAssetTask = /** @class */ (function (_super) {
  72593. __extends(TextFileAssetTask, _super);
  72594. function TextFileAssetTask(name, url) {
  72595. var _this = _super.call(this, name) || this;
  72596. _this.name = name;
  72597. _this.url = url;
  72598. return _this;
  72599. }
  72600. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72601. var _this = this;
  72602. BABYLON.Tools.LoadFile(this.url, function (data) {
  72603. _this.text = data;
  72604. onSuccess();
  72605. }, undefined, scene.database, false, function (request, exception) {
  72606. if (request) {
  72607. onError(request.status + " " + request.statusText, exception);
  72608. }
  72609. });
  72610. };
  72611. return TextFileAssetTask;
  72612. }(AbstractAssetTask));
  72613. BABYLON.TextFileAssetTask = TextFileAssetTask;
  72614. var BinaryFileAssetTask = /** @class */ (function (_super) {
  72615. __extends(BinaryFileAssetTask, _super);
  72616. function BinaryFileAssetTask(name, url) {
  72617. var _this = _super.call(this, name) || this;
  72618. _this.name = name;
  72619. _this.url = url;
  72620. return _this;
  72621. }
  72622. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72623. var _this = this;
  72624. BABYLON.Tools.LoadFile(this.url, function (data) {
  72625. _this.data = data;
  72626. onSuccess();
  72627. }, undefined, scene.database, true, function (request, exception) {
  72628. if (request) {
  72629. onError(request.status + " " + request.statusText, exception);
  72630. }
  72631. });
  72632. };
  72633. return BinaryFileAssetTask;
  72634. }(AbstractAssetTask));
  72635. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  72636. var ImageAssetTask = /** @class */ (function (_super) {
  72637. __extends(ImageAssetTask, _super);
  72638. function ImageAssetTask(name, url) {
  72639. var _this = _super.call(this, name) || this;
  72640. _this.name = name;
  72641. _this.url = url;
  72642. return _this;
  72643. }
  72644. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72645. var _this = this;
  72646. var img = new Image();
  72647. BABYLON.Tools.SetCorsBehavior(this.url, img);
  72648. img.onload = function () {
  72649. _this.image = img;
  72650. onSuccess();
  72651. };
  72652. img.onerror = function (err) {
  72653. onError("Error loading image", err);
  72654. };
  72655. img.src = this.url;
  72656. };
  72657. return ImageAssetTask;
  72658. }(AbstractAssetTask));
  72659. BABYLON.ImageAssetTask = ImageAssetTask;
  72660. var TextureAssetTask = /** @class */ (function (_super) {
  72661. __extends(TextureAssetTask, _super);
  72662. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  72663. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72664. var _this = _super.call(this, name) || this;
  72665. _this.name = name;
  72666. _this.url = url;
  72667. _this.noMipmap = noMipmap;
  72668. _this.invertY = invertY;
  72669. _this.samplingMode = samplingMode;
  72670. return _this;
  72671. }
  72672. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72673. var onload = function () {
  72674. onSuccess();
  72675. };
  72676. var onerror = function (msg, exception) {
  72677. onError(msg, exception);
  72678. };
  72679. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  72680. };
  72681. return TextureAssetTask;
  72682. }(AbstractAssetTask));
  72683. BABYLON.TextureAssetTask = TextureAssetTask;
  72684. var CubeTextureAssetTask = /** @class */ (function (_super) {
  72685. __extends(CubeTextureAssetTask, _super);
  72686. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  72687. var _this = _super.call(this, name) || this;
  72688. _this.name = name;
  72689. _this.url = url;
  72690. _this.extensions = extensions;
  72691. _this.noMipmap = noMipmap;
  72692. _this.files = files;
  72693. return _this;
  72694. }
  72695. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72696. var onload = function () {
  72697. onSuccess();
  72698. };
  72699. var onerror = function (msg, exception) {
  72700. onError(msg, exception);
  72701. };
  72702. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  72703. };
  72704. return CubeTextureAssetTask;
  72705. }(AbstractAssetTask));
  72706. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  72707. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  72708. __extends(HDRCubeTextureAssetTask, _super);
  72709. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72710. if (noMipmap === void 0) { noMipmap = false; }
  72711. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72712. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72713. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72714. var _this = _super.call(this, name) || this;
  72715. _this.name = name;
  72716. _this.url = url;
  72717. _this.size = size;
  72718. _this.noMipmap = noMipmap;
  72719. _this.generateHarmonics = generateHarmonics;
  72720. _this.useInGammaSpace = useInGammaSpace;
  72721. _this.usePMREMGenerator = usePMREMGenerator;
  72722. return _this;
  72723. }
  72724. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72725. var onload = function () {
  72726. onSuccess();
  72727. };
  72728. var onerror = function (message, exception) {
  72729. onError(message, exception);
  72730. };
  72731. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  72732. };
  72733. return HDRCubeTextureAssetTask;
  72734. }(AbstractAssetTask));
  72735. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  72736. var AssetsManager = /** @class */ (function () {
  72737. function AssetsManager(scene) {
  72738. this.tasks = new Array();
  72739. this.waitingTasksCount = 0;
  72740. //Observables
  72741. this.onTaskSuccessObservable = new BABYLON.Observable();
  72742. this.onTaskErrorObservable = new BABYLON.Observable();
  72743. this.onTasksDoneObservable = new BABYLON.Observable();
  72744. this.onProgressObservable = new BABYLON.Observable();
  72745. this.useDefaultLoadingScreen = true;
  72746. this._scene = scene;
  72747. }
  72748. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  72749. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  72750. this.tasks.push(task);
  72751. return task;
  72752. };
  72753. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  72754. var task = new TextFileAssetTask(taskName, url);
  72755. this.tasks.push(task);
  72756. return task;
  72757. };
  72758. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  72759. var task = new BinaryFileAssetTask(taskName, url);
  72760. this.tasks.push(task);
  72761. return task;
  72762. };
  72763. AssetsManager.prototype.addImageTask = function (taskName, url) {
  72764. var task = new ImageAssetTask(taskName, url);
  72765. this.tasks.push(task);
  72766. return task;
  72767. };
  72768. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  72769. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72770. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  72771. this.tasks.push(task);
  72772. return task;
  72773. };
  72774. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  72775. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  72776. this.tasks.push(task);
  72777. return task;
  72778. };
  72779. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72780. if (noMipmap === void 0) { noMipmap = false; }
  72781. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72782. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72783. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72784. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  72785. this.tasks.push(task);
  72786. return task;
  72787. };
  72788. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  72789. this.waitingTasksCount--;
  72790. try {
  72791. if (this.onProgress) {
  72792. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  72793. }
  72794. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  72795. }
  72796. catch (e) {
  72797. BABYLON.Tools.Error("Error running progress callbacks.");
  72798. console.log(e);
  72799. }
  72800. if (this.waitingTasksCount === 0) {
  72801. try {
  72802. if (this.onFinish) {
  72803. this.onFinish(this.tasks);
  72804. }
  72805. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72806. }
  72807. catch (e) {
  72808. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  72809. console.log(e);
  72810. }
  72811. this._scene.getEngine().hideLoadingUI();
  72812. }
  72813. };
  72814. AssetsManager.prototype._runTask = function (task) {
  72815. var _this = this;
  72816. var done = function () {
  72817. try {
  72818. if (_this.onTaskSuccess) {
  72819. _this.onTaskSuccess(task);
  72820. }
  72821. _this.onTaskSuccessObservable.notifyObservers(task);
  72822. _this._decreaseWaitingTasksCount(task);
  72823. }
  72824. catch (e) {
  72825. error("Error executing task success callbacks", e);
  72826. }
  72827. };
  72828. var error = function (message, exception) {
  72829. task.errorObject = task.errorObject || {
  72830. message: message,
  72831. exception: exception
  72832. };
  72833. if (_this.onTaskError) {
  72834. _this.onTaskError(task);
  72835. }
  72836. _this.onTaskErrorObservable.notifyObservers(task);
  72837. _this._decreaseWaitingTasksCount(task);
  72838. };
  72839. task.run(this._scene, done, error);
  72840. };
  72841. AssetsManager.prototype.reset = function () {
  72842. this.tasks = new Array();
  72843. return this;
  72844. };
  72845. AssetsManager.prototype.load = function () {
  72846. this.waitingTasksCount = this.tasks.length;
  72847. if (this.waitingTasksCount === 0) {
  72848. if (this.onFinish) {
  72849. this.onFinish(this.tasks);
  72850. }
  72851. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72852. return this;
  72853. }
  72854. if (this.useDefaultLoadingScreen) {
  72855. this._scene.getEngine().displayLoadingUI();
  72856. }
  72857. for (var index = 0; index < this.tasks.length; index++) {
  72858. var task = this.tasks[index];
  72859. this._runTask(task);
  72860. }
  72861. return this;
  72862. };
  72863. return AssetsManager;
  72864. }());
  72865. BABYLON.AssetsManager = AssetsManager;
  72866. })(BABYLON || (BABYLON = {}));
  72867. //# sourceMappingURL=babylon.assetsManager.js.map
  72868. var BABYLON;
  72869. (function (BABYLON) {
  72870. var serializedGeometries = [];
  72871. var serializeGeometry = function (geometry, serializationGeometries) {
  72872. if (serializedGeometries[geometry.id]) {
  72873. return;
  72874. }
  72875. if (geometry.doNotSerialize) {
  72876. return;
  72877. }
  72878. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  72879. serializationGeometries.boxes.push(geometry.serialize());
  72880. }
  72881. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  72882. serializationGeometries.spheres.push(geometry.serialize());
  72883. }
  72884. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  72885. serializationGeometries.cylinders.push(geometry.serialize());
  72886. }
  72887. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  72888. serializationGeometries.toruses.push(geometry.serialize());
  72889. }
  72890. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  72891. serializationGeometries.grounds.push(geometry.serialize());
  72892. }
  72893. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  72894. serializationGeometries.planes.push(geometry.serialize());
  72895. }
  72896. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  72897. serializationGeometries.torusKnots.push(geometry.serialize());
  72898. }
  72899. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  72900. throw new Error("Unknown primitive type");
  72901. }
  72902. else {
  72903. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  72904. }
  72905. serializedGeometries[geometry.id] = true;
  72906. };
  72907. var serializeMesh = function (mesh, serializationScene) {
  72908. var serializationObject = {};
  72909. // Geometry
  72910. var geometry = mesh._geometry;
  72911. if (geometry) {
  72912. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  72913. // 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
  72914. serializeGeometry(geometry, serializationScene.geometries);
  72915. }
  72916. }
  72917. // Custom
  72918. if (mesh.serialize) {
  72919. mesh.serialize(serializationObject);
  72920. }
  72921. return serializationObject;
  72922. };
  72923. var finalizeSingleMesh = function (mesh, serializationObject) {
  72924. //only works if the mesh is already loaded
  72925. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72926. //serialize material
  72927. if (mesh.material) {
  72928. if (mesh.material instanceof BABYLON.StandardMaterial) {
  72929. serializationObject.materials = serializationObject.materials || [];
  72930. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72931. serializationObject.materials.push(mesh.material.serialize());
  72932. }
  72933. }
  72934. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  72935. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  72936. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72937. serializationObject.multiMaterials.push(mesh.material.serialize());
  72938. }
  72939. }
  72940. }
  72941. //serialize geometry
  72942. var geometry = mesh._geometry;
  72943. if (geometry) {
  72944. if (!serializationObject.geometries) {
  72945. serializationObject.geometries = {};
  72946. serializationObject.geometries.boxes = [];
  72947. serializationObject.geometries.spheres = [];
  72948. serializationObject.geometries.cylinders = [];
  72949. serializationObject.geometries.toruses = [];
  72950. serializationObject.geometries.grounds = [];
  72951. serializationObject.geometries.planes = [];
  72952. serializationObject.geometries.torusKnots = [];
  72953. serializationObject.geometries.vertexData = [];
  72954. }
  72955. serializeGeometry(geometry, serializationObject.geometries);
  72956. }
  72957. // Skeletons
  72958. if (mesh.skeleton) {
  72959. serializationObject.skeletons = serializationObject.skeletons || [];
  72960. serializationObject.skeletons.push(mesh.skeleton.serialize());
  72961. }
  72962. //serialize the actual mesh
  72963. serializationObject.meshes = serializationObject.meshes || [];
  72964. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  72965. }
  72966. };
  72967. var SceneSerializer = /** @class */ (function () {
  72968. function SceneSerializer() {
  72969. }
  72970. SceneSerializer.ClearCache = function () {
  72971. serializedGeometries = [];
  72972. };
  72973. SceneSerializer.Serialize = function (scene) {
  72974. var serializationObject = {};
  72975. SceneSerializer.ClearCache();
  72976. // Scene
  72977. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  72978. serializationObject.autoClear = scene.autoClear;
  72979. serializationObject.clearColor = scene.clearColor.asArray();
  72980. serializationObject.ambientColor = scene.ambientColor.asArray();
  72981. serializationObject.gravity = scene.gravity.asArray();
  72982. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  72983. serializationObject.workerCollisions = scene.workerCollisions;
  72984. // Fog
  72985. if (scene.fogMode && scene.fogMode !== 0) {
  72986. serializationObject.fogMode = scene.fogMode;
  72987. serializationObject.fogColor = scene.fogColor.asArray();
  72988. serializationObject.fogStart = scene.fogStart;
  72989. serializationObject.fogEnd = scene.fogEnd;
  72990. serializationObject.fogDensity = scene.fogDensity;
  72991. }
  72992. //Physics
  72993. if (scene.isPhysicsEnabled()) {
  72994. var physicEngine = scene.getPhysicsEngine();
  72995. if (physicEngine) {
  72996. serializationObject.physicsEnabled = true;
  72997. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  72998. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  72999. }
  73000. }
  73001. // Metadata
  73002. if (scene.metadata) {
  73003. serializationObject.metadata = scene.metadata;
  73004. }
  73005. // Morph targets
  73006. serializationObject.morphTargetManagers = [];
  73007. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  73008. var abstractMesh = _a[_i];
  73009. var manager = abstractMesh.morphTargetManager;
  73010. if (manager) {
  73011. serializationObject.morphTargetManagers.push(manager.serialize());
  73012. }
  73013. }
  73014. // Lights
  73015. serializationObject.lights = [];
  73016. var index;
  73017. var light;
  73018. for (index = 0; index < scene.lights.length; index++) {
  73019. light = scene.lights[index];
  73020. if (!light.doNotSerialize) {
  73021. serializationObject.lights.push(light.serialize());
  73022. }
  73023. }
  73024. // Cameras
  73025. serializationObject.cameras = [];
  73026. for (index = 0; index < scene.cameras.length; index++) {
  73027. var camera = scene.cameras[index];
  73028. if (!camera.doNotSerialize) {
  73029. serializationObject.cameras.push(camera.serialize());
  73030. }
  73031. }
  73032. if (scene.activeCamera) {
  73033. serializationObject.activeCameraID = scene.activeCamera.id;
  73034. }
  73035. // Animations
  73036. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  73037. // Materials
  73038. serializationObject.materials = [];
  73039. serializationObject.multiMaterials = [];
  73040. var material;
  73041. for (index = 0; index < scene.materials.length; index++) {
  73042. material = scene.materials[index];
  73043. if (!material.doNotSerialize) {
  73044. serializationObject.materials.push(material.serialize());
  73045. }
  73046. }
  73047. // MultiMaterials
  73048. serializationObject.multiMaterials = [];
  73049. for (index = 0; index < scene.multiMaterials.length; index++) {
  73050. var multiMaterial = scene.multiMaterials[index];
  73051. serializationObject.multiMaterials.push(multiMaterial.serialize());
  73052. }
  73053. // Skeletons
  73054. serializationObject.skeletons = [];
  73055. for (index = 0; index < scene.skeletons.length; index++) {
  73056. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  73057. }
  73058. // Geometries
  73059. serializationObject.geometries = {};
  73060. serializationObject.geometries.boxes = [];
  73061. serializationObject.geometries.spheres = [];
  73062. serializationObject.geometries.cylinders = [];
  73063. serializationObject.geometries.toruses = [];
  73064. serializationObject.geometries.grounds = [];
  73065. serializationObject.geometries.planes = [];
  73066. serializationObject.geometries.torusKnots = [];
  73067. serializationObject.geometries.vertexData = [];
  73068. serializedGeometries = [];
  73069. var geometries = scene.getGeometries();
  73070. for (index = 0; index < geometries.length; index++) {
  73071. var geometry = geometries[index];
  73072. if (geometry.isReady()) {
  73073. serializeGeometry(geometry, serializationObject.geometries);
  73074. }
  73075. }
  73076. // Meshes
  73077. serializationObject.meshes = [];
  73078. for (index = 0; index < scene.meshes.length; index++) {
  73079. var abstractMesh = scene.meshes[index];
  73080. if (abstractMesh instanceof BABYLON.Mesh) {
  73081. var mesh = abstractMesh;
  73082. if (!mesh.doNotSerialize) {
  73083. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73084. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73085. }
  73086. }
  73087. }
  73088. }
  73089. // Particles Systems
  73090. serializationObject.particleSystems = [];
  73091. for (index = 0; index < scene.particleSystems.length; index++) {
  73092. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  73093. }
  73094. // Lens flares
  73095. serializationObject.lensFlareSystems = [];
  73096. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  73097. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  73098. }
  73099. // Shadows
  73100. serializationObject.shadowGenerators = [];
  73101. for (index = 0; index < scene.lights.length; index++) {
  73102. light = scene.lights[index];
  73103. var shadowGenerator = light.getShadowGenerator();
  73104. if (shadowGenerator) {
  73105. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73106. }
  73107. }
  73108. // Action Manager
  73109. if (scene.actionManager) {
  73110. serializationObject.actions = scene.actionManager.serialize("scene");
  73111. }
  73112. // Audio
  73113. serializationObject.sounds = [];
  73114. for (index = 0; index < scene.soundTracks.length; index++) {
  73115. var soundtrack = scene.soundTracks[index];
  73116. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  73117. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  73118. }
  73119. }
  73120. return serializationObject;
  73121. };
  73122. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  73123. if (withParents === void 0) { withParents = false; }
  73124. if (withChildren === void 0) { withChildren = false; }
  73125. var serializationObject = {};
  73126. SceneSerializer.ClearCache();
  73127. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  73128. if (withParents || withChildren) {
  73129. //deliberate for loop! not for each, appended should be processed as well.
  73130. for (var i = 0; i < toSerialize.length; ++i) {
  73131. if (withChildren) {
  73132. toSerialize[i].getDescendants().forEach(function (node) {
  73133. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  73134. toSerialize.push(node);
  73135. }
  73136. });
  73137. }
  73138. //make sure the array doesn't contain the object already
  73139. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  73140. toSerialize.push(toSerialize[i].parent);
  73141. }
  73142. }
  73143. }
  73144. toSerialize.forEach(function (mesh) {
  73145. finalizeSingleMesh(mesh, serializationObject);
  73146. });
  73147. return serializationObject;
  73148. };
  73149. return SceneSerializer;
  73150. }());
  73151. BABYLON.SceneSerializer = SceneSerializer;
  73152. })(BABYLON || (BABYLON = {}));
  73153. //# sourceMappingURL=babylon.sceneSerializer.js.map
  73154. var BABYLON;
  73155. (function (BABYLON) {
  73156. var ReflectionProbe = /** @class */ (function () {
  73157. function ReflectionProbe(name, size, scene, generateMipMaps) {
  73158. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73159. var _this = this;
  73160. this.name = name;
  73161. this._viewMatrix = BABYLON.Matrix.Identity();
  73162. this._target = BABYLON.Vector3.Zero();
  73163. this._add = BABYLON.Vector3.Zero();
  73164. this.invertYAxis = false;
  73165. this.position = BABYLON.Vector3.Zero();
  73166. this._scene = scene;
  73167. this._scene.reflectionProbes.push(this);
  73168. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  73169. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  73170. switch (faceIndex) {
  73171. case 0:
  73172. _this._add.copyFromFloats(1, 0, 0);
  73173. break;
  73174. case 1:
  73175. _this._add.copyFromFloats(-1, 0, 0);
  73176. break;
  73177. case 2:
  73178. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  73179. break;
  73180. case 3:
  73181. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  73182. break;
  73183. case 4:
  73184. _this._add.copyFromFloats(0, 0, 1);
  73185. break;
  73186. case 5:
  73187. _this._add.copyFromFloats(0, 0, -1);
  73188. break;
  73189. }
  73190. if (_this._attachedMesh) {
  73191. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  73192. }
  73193. _this.position.addToRef(_this._add, _this._target);
  73194. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  73195. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  73196. scene._forcedViewPosition = _this.position;
  73197. });
  73198. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  73199. scene._forcedViewPosition = null;
  73200. scene.updateTransformMatrix(true);
  73201. });
  73202. if (scene.activeCamera) {
  73203. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73204. }
  73205. }
  73206. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  73207. get: function () {
  73208. return this._renderTargetTexture.samples;
  73209. },
  73210. set: function (value) {
  73211. this._renderTargetTexture.samples = value;
  73212. },
  73213. enumerable: true,
  73214. configurable: true
  73215. });
  73216. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  73217. get: function () {
  73218. return this._renderTargetTexture.refreshRate;
  73219. },
  73220. set: function (value) {
  73221. this._renderTargetTexture.refreshRate = value;
  73222. },
  73223. enumerable: true,
  73224. configurable: true
  73225. });
  73226. ReflectionProbe.prototype.getScene = function () {
  73227. return this._scene;
  73228. };
  73229. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  73230. get: function () {
  73231. return this._renderTargetTexture;
  73232. },
  73233. enumerable: true,
  73234. configurable: true
  73235. });
  73236. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  73237. get: function () {
  73238. return this._renderTargetTexture.renderList;
  73239. },
  73240. enumerable: true,
  73241. configurable: true
  73242. });
  73243. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  73244. this._attachedMesh = mesh;
  73245. };
  73246. /**
  73247. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73248. *
  73249. * @param renderingGroupId The rendering group id corresponding to its index
  73250. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73251. */
  73252. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73253. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73254. };
  73255. ReflectionProbe.prototype.dispose = function () {
  73256. var index = this._scene.reflectionProbes.indexOf(this);
  73257. if (index !== -1) {
  73258. // Remove from the scene if found
  73259. this._scene.reflectionProbes.splice(index, 1);
  73260. }
  73261. if (this._renderTargetTexture) {
  73262. this._renderTargetTexture.dispose();
  73263. this._renderTargetTexture = null;
  73264. }
  73265. };
  73266. return ReflectionProbe;
  73267. }());
  73268. BABYLON.ReflectionProbe = ReflectionProbe;
  73269. })(BABYLON || (BABYLON = {}));
  73270. //# sourceMappingURL=babylon.reflectionProbe.js.map
  73271. var BABYLON;
  73272. (function (BABYLON) {
  73273. var Layer = /** @class */ (function () {
  73274. function Layer(name, imgUrl, scene, isBackground, color) {
  73275. this.name = name;
  73276. this.scale = new BABYLON.Vector2(1, 1);
  73277. this.offset = new BABYLON.Vector2(0, 0);
  73278. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  73279. this.layerMask = 0x0FFFFFFF;
  73280. this._vertexBuffers = {};
  73281. // Events
  73282. /**
  73283. * An event triggered when the layer is disposed.
  73284. * @type {BABYLON.Observable}
  73285. */
  73286. this.onDisposeObservable = new BABYLON.Observable();
  73287. /**
  73288. * An event triggered before rendering the scene
  73289. * @type {BABYLON.Observable}
  73290. */
  73291. this.onBeforeRenderObservable = new BABYLON.Observable();
  73292. /**
  73293. * An event triggered after rendering the scene
  73294. * @type {BABYLON.Observable}
  73295. */
  73296. this.onAfterRenderObservable = new BABYLON.Observable();
  73297. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  73298. this.isBackground = isBackground === undefined ? true : isBackground;
  73299. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  73300. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  73301. this._scene.layers.push(this);
  73302. var engine = this._scene.getEngine();
  73303. // VBO
  73304. var vertices = [];
  73305. vertices.push(1, 1);
  73306. vertices.push(-1, 1);
  73307. vertices.push(-1, -1);
  73308. vertices.push(1, -1);
  73309. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73310. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73311. this._createIndexBuffer();
  73312. // Effects
  73313. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  73314. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  73315. }
  73316. Object.defineProperty(Layer.prototype, "onDispose", {
  73317. set: function (callback) {
  73318. if (this._onDisposeObserver) {
  73319. this.onDisposeObservable.remove(this._onDisposeObserver);
  73320. }
  73321. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  73322. },
  73323. enumerable: true,
  73324. configurable: true
  73325. });
  73326. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  73327. set: function (callback) {
  73328. if (this._onBeforeRenderObserver) {
  73329. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73330. }
  73331. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73332. },
  73333. enumerable: true,
  73334. configurable: true
  73335. });
  73336. Object.defineProperty(Layer.prototype, "onAfterRender", {
  73337. set: function (callback) {
  73338. if (this._onAfterRenderObserver) {
  73339. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73340. }
  73341. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73342. },
  73343. enumerable: true,
  73344. configurable: true
  73345. });
  73346. Layer.prototype._createIndexBuffer = function () {
  73347. var engine = this._scene.getEngine();
  73348. // Indices
  73349. var indices = [];
  73350. indices.push(0);
  73351. indices.push(1);
  73352. indices.push(2);
  73353. indices.push(0);
  73354. indices.push(2);
  73355. indices.push(3);
  73356. this._indexBuffer = engine.createIndexBuffer(indices);
  73357. };
  73358. Layer.prototype._rebuild = function () {
  73359. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73360. if (vb) {
  73361. vb._rebuild();
  73362. }
  73363. this._createIndexBuffer();
  73364. };
  73365. Layer.prototype.render = function () {
  73366. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  73367. // Check
  73368. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  73369. return;
  73370. var engine = this._scene.getEngine();
  73371. this.onBeforeRenderObservable.notifyObservers(this);
  73372. // Render
  73373. engine.enableEffect(currentEffect);
  73374. engine.setState(false);
  73375. // Texture
  73376. currentEffect.setTexture("textureSampler", this.texture);
  73377. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  73378. // Color
  73379. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  73380. // Scale / offset
  73381. currentEffect.setVector2("offset", this.offset);
  73382. currentEffect.setVector2("scale", this.scale);
  73383. // VBOs
  73384. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73385. // Draw order
  73386. if (!this.alphaTest) {
  73387. engine.setAlphaMode(this.alphaBlendingMode);
  73388. engine.draw(true, 0, 6);
  73389. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73390. }
  73391. else {
  73392. engine.draw(true, 0, 6);
  73393. }
  73394. this.onAfterRenderObservable.notifyObservers(this);
  73395. };
  73396. Layer.prototype.dispose = function () {
  73397. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73398. if (vertexBuffer) {
  73399. vertexBuffer.dispose();
  73400. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73401. }
  73402. if (this._indexBuffer) {
  73403. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73404. this._indexBuffer = null;
  73405. }
  73406. if (this.texture) {
  73407. this.texture.dispose();
  73408. this.texture = null;
  73409. }
  73410. // Remove from scene
  73411. var index = this._scene.layers.indexOf(this);
  73412. this._scene.layers.splice(index, 1);
  73413. // Callback
  73414. this.onDisposeObservable.notifyObservers(this);
  73415. this.onDisposeObservable.clear();
  73416. this.onAfterRenderObservable.clear();
  73417. this.onBeforeRenderObservable.clear();
  73418. };
  73419. return Layer;
  73420. }());
  73421. BABYLON.Layer = Layer;
  73422. })(BABYLON || (BABYLON = {}));
  73423. //# sourceMappingURL=babylon.layer.js.map
  73424. var BABYLON;
  73425. (function (BABYLON) {
  73426. var TextureTools = /** @class */ (function () {
  73427. function TextureTools() {
  73428. }
  73429. /**
  73430. * Uses the GPU to create a copy texture rescaled at a given size
  73431. * @param texture Texture to copy from
  73432. * @param width Desired width
  73433. * @param height Desired height
  73434. * @return Generated texture
  73435. */
  73436. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  73437. if (useBilinearMode === void 0) { useBilinearMode = true; }
  73438. var scene = texture.getScene();
  73439. var engine = scene.getEngine();
  73440. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  73441. rtt.wrapU = texture.wrapU;
  73442. rtt.wrapV = texture.wrapV;
  73443. rtt.uOffset = texture.uOffset;
  73444. rtt.vOffset = texture.vOffset;
  73445. rtt.uScale = texture.uScale;
  73446. rtt.vScale = texture.vScale;
  73447. rtt.uAng = texture.uAng;
  73448. rtt.vAng = texture.vAng;
  73449. rtt.wAng = texture.wAng;
  73450. rtt.coordinatesIndex = texture.coordinatesIndex;
  73451. rtt.level = texture.level;
  73452. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  73453. rtt._texture.isReady = false;
  73454. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73455. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73456. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73457. passPostProcess.getEffect().executeWhenCompiled(function () {
  73458. passPostProcess.onApply = function (effect) {
  73459. effect.setTexture("textureSampler", texture);
  73460. };
  73461. var internalTexture = rtt.getInternalTexture();
  73462. if (internalTexture) {
  73463. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  73464. engine.unBindFramebuffer(internalTexture);
  73465. rtt.disposeFramebufferObjects();
  73466. passPostProcess.dispose();
  73467. internalTexture.isReady = true;
  73468. }
  73469. });
  73470. return rtt;
  73471. };
  73472. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  73473. if (!scene._environmentBRDFTexture) {
  73474. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73475. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73476. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73477. scene._environmentBRDFTexture = texture;
  73478. }
  73479. return scene._environmentBRDFTexture;
  73480. };
  73481. 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=";
  73482. return TextureTools;
  73483. }());
  73484. BABYLON.TextureTools = TextureTools;
  73485. })(BABYLON || (BABYLON = {}));
  73486. //# sourceMappingURL=babylon.textureTools.js.map
  73487. var BABYLON;
  73488. (function (BABYLON) {
  73489. var FramingBehavior = /** @class */ (function () {
  73490. function FramingBehavior() {
  73491. this._mode = FramingBehavior.FitFrustumSidesMode;
  73492. this._radiusScale = 1.0;
  73493. this._positionScale = 0.5;
  73494. this._defaultElevation = 0.3;
  73495. this._elevationReturnTime = 1500;
  73496. this._elevationReturnWaitTime = 1000;
  73497. this._zoomStopsAnimation = false;
  73498. this._framingTime = 1500;
  73499. this._isPointerDown = false;
  73500. this._lastInteractionTime = -Infinity;
  73501. // Framing control
  73502. this._animatables = new Array();
  73503. this._betaIsAnimating = false;
  73504. }
  73505. Object.defineProperty(FramingBehavior.prototype, "name", {
  73506. get: function () {
  73507. return "Framing";
  73508. },
  73509. enumerable: true,
  73510. configurable: true
  73511. });
  73512. Object.defineProperty(FramingBehavior.prototype, "mode", {
  73513. /**
  73514. * Gets current mode used by the behavior.
  73515. */
  73516. get: function () {
  73517. return this._mode;
  73518. },
  73519. /**
  73520. * Sets the current mode used by the behavior
  73521. */
  73522. set: function (mode) {
  73523. this._mode = mode;
  73524. },
  73525. enumerable: true,
  73526. configurable: true
  73527. });
  73528. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  73529. /**
  73530. * Gets the scale applied to the radius
  73531. */
  73532. get: function () {
  73533. return this._radiusScale;
  73534. },
  73535. /**
  73536. * Sets the scale applied to the radius (1 by default)
  73537. */
  73538. set: function (radius) {
  73539. this._radiusScale = radius;
  73540. },
  73541. enumerable: true,
  73542. configurable: true
  73543. });
  73544. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  73545. /**
  73546. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73547. */
  73548. get: function () {
  73549. return this._positionScale;
  73550. },
  73551. /**
  73552. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73553. */
  73554. set: function (scale) {
  73555. this._positionScale = scale;
  73556. },
  73557. enumerable: true,
  73558. configurable: true
  73559. });
  73560. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  73561. /**
  73562. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73563. * behaviour is triggered, in radians.
  73564. */
  73565. get: function () {
  73566. return this._defaultElevation;
  73567. },
  73568. /**
  73569. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73570. * behaviour is triggered, in radians.
  73571. */
  73572. set: function (elevation) {
  73573. this._defaultElevation = elevation;
  73574. },
  73575. enumerable: true,
  73576. configurable: true
  73577. });
  73578. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  73579. /**
  73580. * Gets the time (in milliseconds) taken to return to the default beta position.
  73581. * Negative value indicates camera should not return to default.
  73582. */
  73583. get: function () {
  73584. return this._elevationReturnTime;
  73585. },
  73586. /**
  73587. * Sets the time (in milliseconds) taken to return to the default beta position.
  73588. * Negative value indicates camera should not return to default.
  73589. */
  73590. set: function (speed) {
  73591. this._elevationReturnTime = speed;
  73592. },
  73593. enumerable: true,
  73594. configurable: true
  73595. });
  73596. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  73597. /**
  73598. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73599. */
  73600. get: function () {
  73601. return this._elevationReturnWaitTime;
  73602. },
  73603. /**
  73604. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73605. */
  73606. set: function (time) {
  73607. this._elevationReturnWaitTime = time;
  73608. },
  73609. enumerable: true,
  73610. configurable: true
  73611. });
  73612. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  73613. /**
  73614. * Gets the flag that indicates if user zooming should stop animation.
  73615. */
  73616. get: function () {
  73617. return this._zoomStopsAnimation;
  73618. },
  73619. /**
  73620. * Sets the flag that indicates if user zooming should stop animation.
  73621. */
  73622. set: function (flag) {
  73623. this._zoomStopsAnimation = flag;
  73624. },
  73625. enumerable: true,
  73626. configurable: true
  73627. });
  73628. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  73629. /**
  73630. * Gets the transition time when framing the mesh, in milliseconds
  73631. */
  73632. get: function () {
  73633. return this._framingTime;
  73634. },
  73635. /**
  73636. * Sets the transition time when framing the mesh, in milliseconds
  73637. */
  73638. set: function (time) {
  73639. this._framingTime = time;
  73640. },
  73641. enumerable: true,
  73642. configurable: true
  73643. });
  73644. FramingBehavior.prototype.attach = function (camera) {
  73645. var _this = this;
  73646. this._attachedCamera = camera;
  73647. var scene = this._attachedCamera.getScene();
  73648. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  73649. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73650. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73651. _this._isPointerDown = true;
  73652. return;
  73653. }
  73654. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73655. _this._isPointerDown = false;
  73656. }
  73657. });
  73658. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73659. if (mesh) {
  73660. _this.zoomOnMesh(mesh);
  73661. }
  73662. });
  73663. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73664. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73665. _this._applyUserInteraction();
  73666. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  73667. // back to the default position after a given timeout
  73668. _this._maintainCameraAboveGround();
  73669. });
  73670. };
  73671. FramingBehavior.prototype.detach = function () {
  73672. if (!this._attachedCamera) {
  73673. return;
  73674. }
  73675. var scene = this._attachedCamera.getScene();
  73676. if (this._onPrePointerObservableObserver) {
  73677. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73678. }
  73679. if (this._onAfterCheckInputsObserver) {
  73680. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73681. }
  73682. if (this._onMeshTargetChangedObserver) {
  73683. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73684. }
  73685. this._attachedCamera = null;
  73686. };
  73687. /**
  73688. * Targets the given mesh and updates zoom level accordingly.
  73689. * @param mesh The mesh to target.
  73690. * @param radius Optional. If a cached radius position already exists, overrides default.
  73691. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73692. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73693. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73694. */
  73695. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  73696. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73697. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73698. mesh.computeWorldMatrix(true);
  73699. var boundingBox = mesh.getBoundingInfo().boundingBox;
  73700. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  73701. };
  73702. /**
  73703. * Targets the given mesh and updates zoom level accordingly.
  73704. * @param mesh The mesh to target.
  73705. * @param radius Optional. If a cached radius position already exists, overrides default.
  73706. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73707. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73708. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73709. */
  73710. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  73711. var _this = this;
  73712. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73713. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73714. var zoomTarget;
  73715. if (!this._attachedCamera) {
  73716. return;
  73717. }
  73718. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  73719. var bottom = minimumWorld.y;
  73720. var top = maximumWorld.y;
  73721. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  73722. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  73723. if (focusOnOriginXZ) {
  73724. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  73725. }
  73726. else {
  73727. var centerWorld = minimumWorld.add(radiusWorld);
  73728. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  73729. }
  73730. if (!this._vectorTransition) {
  73731. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  73732. }
  73733. this._betaIsAnimating = true;
  73734. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  73735. if (animatable) {
  73736. this._animatables.push(animatable);
  73737. }
  73738. // sets the radius and lower radius bounds
  73739. // Small delta ensures camera is not always at lower zoom limit.
  73740. var radius = 0;
  73741. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  73742. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73743. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  73744. radius = position;
  73745. }
  73746. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73747. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73748. if (this._attachedCamera.lowerRadiusLimit === null) {
  73749. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  73750. }
  73751. }
  73752. // Set sensibilities
  73753. var extend = maximumWorld.subtract(minimumWorld).length();
  73754. this._attachedCamera.panningSensibility = 5000 / extend;
  73755. this._attachedCamera.wheelPrecision = 100 / radius;
  73756. // transition to new radius
  73757. if (!this._radiusTransition) {
  73758. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73759. }
  73760. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  73761. if (onAnimationEnd) {
  73762. onAnimationEnd();
  73763. }
  73764. if (_this._attachedCamera) {
  73765. _this._attachedCamera.storeState();
  73766. }
  73767. });
  73768. if (animatable) {
  73769. this._animatables.push(animatable);
  73770. }
  73771. };
  73772. /**
  73773. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  73774. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  73775. * frustum width.
  73776. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  73777. * to fully enclose the mesh in the viewing frustum.
  73778. */
  73779. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  73780. var size = maximumWorld.subtract(minimumWorld);
  73781. var boxVectorGlobalDiagonal = size.length();
  73782. var frustumSlope = this._getFrustumSlope();
  73783. // Formula for setting distance
  73784. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  73785. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  73786. // Horizon distance
  73787. var radius = radiusWithoutFraming * this._radiusScale;
  73788. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  73789. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  73790. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  73791. var camera = this._attachedCamera;
  73792. if (!camera) {
  73793. return 0;
  73794. }
  73795. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73796. // Don't exceed the requested limit
  73797. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  73798. }
  73799. // Don't exceed the upper radius limit
  73800. if (camera.upperRadiusLimit) {
  73801. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  73802. }
  73803. return distance;
  73804. };
  73805. /**
  73806. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  73807. * is automatically returned to its default position (expected to be above ground plane).
  73808. */
  73809. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  73810. var _this = this;
  73811. if (this._elevationReturnTime < 0) {
  73812. return;
  73813. }
  73814. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  73815. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  73816. var limitBeta = Math.PI * 0.5;
  73817. // Bring the camera back up if below the ground plane
  73818. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  73819. this._betaIsAnimating = true;
  73820. //Transition to new position
  73821. this.stopAllAnimations();
  73822. if (!this._betaTransition) {
  73823. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73824. }
  73825. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  73826. _this._clearAnimationLocks();
  73827. _this.stopAllAnimations();
  73828. });
  73829. if (animatabe) {
  73830. this._animatables.push(animatabe);
  73831. }
  73832. }
  73833. };
  73834. /**
  73835. * Returns the frustum slope based on the canvas ratio and camera FOV
  73836. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  73837. */
  73838. FramingBehavior.prototype._getFrustumSlope = function () {
  73839. // Calculate the viewport ratio
  73840. // Aspect Ratio is Height/Width.
  73841. var camera = this._attachedCamera;
  73842. if (!camera) {
  73843. return BABYLON.Vector2.Zero();
  73844. }
  73845. var engine = camera.getScene().getEngine();
  73846. var aspectRatio = engine.getAspectRatio(camera);
  73847. // Camera FOV is the vertical field of view (top-bottom) in radians.
  73848. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  73849. var frustumSlopeY = Math.tan(camera.fov / 2);
  73850. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  73851. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  73852. // along the forward vector.
  73853. var frustumSlopeX = frustumSlopeY * aspectRatio;
  73854. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  73855. };
  73856. /**
  73857. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  73858. */
  73859. FramingBehavior.prototype._clearAnimationLocks = function () {
  73860. this._betaIsAnimating = false;
  73861. };
  73862. /**
  73863. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  73864. */
  73865. FramingBehavior.prototype._applyUserInteraction = function () {
  73866. if (this.isUserIsMoving) {
  73867. this._lastInteractionTime = BABYLON.Tools.Now;
  73868. this.stopAllAnimations();
  73869. this._clearAnimationLocks();
  73870. }
  73871. };
  73872. /**
  73873. * Stops and removes all animations that have been applied to the camera
  73874. */
  73875. FramingBehavior.prototype.stopAllAnimations = function () {
  73876. if (this._attachedCamera) {
  73877. this._attachedCamera.animations = [];
  73878. }
  73879. while (this._animatables.length) {
  73880. if (this._animatables[0]) {
  73881. this._animatables[0].onAnimationEnd = null;
  73882. this._animatables[0].stop();
  73883. }
  73884. this._animatables.shift();
  73885. }
  73886. };
  73887. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  73888. /**
  73889. * Gets a value indicating if the user is moving the camera
  73890. */
  73891. get: function () {
  73892. if (!this._attachedCamera) {
  73893. return false;
  73894. }
  73895. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  73896. this._attachedCamera.inertialBetaOffset !== 0 ||
  73897. this._attachedCamera.inertialRadiusOffset !== 0 ||
  73898. this._attachedCamera.inertialPanningX !== 0 ||
  73899. this._attachedCamera.inertialPanningY !== 0 ||
  73900. this._isPointerDown;
  73901. },
  73902. enumerable: true,
  73903. configurable: true
  73904. });
  73905. /**
  73906. * The easing function used by animations
  73907. */
  73908. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  73909. /**
  73910. * The easing mode used by animations
  73911. */
  73912. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  73913. // Statics
  73914. /**
  73915. * The camera can move all the way towards the mesh.
  73916. */
  73917. FramingBehavior.IgnoreBoundsSizeMode = 0;
  73918. /**
  73919. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  73920. */
  73921. FramingBehavior.FitFrustumSidesMode = 1;
  73922. return FramingBehavior;
  73923. }());
  73924. BABYLON.FramingBehavior = FramingBehavior;
  73925. })(BABYLON || (BABYLON = {}));
  73926. //# sourceMappingURL=babylon.framingBehavior.js.map
  73927. var BABYLON;
  73928. (function (BABYLON) {
  73929. /**
  73930. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  73931. */
  73932. var BouncingBehavior = /** @class */ (function () {
  73933. function BouncingBehavior() {
  73934. /**
  73935. * The duration of the animation, in milliseconds
  73936. */
  73937. this.transitionDuration = 450;
  73938. /**
  73939. * Length of the distance animated by the transition when lower radius is reached
  73940. */
  73941. this.lowerRadiusTransitionRange = 2;
  73942. /**
  73943. * Length of the distance animated by the transition when upper radius is reached
  73944. */
  73945. this.upperRadiusTransitionRange = -2;
  73946. this._autoTransitionRange = false;
  73947. // Animations
  73948. this._radiusIsAnimating = false;
  73949. this._radiusBounceTransition = null;
  73950. this._animatables = new Array();
  73951. }
  73952. Object.defineProperty(BouncingBehavior.prototype, "name", {
  73953. get: function () {
  73954. return "Bouncing";
  73955. },
  73956. enumerable: true,
  73957. configurable: true
  73958. });
  73959. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  73960. /**
  73961. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73962. */
  73963. get: function () {
  73964. return this._autoTransitionRange;
  73965. },
  73966. /**
  73967. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73968. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  73969. */
  73970. set: function (value) {
  73971. var _this = this;
  73972. if (this._autoTransitionRange === value) {
  73973. return;
  73974. }
  73975. this._autoTransitionRange = value;
  73976. var camera = this._attachedCamera;
  73977. if (!camera) {
  73978. return;
  73979. }
  73980. if (value) {
  73981. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73982. if (!mesh) {
  73983. return;
  73984. }
  73985. mesh.computeWorldMatrix(true);
  73986. var diagonal = mesh.getBoundingInfo().diagonalLength;
  73987. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  73988. _this.upperRadiusTransitionRange = diagonal * 0.05;
  73989. });
  73990. }
  73991. else if (this._onMeshTargetChangedObserver) {
  73992. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73993. }
  73994. },
  73995. enumerable: true,
  73996. configurable: true
  73997. });
  73998. BouncingBehavior.prototype.attach = function (camera) {
  73999. var _this = this;
  74000. this._attachedCamera = camera;
  74001. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74002. if (!_this._attachedCamera) {
  74003. return;
  74004. }
  74005. // Add the bounce animation to the lower radius limit
  74006. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  74007. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  74008. }
  74009. // Add the bounce animation to the upper radius limit
  74010. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  74011. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  74012. }
  74013. });
  74014. };
  74015. BouncingBehavior.prototype.detach = function () {
  74016. if (!this._attachedCamera) {
  74017. return;
  74018. }
  74019. if (this._onAfterCheckInputsObserver) {
  74020. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74021. }
  74022. if (this._onMeshTargetChangedObserver) {
  74023. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74024. }
  74025. this._attachedCamera = null;
  74026. };
  74027. /**
  74028. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  74029. * @param radiusLimit The limit to check against.
  74030. * @return Bool to indicate if at limit.
  74031. */
  74032. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  74033. if (!this._attachedCamera) {
  74034. return false;
  74035. }
  74036. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  74037. return true;
  74038. }
  74039. return false;
  74040. };
  74041. /**
  74042. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  74043. * @param radiusDelta The delta by which to animate to. Can be negative.
  74044. */
  74045. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  74046. var _this = this;
  74047. if (!this._attachedCamera) {
  74048. return;
  74049. }
  74050. if (!this._radiusBounceTransition) {
  74051. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  74052. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  74053. }
  74054. // Prevent zoom until bounce has completed
  74055. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  74056. this._attachedCamera.wheelPrecision = Infinity;
  74057. this._attachedCamera.inertialRadiusOffset = 0;
  74058. // Animate to the radius limit
  74059. this.stopAllAnimations();
  74060. this._radiusIsAnimating = true;
  74061. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  74062. if (animatable) {
  74063. this._animatables.push(animatable);
  74064. }
  74065. };
  74066. /**
  74067. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  74068. */
  74069. BouncingBehavior.prototype._clearAnimationLocks = function () {
  74070. this._radiusIsAnimating = false;
  74071. if (this._attachedCamera) {
  74072. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  74073. }
  74074. };
  74075. /**
  74076. * Stops and removes all animations that have been applied to the camera
  74077. */
  74078. BouncingBehavior.prototype.stopAllAnimations = function () {
  74079. if (this._attachedCamera) {
  74080. this._attachedCamera.animations = [];
  74081. }
  74082. while (this._animatables.length) {
  74083. this._animatables[0].onAnimationEnd = null;
  74084. this._animatables[0].stop();
  74085. this._animatables.shift();
  74086. }
  74087. };
  74088. /**
  74089. * The easing function used by animations
  74090. */
  74091. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  74092. /**
  74093. * The easing mode used by animations
  74094. */
  74095. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  74096. return BouncingBehavior;
  74097. }());
  74098. BABYLON.BouncingBehavior = BouncingBehavior;
  74099. })(BABYLON || (BABYLON = {}));
  74100. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  74101. var BABYLON;
  74102. (function (BABYLON) {
  74103. var AutoRotationBehavior = /** @class */ (function () {
  74104. function AutoRotationBehavior() {
  74105. this._zoomStopsAnimation = false;
  74106. this._idleRotationSpeed = 0.05;
  74107. this._idleRotationWaitTime = 2000;
  74108. this._idleRotationSpinupTime = 2000;
  74109. this._isPointerDown = false;
  74110. this._lastFrameTime = null;
  74111. this._lastInteractionTime = -Infinity;
  74112. this._cameraRotationSpeed = 0;
  74113. this._lastFrameRadius = 0;
  74114. }
  74115. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  74116. get: function () {
  74117. return "AutoRotation";
  74118. },
  74119. enumerable: true,
  74120. configurable: true
  74121. });
  74122. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  74123. /**
  74124. * Gets the flag that indicates if user zooming should stop animation.
  74125. */
  74126. get: function () {
  74127. return this._zoomStopsAnimation;
  74128. },
  74129. /**
  74130. * Sets the flag that indicates if user zooming should stop animation.
  74131. */
  74132. set: function (flag) {
  74133. this._zoomStopsAnimation = flag;
  74134. },
  74135. enumerable: true,
  74136. configurable: true
  74137. });
  74138. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  74139. /**
  74140. * Gets the default speed at which the camera rotates around the model.
  74141. */
  74142. get: function () {
  74143. return this._idleRotationSpeed;
  74144. },
  74145. /**
  74146. * Sets the default speed at which the camera rotates around the model.
  74147. */
  74148. set: function (speed) {
  74149. this._idleRotationSpeed = speed;
  74150. },
  74151. enumerable: true,
  74152. configurable: true
  74153. });
  74154. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  74155. /**
  74156. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  74157. */
  74158. get: function () {
  74159. return this._idleRotationWaitTime;
  74160. },
  74161. /**
  74162. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  74163. */
  74164. set: function (time) {
  74165. this._idleRotationWaitTime = time;
  74166. },
  74167. enumerable: true,
  74168. configurable: true
  74169. });
  74170. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  74171. /**
  74172. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74173. */
  74174. get: function () {
  74175. return this._idleRotationSpinupTime;
  74176. },
  74177. /**
  74178. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74179. */
  74180. set: function (time) {
  74181. this._idleRotationSpinupTime = time;
  74182. },
  74183. enumerable: true,
  74184. configurable: true
  74185. });
  74186. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  74187. /**
  74188. * Gets a value indicating if the camera is currently rotating because of this behavior
  74189. */
  74190. get: function () {
  74191. return Math.abs(this._cameraRotationSpeed) > 0;
  74192. },
  74193. enumerable: true,
  74194. configurable: true
  74195. });
  74196. AutoRotationBehavior.prototype.attach = function (camera) {
  74197. var _this = this;
  74198. this._attachedCamera = camera;
  74199. var scene = this._attachedCamera.getScene();
  74200. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74201. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74202. _this._isPointerDown = true;
  74203. return;
  74204. }
  74205. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74206. _this._isPointerDown = false;
  74207. }
  74208. });
  74209. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74210. var now = BABYLON.Tools.Now;
  74211. var dt = 0;
  74212. if (_this._lastFrameTime != null) {
  74213. dt = now - _this._lastFrameTime;
  74214. }
  74215. _this._lastFrameTime = now;
  74216. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74217. _this._applyUserInteraction();
  74218. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  74219. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  74220. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  74221. // Step camera rotation by rotation speed
  74222. if (_this._attachedCamera) {
  74223. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  74224. }
  74225. });
  74226. };
  74227. AutoRotationBehavior.prototype.detach = function () {
  74228. if (!this._attachedCamera) {
  74229. return;
  74230. }
  74231. var scene = this._attachedCamera.getScene();
  74232. if (this._onPrePointerObservableObserver) {
  74233. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74234. }
  74235. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74236. this._attachedCamera = null;
  74237. };
  74238. /**
  74239. * Returns true if user is scrolling.
  74240. * @return true if user is scrolling.
  74241. */
  74242. AutoRotationBehavior.prototype._userIsZooming = function () {
  74243. if (!this._attachedCamera) {
  74244. return false;
  74245. }
  74246. return this._attachedCamera.inertialRadiusOffset !== 0;
  74247. };
  74248. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  74249. if (!this._attachedCamera) {
  74250. return false;
  74251. }
  74252. var zoomHasHitLimit = false;
  74253. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  74254. zoomHasHitLimit = true;
  74255. }
  74256. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  74257. this._lastFrameRadius = this._attachedCamera.radius;
  74258. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  74259. };
  74260. /**
  74261. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74262. */
  74263. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  74264. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  74265. this._lastInteractionTime = BABYLON.Tools.Now;
  74266. }
  74267. };
  74268. // Tools
  74269. AutoRotationBehavior.prototype._userIsMoving = function () {
  74270. if (!this._attachedCamera) {
  74271. return false;
  74272. }
  74273. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74274. this._attachedCamera.inertialBetaOffset !== 0 ||
  74275. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74276. this._attachedCamera.inertialPanningX !== 0 ||
  74277. this._attachedCamera.inertialPanningY !== 0 ||
  74278. this._isPointerDown;
  74279. };
  74280. return AutoRotationBehavior;
  74281. }());
  74282. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  74283. })(BABYLON || (BABYLON = {}));
  74284. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  74285. var BABYLON;
  74286. (function (BABYLON) {
  74287. /**
  74288. * This class can be used to get instrumentation data from a Babylon engine
  74289. */
  74290. var EngineInstrumentation = /** @class */ (function () {
  74291. function EngineInstrumentation(engine) {
  74292. this.engine = engine;
  74293. this._captureGPUFrameTime = false;
  74294. this._gpuFrameTime = new BABYLON.PerfCounter();
  74295. this._captureShaderCompilationTime = false;
  74296. this._shaderCompilationTime = new BABYLON.PerfCounter();
  74297. // Observers
  74298. this._onBeginFrameObserver = null;
  74299. this._onEndFrameObserver = null;
  74300. this._onBeforeShaderCompilationObserver = null;
  74301. this._onAfterShaderCompilationObserver = null;
  74302. }
  74303. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  74304. // Properties
  74305. /**
  74306. * Gets the perf counter used for GPU frame time
  74307. */
  74308. get: function () {
  74309. return this._gpuFrameTime;
  74310. },
  74311. enumerable: true,
  74312. configurable: true
  74313. });
  74314. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  74315. /**
  74316. * Gets the GPU frame time capture status
  74317. */
  74318. get: function () {
  74319. return this._captureGPUFrameTime;
  74320. },
  74321. /**
  74322. * Enable or disable the GPU frame time capture
  74323. */
  74324. set: function (value) {
  74325. var _this = this;
  74326. if (value === this._captureGPUFrameTime) {
  74327. return;
  74328. }
  74329. this._captureGPUFrameTime = value;
  74330. if (value) {
  74331. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  74332. if (!_this._gpuFrameTimeToken) {
  74333. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  74334. }
  74335. });
  74336. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  74337. if (!_this._gpuFrameTimeToken) {
  74338. return;
  74339. }
  74340. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  74341. if (time > -1) {
  74342. _this._gpuFrameTimeToken = null;
  74343. _this._gpuFrameTime.fetchNewFrame();
  74344. _this._gpuFrameTime.addCount(time, true);
  74345. }
  74346. });
  74347. }
  74348. else {
  74349. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74350. this._onBeginFrameObserver = null;
  74351. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74352. this._onEndFrameObserver = null;
  74353. }
  74354. },
  74355. enumerable: true,
  74356. configurable: true
  74357. });
  74358. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  74359. /**
  74360. * Gets the perf counter used for shader compilation time
  74361. */
  74362. get: function () {
  74363. return this._shaderCompilationTime;
  74364. },
  74365. enumerable: true,
  74366. configurable: true
  74367. });
  74368. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  74369. /**
  74370. * Gets the shader compilation time capture status
  74371. */
  74372. get: function () {
  74373. return this._captureShaderCompilationTime;
  74374. },
  74375. /**
  74376. * Enable or disable the shader compilation time capture
  74377. */
  74378. set: function (value) {
  74379. var _this = this;
  74380. if (value === this._captureShaderCompilationTime) {
  74381. return;
  74382. }
  74383. this._captureShaderCompilationTime = value;
  74384. if (value) {
  74385. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  74386. _this._shaderCompilationTime.fetchNewFrame();
  74387. _this._shaderCompilationTime.beginMonitoring();
  74388. });
  74389. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  74390. _this._shaderCompilationTime.endMonitoring();
  74391. });
  74392. }
  74393. else {
  74394. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74395. this._onBeforeShaderCompilationObserver = null;
  74396. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74397. this._onAfterShaderCompilationObserver = null;
  74398. }
  74399. },
  74400. enumerable: true,
  74401. configurable: true
  74402. });
  74403. EngineInstrumentation.prototype.dispose = function () {
  74404. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74405. this._onBeginFrameObserver = null;
  74406. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74407. this._onEndFrameObserver = null;
  74408. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74409. this._onBeforeShaderCompilationObserver = null;
  74410. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74411. this._onAfterShaderCompilationObserver = null;
  74412. this.engine = null;
  74413. };
  74414. return EngineInstrumentation;
  74415. }());
  74416. BABYLON.EngineInstrumentation = EngineInstrumentation;
  74417. })(BABYLON || (BABYLON = {}));
  74418. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  74419. var BABYLON;
  74420. (function (BABYLON) {
  74421. /**
  74422. * This class can be used to get instrumentation data from a Babylon engine
  74423. */
  74424. var SceneInstrumentation = /** @class */ (function () {
  74425. function SceneInstrumentation(scene) {
  74426. var _this = this;
  74427. this.scene = scene;
  74428. this._captureActiveMeshesEvaluationTime = false;
  74429. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  74430. this._captureRenderTargetsRenderTime = false;
  74431. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  74432. this._captureFrameTime = false;
  74433. this._frameTime = new BABYLON.PerfCounter();
  74434. this._captureRenderTime = false;
  74435. this._renderTime = new BABYLON.PerfCounter();
  74436. this._captureInterFrameTime = false;
  74437. this._interFrameTime = new BABYLON.PerfCounter();
  74438. this._captureParticlesRenderTime = false;
  74439. this._particlesRenderTime = new BABYLON.PerfCounter();
  74440. this._captureSpritesRenderTime = false;
  74441. this._spritesRenderTime = new BABYLON.PerfCounter();
  74442. this._capturePhysicsTime = false;
  74443. this._physicsTime = new BABYLON.PerfCounter();
  74444. this._captureAnimationsTime = false;
  74445. this._animationsTime = new BABYLON.PerfCounter();
  74446. // Observers
  74447. this._onBeforeActiveMeshesEvaluationObserver = null;
  74448. this._onAfterActiveMeshesEvaluationObserver = null;
  74449. this._onBeforeRenderTargetsRenderObserver = null;
  74450. this._onAfterRenderTargetsRenderObserver = null;
  74451. this._onAfterRenderObserver = null;
  74452. this._onBeforeDrawPhaseObserver = null;
  74453. this._onAfterDrawPhaseObserver = null;
  74454. this._onBeforeAnimationsObserver = null;
  74455. this._onBeforeParticlesRenderingObserver = null;
  74456. this._onAfterParticlesRenderingObserver = null;
  74457. this._onBeforeSpritesRenderingObserver = null;
  74458. this._onAfterSpritesRenderingObserver = null;
  74459. this._onBeforePhysicsObserver = null;
  74460. this._onAfterPhysicsObserver = null;
  74461. this._onAfterAnimationsObserver = null;
  74462. // Before render
  74463. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  74464. if (_this._captureActiveMeshesEvaluationTime) {
  74465. _this._activeMeshesEvaluationTime.fetchNewFrame();
  74466. }
  74467. if (_this._captureRenderTargetsRenderTime) {
  74468. _this._renderTargetsRenderTime.fetchNewFrame();
  74469. }
  74470. if (_this._captureFrameTime) {
  74471. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  74472. _this._frameTime.beginMonitoring();
  74473. }
  74474. if (_this._captureInterFrameTime) {
  74475. _this._interFrameTime.endMonitoring();
  74476. }
  74477. if (_this._captureParticlesRenderTime) {
  74478. _this._particlesRenderTime.fetchNewFrame();
  74479. }
  74480. if (_this._captureSpritesRenderTime) {
  74481. _this._spritesRenderTime.fetchNewFrame();
  74482. }
  74483. if (_this._captureAnimationsTime) {
  74484. _this._animationsTime.beginMonitoring();
  74485. }
  74486. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  74487. });
  74488. // After render
  74489. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  74490. if (_this._captureFrameTime) {
  74491. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  74492. _this._frameTime.endMonitoring();
  74493. }
  74494. if (_this._captureRenderTime) {
  74495. _this._renderTime.endMonitoring(false);
  74496. }
  74497. if (_this._captureInterFrameTime) {
  74498. _this._interFrameTime.beginMonitoring();
  74499. }
  74500. });
  74501. }
  74502. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  74503. // Properties
  74504. /**
  74505. * Gets the perf counter used for active meshes evaluation time
  74506. */
  74507. get: function () {
  74508. return this._activeMeshesEvaluationTime;
  74509. },
  74510. enumerable: true,
  74511. configurable: true
  74512. });
  74513. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  74514. /**
  74515. * Gets the active meshes evaluation time capture status
  74516. */
  74517. get: function () {
  74518. return this._captureActiveMeshesEvaluationTime;
  74519. },
  74520. /**
  74521. * Enable or disable the active meshes evaluation time capture
  74522. */
  74523. set: function (value) {
  74524. var _this = this;
  74525. if (value === this._captureActiveMeshesEvaluationTime) {
  74526. return;
  74527. }
  74528. this._captureActiveMeshesEvaluationTime = value;
  74529. if (value) {
  74530. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  74531. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  74532. _this._activeMeshesEvaluationTime.beginMonitoring();
  74533. });
  74534. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  74535. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  74536. _this._activeMeshesEvaluationTime.endMonitoring();
  74537. });
  74538. }
  74539. else {
  74540. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74541. this._onBeforeActiveMeshesEvaluationObserver = null;
  74542. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74543. this._onAfterActiveMeshesEvaluationObserver = null;
  74544. }
  74545. },
  74546. enumerable: true,
  74547. configurable: true
  74548. });
  74549. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  74550. /**
  74551. * Gets the perf counter used for render targets render time
  74552. */
  74553. get: function () {
  74554. return this._renderTargetsRenderTime;
  74555. },
  74556. enumerable: true,
  74557. configurable: true
  74558. });
  74559. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  74560. /**
  74561. * Gets the render targets render time capture status
  74562. */
  74563. get: function () {
  74564. return this._captureRenderTargetsRenderTime;
  74565. },
  74566. /**
  74567. * Enable or disable the render targets render time capture
  74568. */
  74569. set: function (value) {
  74570. var _this = this;
  74571. if (value === this._captureRenderTargetsRenderTime) {
  74572. return;
  74573. }
  74574. this._captureRenderTargetsRenderTime = value;
  74575. if (value) {
  74576. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  74577. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  74578. _this._renderTargetsRenderTime.beginMonitoring();
  74579. });
  74580. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  74581. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  74582. _this._renderTargetsRenderTime.endMonitoring(false);
  74583. });
  74584. }
  74585. else {
  74586. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74587. this._onBeforeRenderTargetsRenderObserver = null;
  74588. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74589. this._onAfterRenderTargetsRenderObserver = null;
  74590. }
  74591. },
  74592. enumerable: true,
  74593. configurable: true
  74594. });
  74595. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  74596. /**
  74597. * Gets the perf counter used for particles render time
  74598. */
  74599. get: function () {
  74600. return this._particlesRenderTime;
  74601. },
  74602. enumerable: true,
  74603. configurable: true
  74604. });
  74605. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  74606. /**
  74607. * Gets the particles render time capture status
  74608. */
  74609. get: function () {
  74610. return this._captureParticlesRenderTime;
  74611. },
  74612. /**
  74613. * Enable or disable the particles render time capture
  74614. */
  74615. set: function (value) {
  74616. var _this = this;
  74617. if (value === this._captureParticlesRenderTime) {
  74618. return;
  74619. }
  74620. this._captureParticlesRenderTime = value;
  74621. if (value) {
  74622. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  74623. BABYLON.Tools.StartPerformanceCounter("Particles");
  74624. _this._particlesRenderTime.beginMonitoring();
  74625. });
  74626. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  74627. BABYLON.Tools.EndPerformanceCounter("Particles");
  74628. _this._particlesRenderTime.endMonitoring(false);
  74629. });
  74630. }
  74631. else {
  74632. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  74633. this._onBeforeParticlesRenderingObserver = null;
  74634. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  74635. this._onAfterParticlesRenderingObserver = null;
  74636. }
  74637. },
  74638. enumerable: true,
  74639. configurable: true
  74640. });
  74641. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  74642. /**
  74643. * Gets the perf counter used for sprites render time
  74644. */
  74645. get: function () {
  74646. return this._spritesRenderTime;
  74647. },
  74648. enumerable: true,
  74649. configurable: true
  74650. });
  74651. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  74652. /**
  74653. * Gets the sprites render time capture status
  74654. */
  74655. get: function () {
  74656. return this._captureSpritesRenderTime;
  74657. },
  74658. /**
  74659. * Enable or disable the sprites render time capture
  74660. */
  74661. set: function (value) {
  74662. var _this = this;
  74663. if (value === this._captureSpritesRenderTime) {
  74664. return;
  74665. }
  74666. this._captureSpritesRenderTime = value;
  74667. if (value) {
  74668. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  74669. BABYLON.Tools.StartPerformanceCounter("Sprites");
  74670. _this._spritesRenderTime.beginMonitoring();
  74671. });
  74672. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  74673. BABYLON.Tools.EndPerformanceCounter("Sprites");
  74674. _this._spritesRenderTime.endMonitoring(false);
  74675. });
  74676. }
  74677. else {
  74678. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  74679. this._onBeforeSpritesRenderingObserver = null;
  74680. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  74681. this._onAfterSpritesRenderingObserver = null;
  74682. }
  74683. },
  74684. enumerable: true,
  74685. configurable: true
  74686. });
  74687. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  74688. /**
  74689. * Gets the perf counter used for physics time
  74690. */
  74691. get: function () {
  74692. return this._physicsTime;
  74693. },
  74694. enumerable: true,
  74695. configurable: true
  74696. });
  74697. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  74698. /**
  74699. * Gets the physics time capture status
  74700. */
  74701. get: function () {
  74702. return this._capturePhysicsTime;
  74703. },
  74704. /**
  74705. * Enable or disable the physics time capture
  74706. */
  74707. set: function (value) {
  74708. var _this = this;
  74709. if (value === this._capturePhysicsTime) {
  74710. return;
  74711. }
  74712. this._capturePhysicsTime = value;
  74713. if (value) {
  74714. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  74715. BABYLON.Tools.StartPerformanceCounter("Physics");
  74716. _this._physicsTime.beginMonitoring();
  74717. });
  74718. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  74719. BABYLON.Tools.EndPerformanceCounter("Physics");
  74720. _this._physicsTime.endMonitoring();
  74721. });
  74722. }
  74723. else {
  74724. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  74725. this._onBeforePhysicsObserver = null;
  74726. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  74727. this._onAfterPhysicsObserver = null;
  74728. }
  74729. },
  74730. enumerable: true,
  74731. configurable: true
  74732. });
  74733. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  74734. /**
  74735. * Gets the perf counter used for animations time
  74736. */
  74737. get: function () {
  74738. return this._animationsTime;
  74739. },
  74740. enumerable: true,
  74741. configurable: true
  74742. });
  74743. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  74744. /**
  74745. * Gets the animations time capture status
  74746. */
  74747. get: function () {
  74748. return this._captureAnimationsTime;
  74749. },
  74750. /**
  74751. * Enable or disable the animations time capture
  74752. */
  74753. set: function (value) {
  74754. var _this = this;
  74755. if (value === this._captureAnimationsTime) {
  74756. return;
  74757. }
  74758. this._captureAnimationsTime = value;
  74759. if (value) {
  74760. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  74761. _this._animationsTime.endMonitoring();
  74762. });
  74763. }
  74764. else {
  74765. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  74766. this._onAfterAnimationsObserver = null;
  74767. }
  74768. },
  74769. enumerable: true,
  74770. configurable: true
  74771. });
  74772. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  74773. /**
  74774. * Gets the perf counter used for frame time capture
  74775. */
  74776. get: function () {
  74777. return this._frameTime;
  74778. },
  74779. enumerable: true,
  74780. configurable: true
  74781. });
  74782. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  74783. /**
  74784. * Gets the frame time capture status
  74785. */
  74786. get: function () {
  74787. return this._captureFrameTime;
  74788. },
  74789. /**
  74790. * Enable or disable the frame time capture
  74791. */
  74792. set: function (value) {
  74793. this._captureFrameTime = value;
  74794. },
  74795. enumerable: true,
  74796. configurable: true
  74797. });
  74798. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  74799. /**
  74800. * Gets the perf counter used for inter-frames time capture
  74801. */
  74802. get: function () {
  74803. return this._interFrameTime;
  74804. },
  74805. enumerable: true,
  74806. configurable: true
  74807. });
  74808. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  74809. /**
  74810. * Gets the inter-frames time capture status
  74811. */
  74812. get: function () {
  74813. return this._captureInterFrameTime;
  74814. },
  74815. /**
  74816. * Enable or disable the inter-frames time capture
  74817. */
  74818. set: function (value) {
  74819. this._captureInterFrameTime = value;
  74820. },
  74821. enumerable: true,
  74822. configurable: true
  74823. });
  74824. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  74825. /**
  74826. * Gets the perf counter used for render time capture
  74827. */
  74828. get: function () {
  74829. return this._renderTime;
  74830. },
  74831. enumerable: true,
  74832. configurable: true
  74833. });
  74834. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  74835. /**
  74836. * Gets the render time capture status
  74837. */
  74838. get: function () {
  74839. return this._captureRenderTime;
  74840. },
  74841. /**
  74842. * Enable or disable the render time capture
  74843. */
  74844. set: function (value) {
  74845. var _this = this;
  74846. if (value === this._captureRenderTime) {
  74847. return;
  74848. }
  74849. this._captureRenderTime = value;
  74850. if (value) {
  74851. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  74852. _this._renderTime.beginMonitoring();
  74853. BABYLON.Tools.StartPerformanceCounter("Main render");
  74854. });
  74855. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  74856. _this._renderTime.endMonitoring(false);
  74857. BABYLON.Tools.EndPerformanceCounter("Main render");
  74858. });
  74859. }
  74860. else {
  74861. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  74862. this._onBeforeDrawPhaseObserver = null;
  74863. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  74864. this._onAfterDrawPhaseObserver = null;
  74865. }
  74866. },
  74867. enumerable: true,
  74868. configurable: true
  74869. });
  74870. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  74871. /**
  74872. * Gets the perf counter used for frame time capture
  74873. */
  74874. get: function () {
  74875. return this.scene.getEngine()._drawCalls;
  74876. },
  74877. enumerable: true,
  74878. configurable: true
  74879. });
  74880. SceneInstrumentation.prototype.dispose = function () {
  74881. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74882. this._onAfterRenderObserver = null;
  74883. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74884. this._onBeforeActiveMeshesEvaluationObserver = null;
  74885. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74886. this._onAfterActiveMeshesEvaluationObserver = null;
  74887. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74888. this._onBeforeRenderTargetsRenderObserver = null;
  74889. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74890. this._onAfterRenderTargetsRenderObserver = null;
  74891. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  74892. this._onBeforeAnimationsObserver = null;
  74893. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  74894. this._onBeforeParticlesRenderingObserver = null;
  74895. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  74896. this._onAfterParticlesRenderingObserver = null;
  74897. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  74898. this._onBeforeSpritesRenderingObserver = null;
  74899. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  74900. this._onAfterSpritesRenderingObserver = null;
  74901. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  74902. this._onBeforeDrawPhaseObserver = null;
  74903. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  74904. this._onAfterDrawPhaseObserver = null;
  74905. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  74906. this._onBeforePhysicsObserver = null;
  74907. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  74908. this._onAfterPhysicsObserver = null;
  74909. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  74910. this._onAfterAnimationsObserver = null;
  74911. this.scene = null;
  74912. };
  74913. return SceneInstrumentation;
  74914. }());
  74915. BABYLON.SceneInstrumentation = SceneInstrumentation;
  74916. })(BABYLON || (BABYLON = {}));
  74917. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  74918. var BABYLON;
  74919. (function (BABYLON) {
  74920. var _TimeToken = /** @class */ (function () {
  74921. function _TimeToken() {
  74922. this._timeElapsedQueryEnded = false;
  74923. }
  74924. return _TimeToken;
  74925. }());
  74926. BABYLON._TimeToken = _TimeToken;
  74927. })(BABYLON || (BABYLON = {}));
  74928. //# sourceMappingURL=babylon.timeToken.js.map
  74929. 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}"};
  74930. 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};"};
  74931. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74932. var BABYLON;
  74933. (function (BABYLON) {
  74934. var GridMaterialDefines = /** @class */ (function (_super) {
  74935. __extends(GridMaterialDefines, _super);
  74936. function GridMaterialDefines() {
  74937. var _this = _super.call(this) || this;
  74938. _this.TRANSPARENT = false;
  74939. _this.FOG = false;
  74940. _this.PREMULTIPLYALPHA = false;
  74941. _this.rebuild();
  74942. return _this;
  74943. }
  74944. return GridMaterialDefines;
  74945. }(BABYLON.MaterialDefines));
  74946. /**
  74947. * The grid materials allows you to wrap any shape with a grid.
  74948. * Colors are customizable.
  74949. */
  74950. var GridMaterial = /** @class */ (function (_super) {
  74951. __extends(GridMaterial, _super);
  74952. /**
  74953. * constructor
  74954. * @param name The name given to the material in order to identify it afterwards.
  74955. * @param scene The scene the material is used in.
  74956. */
  74957. function GridMaterial(name, scene) {
  74958. var _this = _super.call(this, name, scene) || this;
  74959. /**
  74960. * Main color of the grid (e.g. between lines)
  74961. */
  74962. _this.mainColor = BABYLON.Color3.Black();
  74963. /**
  74964. * Color of the grid lines.
  74965. */
  74966. _this.lineColor = BABYLON.Color3.Teal();
  74967. /**
  74968. * The scale of the grid compared to unit.
  74969. */
  74970. _this.gridRatio = 1.0;
  74971. /**
  74972. * Allows setting an offset for the grid lines.
  74973. */
  74974. _this.gridOffset = BABYLON.Vector3.Zero();
  74975. /**
  74976. * The frequency of thicker lines.
  74977. */
  74978. _this.majorUnitFrequency = 10;
  74979. /**
  74980. * The visibility of minor units in the grid.
  74981. */
  74982. _this.minorUnitVisibility = 0.33;
  74983. /**
  74984. * The grid opacity outside of the lines.
  74985. */
  74986. _this.opacity = 1.0;
  74987. /**
  74988. * Determine RBG output is premultiplied by alpha value.
  74989. */
  74990. _this.preMultiplyAlpha = false;
  74991. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  74992. return _this;
  74993. }
  74994. /**
  74995. * Returns wehter or not the grid requires alpha blending.
  74996. */
  74997. GridMaterial.prototype.needAlphaBlending = function () {
  74998. return this.opacity < 1.0;
  74999. };
  75000. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75001. if (this.isFrozen) {
  75002. if (this._wasPreviouslyReady && subMesh.effect) {
  75003. return true;
  75004. }
  75005. }
  75006. if (!subMesh._materialDefines) {
  75007. subMesh._materialDefines = new GridMaterialDefines();
  75008. }
  75009. var defines = subMesh._materialDefines;
  75010. var scene = this.getScene();
  75011. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  75012. if (this._renderId === scene.getRenderId()) {
  75013. return true;
  75014. }
  75015. }
  75016. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  75017. defines.TRANSPARENT = !defines.TRANSPARENT;
  75018. defines.markAsUnprocessed();
  75019. }
  75020. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  75021. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  75022. defines.markAsUnprocessed();
  75023. }
  75024. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  75025. // Get correct effect
  75026. if (defines.isDirty) {
  75027. defines.markAsProcessed();
  75028. scene.resetCachedMaterial();
  75029. // Attributes
  75030. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75031. // Defines
  75032. var join = defines.toString();
  75033. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  75034. }
  75035. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75036. return false;
  75037. }
  75038. this._renderId = scene.getRenderId();
  75039. this._wasPreviouslyReady = true;
  75040. return true;
  75041. };
  75042. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75043. var scene = this.getScene();
  75044. var defines = subMesh._materialDefines;
  75045. if (!defines) {
  75046. return;
  75047. }
  75048. var effect = subMesh.effect;
  75049. if (!effect) {
  75050. return;
  75051. }
  75052. this._activeEffect = effect;
  75053. // Matrices
  75054. this.bindOnlyWorldMatrix(world);
  75055. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  75056. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  75057. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  75058. // Uniforms
  75059. if (this._mustRebind(scene, effect)) {
  75060. this._activeEffect.setColor3("mainColor", this.mainColor);
  75061. this._activeEffect.setColor3("lineColor", this.lineColor);
  75062. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  75063. this._gridControl.x = this.gridRatio;
  75064. this._gridControl.y = Math.round(this.majorUnitFrequency);
  75065. this._gridControl.z = this.minorUnitVisibility;
  75066. this._gridControl.w = this.opacity;
  75067. this._activeEffect.setVector4("gridControl", this._gridControl);
  75068. }
  75069. // Fog
  75070. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75071. this._afterBind(mesh, this._activeEffect);
  75072. };
  75073. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  75074. _super.prototype.dispose.call(this, forceDisposeEffect);
  75075. };
  75076. GridMaterial.prototype.clone = function (name) {
  75077. var _this = this;
  75078. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  75079. };
  75080. GridMaterial.prototype.serialize = function () {
  75081. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75082. serializationObject.customType = "BABYLON.GridMaterial";
  75083. return serializationObject;
  75084. };
  75085. GridMaterial.prototype.getClassName = function () {
  75086. return "GridMaterial";
  75087. };
  75088. GridMaterial.Parse = function (source, scene, rootUrl) {
  75089. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  75090. };
  75091. __decorate([
  75092. BABYLON.serializeAsColor3()
  75093. ], GridMaterial.prototype, "mainColor", void 0);
  75094. __decorate([
  75095. BABYLON.serializeAsColor3()
  75096. ], GridMaterial.prototype, "lineColor", void 0);
  75097. __decorate([
  75098. BABYLON.serialize()
  75099. ], GridMaterial.prototype, "gridRatio", void 0);
  75100. __decorate([
  75101. BABYLON.serializeAsColor3()
  75102. ], GridMaterial.prototype, "gridOffset", void 0);
  75103. __decorate([
  75104. BABYLON.serialize()
  75105. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  75106. __decorate([
  75107. BABYLON.serialize()
  75108. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  75109. __decorate([
  75110. BABYLON.serialize()
  75111. ], GridMaterial.prototype, "opacity", void 0);
  75112. __decorate([
  75113. BABYLON.serialize()
  75114. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  75115. return GridMaterial;
  75116. }(BABYLON.PushMaterial));
  75117. BABYLON.GridMaterial = GridMaterial;
  75118. })(BABYLON || (BABYLON = {}));
  75119. //# sourceMappingURL=babylon.gridmaterial.js.map
  75120. 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}";
  75121. 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}";
  75122. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  75123. var BABYLON;
  75124. (function (BABYLON) {
  75125. /**
  75126. * Background material defines definition.
  75127. */
  75128. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  75129. __extends(BackgroundMaterialDefines, _super);
  75130. /**
  75131. * Constructor of the defines.
  75132. */
  75133. function BackgroundMaterialDefines() {
  75134. var _this = _super.call(this) || this;
  75135. /**
  75136. * True if the diffuse texture is in use.
  75137. */
  75138. _this.DIFFUSE = false;
  75139. /**
  75140. * The direct UV channel to use.
  75141. */
  75142. _this.DIFFUSEDIRECTUV = 0;
  75143. /**
  75144. * True if the diffuse texture is in gamma space.
  75145. */
  75146. _this.GAMMADIFFUSE = false;
  75147. /**
  75148. * True if the diffuse texture has opacity in the alpha channel.
  75149. */
  75150. _this.DIFFUSEHASALPHA = false;
  75151. /**
  75152. * True if you want the material to fade to transparent at grazing angle.
  75153. */
  75154. _this.OPACITYFRESNEL = false;
  75155. /**
  75156. * True if an extra blur needs to be added in the reflection.
  75157. */
  75158. _this.REFLECTIONBLUR = false;
  75159. /**
  75160. * False if the current Webgl implementation does not support the texture lod extension.
  75161. */
  75162. _this.TEXTURELODSUPPORT = false;
  75163. /**
  75164. * True to ensure the data are premultiplied.
  75165. */
  75166. _this.PREMULTIPLYALPHA = false;
  75167. /**
  75168. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  75169. */
  75170. _this.USERGBCOLOR = false;
  75171. // Image Processing Configuration.
  75172. _this.IMAGEPROCESSING = false;
  75173. _this.VIGNETTE = false;
  75174. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  75175. _this.VIGNETTEBLENDMODEOPAQUE = false;
  75176. _this.TONEMAPPING = false;
  75177. _this.CONTRAST = false;
  75178. _this.COLORCURVES = false;
  75179. _this.COLORGRADING = false;
  75180. _this.COLORGRADING3D = false;
  75181. _this.SAMPLER3DGREENDEPTH = false;
  75182. _this.SAMPLER3DBGRMAP = false;
  75183. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  75184. _this.EXPOSURE = false;
  75185. // Reflection.
  75186. _this.REFLECTION = false;
  75187. _this.REFLECTIONMAP_3D = false;
  75188. _this.REFLECTIONMAP_SPHERICAL = false;
  75189. _this.REFLECTIONMAP_PLANAR = false;
  75190. _this.REFLECTIONMAP_CUBIC = false;
  75191. _this.REFLECTIONMAP_PROJECTION = false;
  75192. _this.REFLECTIONMAP_SKYBOX = false;
  75193. _this.REFLECTIONMAP_EXPLICIT = false;
  75194. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75195. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75196. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75197. _this.INVERTCUBICMAP = false;
  75198. _this.REFLECTIONMAP_OPPOSITEZ = false;
  75199. _this.LODINREFLECTIONALPHA = false;
  75200. _this.GAMMAREFLECTION = false;
  75201. // Default BJS.
  75202. _this.MAINUV1 = false;
  75203. _this.MAINUV2 = false;
  75204. _this.UV1 = false;
  75205. _this.UV2 = false;
  75206. _this.CLIPPLANE = false;
  75207. _this.POINTSIZE = false;
  75208. _this.FOG = false;
  75209. _this.NORMAL = false;
  75210. _this.NUM_BONE_INFLUENCERS = 0;
  75211. _this.BonesPerMesh = 0;
  75212. _this.INSTANCES = false;
  75213. _this.SHADOWFLOAT = false;
  75214. _this.rebuild();
  75215. return _this;
  75216. }
  75217. return BackgroundMaterialDefines;
  75218. }(BABYLON.MaterialDefines));
  75219. /**
  75220. * Background material
  75221. */
  75222. var BackgroundMaterial = /** @class */ (function (_super) {
  75223. __extends(BackgroundMaterial, _super);
  75224. /**
  75225. * constructor
  75226. * @param name The name of the material
  75227. * @param scene The scene to add the material to
  75228. */
  75229. function BackgroundMaterial(name, scene) {
  75230. var _this = _super.call(this, name, scene) || this;
  75231. _this.primaryColor = BABYLON.Color3.White();
  75232. _this.primaryLevel = 1;
  75233. _this.secondaryColor = BABYLON.Color3.Gray();
  75234. _this.secondaryLevel = 1;
  75235. _this.tertiaryColor = BABYLON.Color3.Black();
  75236. _this.tertiaryLevel = 1;
  75237. _this.reflectionTexture = null;
  75238. _this.reflectionBlur = 0;
  75239. _this.diffuseTexture = null;
  75240. /**
  75241. * Specify the list of lights casting shadow on the material.
  75242. * All scene shadow lights will be included if null.
  75243. */
  75244. _this._shadowLights = null;
  75245. _this.shadowLights = null;
  75246. _this.shadowBlurScale = 1;
  75247. _this.shadowLevel = 0;
  75248. _this.opacityFresnel = true;
  75249. _this.useRGBColor = true;
  75250. /**
  75251. * Number of Simultaneous lights allowed on the material.
  75252. */
  75253. _this._maxSimultaneousLights = 4;
  75254. _this.maxSimultaneousLights = 4;
  75255. /**
  75256. * Keep track of the image processing observer to allow dispose and replace.
  75257. */
  75258. _this._imageProcessingObserver = null;
  75259. // Temp values kept as cache in the material.
  75260. _this._renderTargets = new BABYLON.SmartArray(16);
  75261. // Setup the default processing configuration to the scene.
  75262. _this._attachImageProcessingConfiguration(null);
  75263. _this.getRenderTargetTextures = function () {
  75264. _this._renderTargets.reset();
  75265. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  75266. _this._renderTargets.push(_this._diffuseTexture);
  75267. }
  75268. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  75269. _this._renderTargets.push(_this._reflectionTexture);
  75270. }
  75271. return _this._renderTargets;
  75272. };
  75273. return _this;
  75274. }
  75275. /**
  75276. * Attaches a new image processing configuration to the PBR Material.
  75277. * @param configuration (if null the scene configuration will be use)
  75278. */
  75279. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  75280. var _this = this;
  75281. if (configuration === this._imageProcessingConfiguration) {
  75282. return;
  75283. }
  75284. // Detaches observer.
  75285. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75286. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75287. }
  75288. // Pick the scene configuration if needed.
  75289. if (!configuration) {
  75290. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  75291. }
  75292. else {
  75293. this._imageProcessingConfiguration = configuration;
  75294. }
  75295. // Attaches observer.
  75296. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75297. _this._markAllSubMeshesAsImageProcessingDirty();
  75298. });
  75299. };
  75300. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  75301. /**
  75302. * Gets the image processing configuration used either in this material.
  75303. */
  75304. get: function () {
  75305. return this._imageProcessingConfiguration;
  75306. },
  75307. /**
  75308. * Sets the Default image processing configuration used either in the this material.
  75309. *
  75310. * If sets to null, the scene one is in use.
  75311. */
  75312. set: function (value) {
  75313. this._attachImageProcessingConfiguration(value);
  75314. // Ensure the effect will be rebuilt.
  75315. this._markAllSubMeshesAsTexturesDirty();
  75316. },
  75317. enumerable: true,
  75318. configurable: true
  75319. });
  75320. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  75321. /**
  75322. * Gets wether the color curves effect is enabled.
  75323. */
  75324. get: function () {
  75325. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75326. },
  75327. /**
  75328. * Sets wether the color curves effect is enabled.
  75329. */
  75330. set: function (value) {
  75331. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75332. },
  75333. enumerable: true,
  75334. configurable: true
  75335. });
  75336. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  75337. /**
  75338. * Gets wether the color grading effect is enabled.
  75339. */
  75340. get: function () {
  75341. return this.imageProcessingConfiguration.colorGradingEnabled;
  75342. },
  75343. /**
  75344. * Gets wether the color grading effect is enabled.
  75345. */
  75346. set: function (value) {
  75347. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75348. },
  75349. enumerable: true,
  75350. configurable: true
  75351. });
  75352. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  75353. /**
  75354. * Gets wether tonemapping is enabled or not.
  75355. */
  75356. get: function () {
  75357. return this._imageProcessingConfiguration.toneMappingEnabled;
  75358. },
  75359. /**
  75360. * Sets wether tonemapping is enabled or not
  75361. */
  75362. set: function (value) {
  75363. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75364. },
  75365. enumerable: true,
  75366. configurable: true
  75367. });
  75368. ;
  75369. ;
  75370. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  75371. /**
  75372. * The camera exposure used on this material.
  75373. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  75374. * This corresponds to a photographic exposure.
  75375. */
  75376. get: function () {
  75377. return this._imageProcessingConfiguration.exposure;
  75378. },
  75379. /**
  75380. * The camera exposure used on this material.
  75381. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  75382. * This corresponds to a photographic exposure.
  75383. */
  75384. set: function (value) {
  75385. this._imageProcessingConfiguration.exposure = value;
  75386. },
  75387. enumerable: true,
  75388. configurable: true
  75389. });
  75390. ;
  75391. ;
  75392. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  75393. /**
  75394. * Gets The camera contrast used on this material.
  75395. */
  75396. get: function () {
  75397. return this._imageProcessingConfiguration.contrast;
  75398. },
  75399. /**
  75400. * Sets The camera contrast used on this material.
  75401. */
  75402. set: function (value) {
  75403. this._imageProcessingConfiguration.contrast = value;
  75404. },
  75405. enumerable: true,
  75406. configurable: true
  75407. });
  75408. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  75409. /**
  75410. * Gets the Color Grading 2D Lookup Texture.
  75411. */
  75412. get: function () {
  75413. return this._imageProcessingConfiguration.colorGradingTexture;
  75414. },
  75415. /**
  75416. * Sets the Color Grading 2D Lookup Texture.
  75417. */
  75418. set: function (value) {
  75419. this.imageProcessingConfiguration.colorGradingTexture = value;
  75420. },
  75421. enumerable: true,
  75422. configurable: true
  75423. });
  75424. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  75425. /**
  75426. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  75427. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  75428. * 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;
  75429. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  75430. */
  75431. get: function () {
  75432. return this.imageProcessingConfiguration.colorCurves;
  75433. },
  75434. /**
  75435. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  75436. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  75437. * 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;
  75438. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  75439. */
  75440. set: function (value) {
  75441. this.imageProcessingConfiguration.colorCurves = value;
  75442. },
  75443. enumerable: true,
  75444. configurable: true
  75445. });
  75446. /**
  75447. * The entire material has been created in order to prevent overdraw.
  75448. * @returns false
  75449. */
  75450. BackgroundMaterial.prototype.needAlphaTesting = function () {
  75451. return false;
  75452. };
  75453. /**
  75454. * The entire material has been created in order to prevent overdraw.
  75455. * @returns true if blending is enable
  75456. */
  75457. BackgroundMaterial.prototype.needAlphaBlending = function () {
  75458. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  75459. };
  75460. /**
  75461. * Checks wether the material is ready to be rendered for a given mesh.
  75462. * @param mesh The mesh to render
  75463. * @param subMesh The submesh to check against
  75464. * @param useInstances Specify wether or not the material is used with instances
  75465. */
  75466. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75467. var _this = this;
  75468. if (useInstances === void 0) { useInstances = false; }
  75469. if (subMesh.effect && this.isFrozen) {
  75470. if (this._wasPreviouslyReady) {
  75471. return true;
  75472. }
  75473. }
  75474. if (!subMesh._materialDefines) {
  75475. subMesh._materialDefines = new BackgroundMaterialDefines();
  75476. }
  75477. var scene = this.getScene();
  75478. var defines = subMesh._materialDefines;
  75479. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  75480. if (defines._renderId === scene.getRenderId()) {
  75481. return true;
  75482. }
  75483. }
  75484. var engine = scene.getEngine();
  75485. // Lights
  75486. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  75487. defines._needNormals = true;
  75488. // Textures
  75489. if (defines._areTexturesDirty) {
  75490. defines._needUVs = false;
  75491. if (scene.texturesEnabled) {
  75492. if (scene.getEngine().getCaps().textureLOD) {
  75493. defines.TEXTURELODSUPPORT = true;
  75494. }
  75495. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75496. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  75497. return false;
  75498. }
  75499. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  75500. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  75501. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  75502. defines.OPACITYFRESNEL = this._opacityFresnel;
  75503. }
  75504. else {
  75505. defines.DIFFUSE = false;
  75506. defines.DIFFUSEHASALPHA = false;
  75507. defines.GAMMADIFFUSE = false;
  75508. defines.OPACITYFRESNEL = false;
  75509. }
  75510. var reflectionTexture = this._reflectionTexture;
  75511. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75512. if (!reflectionTexture.isReadyOrNotBlocking()) {
  75513. return false;
  75514. }
  75515. defines.REFLECTION = true;
  75516. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  75517. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  75518. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  75519. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  75520. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  75521. defines.INVERTCUBICMAP = true;
  75522. }
  75523. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  75524. switch (reflectionTexture.coordinatesMode) {
  75525. case BABYLON.Texture.CUBIC_MODE:
  75526. case BABYLON.Texture.INVCUBIC_MODE:
  75527. defines.REFLECTIONMAP_CUBIC = true;
  75528. break;
  75529. case BABYLON.Texture.EXPLICIT_MODE:
  75530. defines.REFLECTIONMAP_EXPLICIT = true;
  75531. break;
  75532. case BABYLON.Texture.PLANAR_MODE:
  75533. defines.REFLECTIONMAP_PLANAR = true;
  75534. break;
  75535. case BABYLON.Texture.PROJECTION_MODE:
  75536. defines.REFLECTIONMAP_PROJECTION = true;
  75537. break;
  75538. case BABYLON.Texture.SKYBOX_MODE:
  75539. defines.REFLECTIONMAP_SKYBOX = true;
  75540. break;
  75541. case BABYLON.Texture.SPHERICAL_MODE:
  75542. defines.REFLECTIONMAP_SPHERICAL = true;
  75543. break;
  75544. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  75545. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  75546. break;
  75547. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  75548. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  75549. break;
  75550. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  75551. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  75552. break;
  75553. }
  75554. }
  75555. else {
  75556. defines.REFLECTION = false;
  75557. defines.REFLECTIONBLUR = false;
  75558. defines.REFLECTIONMAP_3D = false;
  75559. defines.REFLECTIONMAP_SPHERICAL = false;
  75560. defines.REFLECTIONMAP_PLANAR = false;
  75561. defines.REFLECTIONMAP_CUBIC = false;
  75562. defines.REFLECTIONMAP_PROJECTION = false;
  75563. defines.REFLECTIONMAP_SKYBOX = false;
  75564. defines.REFLECTIONMAP_EXPLICIT = false;
  75565. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  75566. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  75567. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  75568. defines.INVERTCUBICMAP = false;
  75569. defines.REFLECTIONMAP_OPPOSITEZ = false;
  75570. defines.LODINREFLECTIONALPHA = false;
  75571. defines.GAMMAREFLECTION = false;
  75572. }
  75573. }
  75574. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  75575. defines.USERGBCOLOR = this._useRGBColor;
  75576. }
  75577. if (defines._areImageProcessingDirty) {
  75578. if (!this._imageProcessingConfiguration.isReady()) {
  75579. return false;
  75580. }
  75581. this._imageProcessingConfiguration.prepareDefines(defines);
  75582. }
  75583. // Misc.
  75584. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  75585. // Values that need to be evaluated on every frame
  75586. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  75587. // Attribs
  75588. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  75589. if (mesh) {
  75590. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75591. mesh.createNormals(true);
  75592. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  75593. }
  75594. }
  75595. }
  75596. // Get correct effect
  75597. if (defines.isDirty) {
  75598. defines.markAsProcessed();
  75599. scene.resetCachedMaterial();
  75600. // Fallbacks
  75601. var fallbacks = new BABYLON.EffectFallbacks();
  75602. if (defines.FOG) {
  75603. fallbacks.addFallback(0, "FOG");
  75604. }
  75605. if (defines.POINTSIZE) {
  75606. fallbacks.addFallback(1, "POINTSIZE");
  75607. }
  75608. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  75609. if (defines.NUM_BONE_INFLUENCERS > 0) {
  75610. fallbacks.addCPUSkinningFallback(0, mesh);
  75611. }
  75612. //Attributes
  75613. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75614. if (defines.NORMAL) {
  75615. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75616. }
  75617. if (defines.UV1) {
  75618. attribs.push(BABYLON.VertexBuffer.UVKind);
  75619. }
  75620. if (defines.UV2) {
  75621. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75622. }
  75623. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  75624. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  75625. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  75626. "vFogInfos", "vFogColor", "pointSize",
  75627. "vClipPlane", "mBones",
  75628. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  75629. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  75630. "shadowLevel", "alpha",
  75631. "vDiffuseInfos", "diffuseMatrix",
  75632. ];
  75633. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  75634. var uniformBuffers = ["Material", "Scene"];
  75635. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  75636. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  75637. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  75638. uniformsNames: uniforms,
  75639. uniformBuffersNames: uniformBuffers,
  75640. samplers: samplers,
  75641. defines: defines,
  75642. maxSimultaneousLights: this._maxSimultaneousLights
  75643. });
  75644. var onCompiled = function (effect) {
  75645. if (_this.onCompiled) {
  75646. _this.onCompiled(effect);
  75647. }
  75648. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  75649. };
  75650. var join = defines.toString();
  75651. subMesh.setEffect(scene.getEngine().createEffect("background", {
  75652. attributes: attribs,
  75653. uniformsNames: uniforms,
  75654. uniformBuffersNames: uniformBuffers,
  75655. samplers: samplers,
  75656. defines: join,
  75657. fallbacks: fallbacks,
  75658. onCompiled: onCompiled,
  75659. onError: this.onError,
  75660. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  75661. }, engine), defines);
  75662. this.buildUniformLayout();
  75663. }
  75664. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75665. return false;
  75666. }
  75667. defines._renderId = scene.getRenderId();
  75668. this._wasPreviouslyReady = true;
  75669. return true;
  75670. };
  75671. /**
  75672. * Build the uniform buffer used in the material.
  75673. */
  75674. BackgroundMaterial.prototype.buildUniformLayout = function () {
  75675. // Order is important !
  75676. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  75677. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  75678. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  75679. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  75680. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  75681. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  75682. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  75683. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  75684. this._uniformBuffer.addUniform("pointSize", 1);
  75685. this._uniformBuffer.addUniform("shadowLevel", 1);
  75686. this._uniformBuffer.addUniform("alpha", 1);
  75687. this._uniformBuffer.create();
  75688. };
  75689. /**
  75690. * Unbind the material.
  75691. */
  75692. BackgroundMaterial.prototype.unbind = function () {
  75693. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  75694. this._uniformBuffer.setTexture("diffuseSampler", null);
  75695. }
  75696. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  75697. this._uniformBuffer.setTexture("reflectionSampler", null);
  75698. }
  75699. _super.prototype.unbind.call(this);
  75700. };
  75701. /**
  75702. * Bind only the world matrix to the material.
  75703. * @param world The world matrix to bind.
  75704. */
  75705. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  75706. this._activeEffect.setMatrix("world", world);
  75707. };
  75708. /**
  75709. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  75710. * @param world The world matrix to bind.
  75711. * @param subMesh The submesh to bind for.
  75712. */
  75713. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75714. var scene = this.getScene();
  75715. var defines = subMesh._materialDefines;
  75716. if (!defines) {
  75717. return;
  75718. }
  75719. var effect = subMesh.effect;
  75720. if (!effect) {
  75721. return;
  75722. }
  75723. this._activeEffect = effect;
  75724. // Matrices
  75725. this.bindOnlyWorldMatrix(world);
  75726. // Bones
  75727. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  75728. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  75729. if (mustRebind) {
  75730. this._uniformBuffer.bindToEffect(effect, "Material");
  75731. this.bindViewProjection(effect);
  75732. var reflectionTexture = this._reflectionTexture;
  75733. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  75734. // Texture uniforms
  75735. if (scene.texturesEnabled) {
  75736. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75737. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  75738. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  75739. }
  75740. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75741. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  75742. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  75743. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  75744. }
  75745. }
  75746. if (this.shadowLevel > 0) {
  75747. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  75748. }
  75749. this._uniformBuffer.updateFloat("alpha", this.alpha);
  75750. // Point size
  75751. if (this.pointsCloud) {
  75752. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  75753. }
  75754. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  75755. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  75756. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  75757. }
  75758. // Textures
  75759. if (scene.texturesEnabled) {
  75760. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75761. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  75762. }
  75763. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75764. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  75765. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75766. }
  75767. else if (!defines.REFLECTIONBLUR) {
  75768. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75769. }
  75770. else {
  75771. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  75772. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  75773. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  75774. }
  75775. }
  75776. }
  75777. // Clip plane
  75778. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  75779. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  75780. }
  75781. if (mustRebind || !this.isFrozen) {
  75782. if (scene.lightsEnabled) {
  75783. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  75784. }
  75785. // View
  75786. this.bindView(effect);
  75787. // Fog
  75788. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75789. // image processing
  75790. this._imageProcessingConfiguration.bind(this._activeEffect);
  75791. }
  75792. this._uniformBuffer.update();
  75793. this._afterBind(mesh);
  75794. };
  75795. /**
  75796. * Dispose the material.
  75797. * @forceDisposeEffect Force disposal of the associated effect.
  75798. * @forceDisposeTextures Force disposal of the associated textures.
  75799. */
  75800. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75801. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  75802. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  75803. if (forceDisposeTextures) {
  75804. if (this.diffuseTexture) {
  75805. this.diffuseTexture.dispose();
  75806. }
  75807. if (this.reflectionTexture) {
  75808. this.reflectionTexture.dispose();
  75809. }
  75810. }
  75811. this._renderTargets.dispose();
  75812. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75813. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75814. }
  75815. _super.prototype.dispose.call(this, forceDisposeEffect);
  75816. };
  75817. /**
  75818. * Clones the material.
  75819. * @name The cloned name.
  75820. * @returns The cloned material.
  75821. */
  75822. BackgroundMaterial.prototype.clone = function (name) {
  75823. var _this = this;
  75824. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  75825. };
  75826. /**
  75827. * Serializes the current material to its JSON representation.
  75828. * @returns The JSON representation.
  75829. */
  75830. BackgroundMaterial.prototype.serialize = function () {
  75831. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75832. serializationObject.customType = "BABYLON.BackgroundMaterial";
  75833. return serializationObject;
  75834. };
  75835. /**
  75836. * Gets the class name of the material
  75837. * @returns "BackgroundMaterial"
  75838. */
  75839. BackgroundMaterial.prototype.getClassName = function () {
  75840. return "BackgroundMaterial";
  75841. };
  75842. /**
  75843. * Parse a JSON input to create back a background material.
  75844. * @param source
  75845. * @param scene
  75846. * @param rootUrl
  75847. * @returns the instantiated BackgroundMaterial.
  75848. */
  75849. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  75850. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  75851. };
  75852. __decorate([
  75853. BABYLON.serializeAsColor3()
  75854. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  75855. __decorate([
  75856. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75857. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  75858. __decorate([
  75859. BABYLON.serialize()
  75860. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  75861. __decorate([
  75862. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75863. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  75864. __decorate([
  75865. BABYLON.serializeAsColor3()
  75866. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  75867. __decorate([
  75868. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75869. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  75870. __decorate([
  75871. BABYLON.serialize()
  75872. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  75873. __decorate([
  75874. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75875. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  75876. __decorate([
  75877. BABYLON.serializeAsColor3()
  75878. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  75879. __decorate([
  75880. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75881. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  75882. __decorate([
  75883. BABYLON.serialize()
  75884. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  75885. __decorate([
  75886. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75887. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  75888. __decorate([
  75889. BABYLON.serializeAsTexture()
  75890. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  75891. __decorate([
  75892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75893. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  75894. __decorate([
  75895. BABYLON.serialize()
  75896. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  75897. __decorate([
  75898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75899. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  75900. __decorate([
  75901. BABYLON.serializeAsTexture()
  75902. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  75903. __decorate([
  75904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75905. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  75906. __decorate([
  75907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75908. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  75909. __decorate([
  75910. BABYLON.serialize()
  75911. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  75912. __decorate([
  75913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75914. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  75915. __decorate([
  75916. BABYLON.serialize()
  75917. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  75918. __decorate([
  75919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75920. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  75921. __decorate([
  75922. BABYLON.serialize()
  75923. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  75924. __decorate([
  75925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75926. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  75927. __decorate([
  75928. BABYLON.serialize()
  75929. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  75930. __decorate([
  75931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75932. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  75933. __decorate([
  75934. BABYLON.serialize()
  75935. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  75936. __decorate([
  75937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75938. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  75939. __decorate([
  75940. BABYLON.serializeAsImageProcessingConfiguration()
  75941. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  75942. return BackgroundMaterial;
  75943. }(BABYLON.PushMaterial));
  75944. BABYLON.BackgroundMaterial = BackgroundMaterial;
  75945. })(BABYLON || (BABYLON = {}));
  75946. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  75947. BABYLON.Effect.ShadersStore['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";
  75948. BABYLON.Effect.ShadersStore['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>\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 environmentColor=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;\nenvironmentColor=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){\nenvironmentColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nenvironmentColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nenvironmentColor=sampleReflection(reflectionSampler,reflectionCoords).rgb;\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentColor=toLinearSpace(environmentColor.rgb);\n#endif\n\nenvironmentColor*=vReflectionInfos.x;\n#endif\n\nvec3 groundColor=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\ngroundColor=diffuseMap.rgb;\n#endif\n\nvec3 colorBase=environmentColor*groundColor;\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#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n#ifdef OPACITYFRESNEL\n\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\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}";
  75949. BABYLON.Effect.IncludesShadersStore['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";
  75950. BABYLON.Effect.IncludesShadersStore['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};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};";
  75951. BABYLON.Effect.IncludesShadersStore['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";
  75952. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  75953. var BABYLON;
  75954. (function (BABYLON) {
  75955. var GLTFLoaderCoordinateSystemMode;
  75956. (function (GLTFLoaderCoordinateSystemMode) {
  75957. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  75958. // 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.
  75959. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  75960. // The glTF right-handed data is not transformed in any form and is loaded directly.
  75961. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  75962. // Sets the useRightHandedSystem flag on the scene.
  75963. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  75964. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  75965. var GLTFFileLoader = /** @class */ (function () {
  75966. function GLTFFileLoader() {
  75967. // V2 options
  75968. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  75969. this.name = "gltf";
  75970. this.extensions = {
  75971. ".gltf": { isBinary: false },
  75972. ".glb": { isBinary: true }
  75973. };
  75974. }
  75975. GLTFFileLoader.prototype.dispose = function () {
  75976. if (this._loader) {
  75977. this._loader.dispose();
  75978. }
  75979. };
  75980. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75981. try {
  75982. var loaderData = GLTFFileLoader._parse(data);
  75983. if (this.onParsed) {
  75984. this.onParsed(loaderData);
  75985. }
  75986. this._loader = this._getLoader(loaderData);
  75987. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  75988. }
  75989. catch (e) {
  75990. onError(e.message);
  75991. }
  75992. };
  75993. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  75994. try {
  75995. var loaderData = GLTFFileLoader._parse(data);
  75996. if (this.onParsed) {
  75997. this.onParsed(loaderData);
  75998. }
  75999. this._loader = this._getLoader(loaderData);
  76000. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  76001. }
  76002. catch (e) {
  76003. onError(e.message);
  76004. }
  76005. };
  76006. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  76007. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  76008. };
  76009. GLTFFileLoader._parse = function (data) {
  76010. if (data instanceof ArrayBuffer) {
  76011. return GLTFFileLoader._parseBinary(data);
  76012. }
  76013. return {
  76014. json: JSON.parse(data),
  76015. bin: null
  76016. };
  76017. };
  76018. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  76019. var loaderVersion = { major: 2, minor: 0 };
  76020. var asset = loaderData.json.asset || {};
  76021. var version = GLTFFileLoader._parseVersion(asset.version);
  76022. if (!version) {
  76023. throw new Error("Invalid version: " + asset.version);
  76024. }
  76025. if (asset.minVersion !== undefined) {
  76026. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  76027. if (!minVersion) {
  76028. throw new Error("Invalid minimum version: " + asset.minVersion);
  76029. }
  76030. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  76031. throw new Error("Incompatible minimum version: " + asset.minVersion);
  76032. }
  76033. }
  76034. var createLoaders = {
  76035. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  76036. 2: GLTFFileLoader.CreateGLTFLoaderV2
  76037. };
  76038. var createLoader = createLoaders[version.major];
  76039. if (!createLoader) {
  76040. throw new Error("Unsupported version: " + asset.version);
  76041. }
  76042. return createLoader(this);
  76043. };
  76044. GLTFFileLoader._parseBinary = function (data) {
  76045. var Binary = {
  76046. Magic: 0x46546C67
  76047. };
  76048. var binaryReader = new BinaryReader(data);
  76049. var magic = binaryReader.readUint32();
  76050. if (magic !== Binary.Magic) {
  76051. throw new Error("Unexpected magic: " + magic);
  76052. }
  76053. var version = binaryReader.readUint32();
  76054. switch (version) {
  76055. case 1: return GLTFFileLoader._parseV1(binaryReader);
  76056. case 2: return GLTFFileLoader._parseV2(binaryReader);
  76057. }
  76058. throw new Error("Unsupported version: " + version);
  76059. };
  76060. GLTFFileLoader._parseV1 = function (binaryReader) {
  76061. var ContentFormat = {
  76062. JSON: 0
  76063. };
  76064. var length = binaryReader.readUint32();
  76065. if (length != binaryReader.getLength()) {
  76066. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  76067. }
  76068. var contentLength = binaryReader.readUint32();
  76069. var contentFormat = binaryReader.readUint32();
  76070. var content;
  76071. switch (contentFormat) {
  76072. case ContentFormat.JSON: {
  76073. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  76074. break;
  76075. }
  76076. default: {
  76077. throw new Error("Unexpected content format: " + contentFormat);
  76078. }
  76079. }
  76080. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  76081. var body = binaryReader.readUint8Array(bytesRemaining);
  76082. return {
  76083. json: content,
  76084. bin: body
  76085. };
  76086. };
  76087. GLTFFileLoader._parseV2 = function (binaryReader) {
  76088. var ChunkFormat = {
  76089. JSON: 0x4E4F534A,
  76090. BIN: 0x004E4942
  76091. };
  76092. var length = binaryReader.readUint32();
  76093. if (length !== binaryReader.getLength()) {
  76094. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  76095. }
  76096. // JSON chunk
  76097. var chunkLength = binaryReader.readUint32();
  76098. var chunkFormat = binaryReader.readUint32();
  76099. if (chunkFormat !== ChunkFormat.JSON) {
  76100. throw new Error("First chunk format is not JSON");
  76101. }
  76102. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  76103. // Look for BIN chunk
  76104. var bin = null;
  76105. while (binaryReader.getPosition() < binaryReader.getLength()) {
  76106. var chunkLength_1 = binaryReader.readUint32();
  76107. var chunkFormat_1 = binaryReader.readUint32();
  76108. switch (chunkFormat_1) {
  76109. case ChunkFormat.JSON: {
  76110. throw new Error("Unexpected JSON chunk");
  76111. }
  76112. case ChunkFormat.BIN: {
  76113. bin = binaryReader.readUint8Array(chunkLength_1);
  76114. break;
  76115. }
  76116. default: {
  76117. // ignore unrecognized chunkFormat
  76118. binaryReader.skipBytes(chunkLength_1);
  76119. break;
  76120. }
  76121. }
  76122. }
  76123. return {
  76124. json: json,
  76125. bin: bin
  76126. };
  76127. };
  76128. GLTFFileLoader._parseVersion = function (version) {
  76129. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  76130. if (!match) {
  76131. return null;
  76132. }
  76133. return {
  76134. major: parseInt(match[1]),
  76135. minor: parseInt(match[2])
  76136. };
  76137. };
  76138. GLTFFileLoader._compareVersion = function (a, b) {
  76139. if (a.major > b.major)
  76140. return 1;
  76141. if (a.major < b.major)
  76142. return -1;
  76143. if (a.minor > b.minor)
  76144. return 1;
  76145. if (a.minor < b.minor)
  76146. return -1;
  76147. return 0;
  76148. };
  76149. GLTFFileLoader._decodeBufferToText = function (buffer) {
  76150. var result = "";
  76151. var length = buffer.byteLength;
  76152. for (var i = 0; i < length; i++) {
  76153. result += String.fromCharCode(buffer[i]);
  76154. }
  76155. return result;
  76156. };
  76157. // V1 options
  76158. GLTFFileLoader.HomogeneousCoordinates = false;
  76159. GLTFFileLoader.IncrementalLoading = true;
  76160. return GLTFFileLoader;
  76161. }());
  76162. BABYLON.GLTFFileLoader = GLTFFileLoader;
  76163. var BinaryReader = /** @class */ (function () {
  76164. function BinaryReader(arrayBuffer) {
  76165. this._arrayBuffer = arrayBuffer;
  76166. this._dataView = new DataView(arrayBuffer);
  76167. this._byteOffset = 0;
  76168. }
  76169. BinaryReader.prototype.getPosition = function () {
  76170. return this._byteOffset;
  76171. };
  76172. BinaryReader.prototype.getLength = function () {
  76173. return this._arrayBuffer.byteLength;
  76174. };
  76175. BinaryReader.prototype.readUint32 = function () {
  76176. var value = this._dataView.getUint32(this._byteOffset, true);
  76177. this._byteOffset += 4;
  76178. return value;
  76179. };
  76180. BinaryReader.prototype.readUint8Array = function (length) {
  76181. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  76182. this._byteOffset += length;
  76183. return value;
  76184. };
  76185. BinaryReader.prototype.skipBytes = function (length) {
  76186. this._byteOffset += length;
  76187. };
  76188. return BinaryReader;
  76189. }());
  76190. if (BABYLON.SceneLoader) {
  76191. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  76192. }
  76193. })(BABYLON || (BABYLON = {}));
  76194. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  76195. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76196. var BABYLON;
  76197. (function (BABYLON) {
  76198. var GLTF1;
  76199. (function (GLTF1) {
  76200. /**
  76201. * Enums
  76202. */
  76203. var EComponentType;
  76204. (function (EComponentType) {
  76205. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  76206. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  76207. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  76208. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  76209. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  76210. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  76211. var EShaderType;
  76212. (function (EShaderType) {
  76213. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  76214. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  76215. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  76216. var EParameterType;
  76217. (function (EParameterType) {
  76218. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  76219. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  76220. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  76221. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  76222. EParameterType[EParameterType["INT"] = 5124] = "INT";
  76223. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  76224. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  76225. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  76226. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  76227. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  76228. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  76229. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  76230. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  76231. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  76232. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  76233. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  76234. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  76235. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  76236. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  76237. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  76238. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  76239. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  76240. var ETextureWrapMode;
  76241. (function (ETextureWrapMode) {
  76242. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  76243. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  76244. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  76245. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  76246. var ETextureFilterType;
  76247. (function (ETextureFilterType) {
  76248. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  76249. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  76250. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  76251. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  76252. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  76253. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  76254. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  76255. var ETextureFormat;
  76256. (function (ETextureFormat) {
  76257. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  76258. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  76259. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  76260. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  76261. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  76262. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  76263. var ECullingType;
  76264. (function (ECullingType) {
  76265. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  76266. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  76267. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  76268. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  76269. var EBlendingFunction;
  76270. (function (EBlendingFunction) {
  76271. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  76272. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  76273. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  76274. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  76275. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  76276. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  76277. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  76278. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  76279. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  76280. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  76281. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  76282. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  76283. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  76284. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  76285. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  76286. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  76287. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  76288. })(BABYLON || (BABYLON = {}));
  76289. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  76290. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76291. var BABYLON;
  76292. (function (BABYLON) {
  76293. var GLTF1;
  76294. (function (GLTF1) {
  76295. /**
  76296. * Tokenizer. Used for shaders compatibility
  76297. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  76298. */
  76299. var ETokenType;
  76300. (function (ETokenType) {
  76301. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  76302. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  76303. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  76304. })(ETokenType || (ETokenType = {}));
  76305. var Tokenizer = /** @class */ (function () {
  76306. function Tokenizer(toParse) {
  76307. this._pos = 0;
  76308. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  76309. this._toParse = toParse;
  76310. this._maxPos = toParse.length;
  76311. }
  76312. Tokenizer.prototype.getNextToken = function () {
  76313. if (this.isEnd())
  76314. return ETokenType.END_OF_INPUT;
  76315. this.currentString = this.read();
  76316. this.currentToken = ETokenType.UNKNOWN;
  76317. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  76318. this.currentToken = ETokenType.IDENTIFIER;
  76319. this.currentIdentifier = this.currentString;
  76320. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  76321. this.currentIdentifier += this.currentString;
  76322. this.forward();
  76323. }
  76324. }
  76325. return this.currentToken;
  76326. };
  76327. Tokenizer.prototype.peek = function () {
  76328. return this._toParse[this._pos];
  76329. };
  76330. Tokenizer.prototype.read = function () {
  76331. return this._toParse[this._pos++];
  76332. };
  76333. Tokenizer.prototype.forward = function () {
  76334. this._pos++;
  76335. };
  76336. Tokenizer.prototype.isEnd = function () {
  76337. return this._pos >= this._maxPos;
  76338. };
  76339. return Tokenizer;
  76340. }());
  76341. /**
  76342. * Values
  76343. */
  76344. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  76345. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  76346. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  76347. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  76348. /**
  76349. * Parse
  76350. */
  76351. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  76352. for (var buf in parsedBuffers) {
  76353. var parsedBuffer = parsedBuffers[buf];
  76354. gltfRuntime.buffers[buf] = parsedBuffer;
  76355. gltfRuntime.buffersCount++;
  76356. }
  76357. };
  76358. var parseShaders = function (parsedShaders, gltfRuntime) {
  76359. for (var sha in parsedShaders) {
  76360. var parsedShader = parsedShaders[sha];
  76361. gltfRuntime.shaders[sha] = parsedShader;
  76362. gltfRuntime.shaderscount++;
  76363. }
  76364. };
  76365. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  76366. for (var object in parsedObjects) {
  76367. var parsedObject = parsedObjects[object];
  76368. gltfRuntime[runtimeProperty][object] = parsedObject;
  76369. }
  76370. };
  76371. /**
  76372. * Utils
  76373. */
  76374. var normalizeUVs = function (buffer) {
  76375. if (!buffer) {
  76376. return;
  76377. }
  76378. for (var i = 0; i < buffer.length / 2; i++) {
  76379. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  76380. }
  76381. };
  76382. var getAttribute = function (attributeParameter) {
  76383. if (attributeParameter.semantic === "NORMAL") {
  76384. return "normal";
  76385. }
  76386. else if (attributeParameter.semantic === "POSITION") {
  76387. return "position";
  76388. }
  76389. else if (attributeParameter.semantic === "JOINT") {
  76390. return "matricesIndices";
  76391. }
  76392. else if (attributeParameter.semantic === "WEIGHT") {
  76393. return "matricesWeights";
  76394. }
  76395. else if (attributeParameter.semantic === "COLOR") {
  76396. return "color";
  76397. }
  76398. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  76399. var channel = Number(attributeParameter.semantic.split("_")[1]);
  76400. return "uv" + (channel === 0 ? "" : channel + 1);
  76401. }
  76402. return null;
  76403. };
  76404. /**
  76405. * Loads and creates animations
  76406. */
  76407. var loadAnimations = function (gltfRuntime) {
  76408. for (var anim in gltfRuntime.animations) {
  76409. var animation = gltfRuntime.animations[anim];
  76410. if (!animation.channels || !animation.samplers) {
  76411. continue;
  76412. }
  76413. var lastAnimation = null;
  76414. for (var i = 0; i < animation.channels.length; i++) {
  76415. // Get parameters and load buffers
  76416. var channel = animation.channels[i];
  76417. var sampler = animation.samplers[channel.sampler];
  76418. if (!sampler) {
  76419. continue;
  76420. }
  76421. var inputData = null;
  76422. var outputData = null;
  76423. if (animation.parameters) {
  76424. inputData = animation.parameters[sampler.input];
  76425. outputData = animation.parameters[sampler.output];
  76426. }
  76427. else {
  76428. inputData = sampler.input;
  76429. outputData = sampler.output;
  76430. }
  76431. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  76432. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  76433. var targetID = channel.target.id;
  76434. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  76435. if (targetNode === null) {
  76436. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  76437. }
  76438. if (targetNode === null) {
  76439. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  76440. continue;
  76441. }
  76442. var isBone = targetNode instanceof BABYLON.Bone;
  76443. // Get target path (position, rotation or scaling)
  76444. var targetPath = channel.target.path;
  76445. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  76446. if (targetPathIndex !== -1) {
  76447. targetPath = babylonAnimationPaths[targetPathIndex];
  76448. }
  76449. // Determine animation type
  76450. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  76451. if (!isBone) {
  76452. if (targetPath === "rotationQuaternion") {
  76453. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  76454. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  76455. }
  76456. else {
  76457. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  76458. }
  76459. }
  76460. // Create animation and key frames
  76461. var babylonAnimation = null;
  76462. var keys = [];
  76463. var arrayOffset = 0;
  76464. var modifyKey = false;
  76465. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  76466. babylonAnimation = lastAnimation;
  76467. modifyKey = true;
  76468. }
  76469. if (!modifyKey) {
  76470. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  76471. }
  76472. // For each frame
  76473. for (var j = 0; j < bufferInput.length; j++) {
  76474. var value = null;
  76475. if (targetPath === "rotationQuaternion") {
  76476. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  76477. arrayOffset += 4;
  76478. }
  76479. else {
  76480. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  76481. arrayOffset += 3;
  76482. }
  76483. if (isBone) {
  76484. var bone = targetNode;
  76485. var translation = BABYLON.Vector3.Zero();
  76486. var rotationQuaternion = new BABYLON.Quaternion();
  76487. var scaling = BABYLON.Vector3.Zero();
  76488. // Warning on decompose
  76489. var mat = bone.getBaseMatrix();
  76490. if (modifyKey && lastAnimation) {
  76491. mat = lastAnimation.getKeys()[j].value;
  76492. }
  76493. mat.decompose(scaling, rotationQuaternion, translation);
  76494. if (targetPath === "position") {
  76495. translation = value;
  76496. }
  76497. else if (targetPath === "rotationQuaternion") {
  76498. rotationQuaternion = value;
  76499. }
  76500. else {
  76501. scaling = value;
  76502. }
  76503. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  76504. }
  76505. if (!modifyKey) {
  76506. keys.push({
  76507. frame: bufferInput[j],
  76508. value: value
  76509. });
  76510. }
  76511. else if (lastAnimation) {
  76512. lastAnimation.getKeys()[j].value = value;
  76513. }
  76514. }
  76515. // Finish
  76516. if (!modifyKey && babylonAnimation) {
  76517. babylonAnimation.setKeys(keys);
  76518. targetNode.animations.push(babylonAnimation);
  76519. }
  76520. lastAnimation = babylonAnimation;
  76521. gltfRuntime.scene.stopAnimation(targetNode);
  76522. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  76523. }
  76524. }
  76525. };
  76526. /**
  76527. * Returns the bones transformation matrix
  76528. */
  76529. var configureBoneTransformation = function (node) {
  76530. var mat = null;
  76531. if (node.translation || node.rotation || node.scale) {
  76532. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  76533. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  76534. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  76535. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  76536. }
  76537. else {
  76538. mat = BABYLON.Matrix.FromArray(node.matrix);
  76539. }
  76540. return mat;
  76541. };
  76542. /**
  76543. * Returns the parent bone
  76544. */
  76545. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  76546. // Try to find
  76547. for (var i = 0; i < newSkeleton.bones.length; i++) {
  76548. if (newSkeleton.bones[i].name === jointName) {
  76549. return newSkeleton.bones[i];
  76550. }
  76551. }
  76552. // Not found, search in gltf nodes
  76553. var nodes = gltfRuntime.nodes;
  76554. for (var nde in nodes) {
  76555. var node = nodes[nde];
  76556. if (!node.jointName) {
  76557. continue;
  76558. }
  76559. var children = node.children;
  76560. for (var i = 0; i < children.length; i++) {
  76561. var child = gltfRuntime.nodes[children[i]];
  76562. if (!child.jointName) {
  76563. continue;
  76564. }
  76565. if (child.jointName === jointName) {
  76566. var mat = configureBoneTransformation(node);
  76567. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  76568. bone.id = nde;
  76569. return bone;
  76570. }
  76571. }
  76572. }
  76573. return null;
  76574. };
  76575. /**
  76576. * Returns the appropriate root node
  76577. */
  76578. var getNodeToRoot = function (nodesToRoot, id) {
  76579. for (var i = 0; i < nodesToRoot.length; i++) {
  76580. var nodeToRoot = nodesToRoot[i];
  76581. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  76582. var child = nodeToRoot.node.children[j];
  76583. if (child === id) {
  76584. return nodeToRoot.bone;
  76585. }
  76586. }
  76587. }
  76588. return null;
  76589. };
  76590. /**
  76591. * Returns the node with the joint name
  76592. */
  76593. var getJointNode = function (gltfRuntime, jointName) {
  76594. var nodes = gltfRuntime.nodes;
  76595. var node = nodes[jointName];
  76596. if (node) {
  76597. return {
  76598. node: node,
  76599. id: jointName
  76600. };
  76601. }
  76602. for (var nde in nodes) {
  76603. node = nodes[nde];
  76604. if (node.jointName === jointName) {
  76605. return {
  76606. node: node,
  76607. id: nde
  76608. };
  76609. }
  76610. }
  76611. return null;
  76612. };
  76613. /**
  76614. * Checks if a nodes is in joints
  76615. */
  76616. var nodeIsInJoints = function (skins, id) {
  76617. for (var i = 0; i < skins.jointNames.length; i++) {
  76618. if (skins.jointNames[i] === id) {
  76619. return true;
  76620. }
  76621. }
  76622. return false;
  76623. };
  76624. /**
  76625. * Fills the nodes to root for bones and builds hierarchy
  76626. */
  76627. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  76628. // Creates nodes for root
  76629. for (var nde in gltfRuntime.nodes) {
  76630. var node = gltfRuntime.nodes[nde];
  76631. var id = nde;
  76632. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  76633. continue;
  76634. }
  76635. // Create node to root bone
  76636. var mat = configureBoneTransformation(node);
  76637. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  76638. bone.id = id;
  76639. nodesToRoot.push({ bone: bone, node: node, id: id });
  76640. }
  76641. // Parenting
  76642. for (var i = 0; i < nodesToRoot.length; i++) {
  76643. var nodeToRoot = nodesToRoot[i];
  76644. var children = nodeToRoot.node.children;
  76645. for (var j = 0; j < children.length; j++) {
  76646. var child = null;
  76647. for (var k = 0; k < nodesToRoot.length; k++) {
  76648. if (nodesToRoot[k].id === children[j]) {
  76649. child = nodesToRoot[k];
  76650. break;
  76651. }
  76652. }
  76653. if (child) {
  76654. child.bone._parent = nodeToRoot.bone;
  76655. nodeToRoot.bone.children.push(child.bone);
  76656. }
  76657. }
  76658. }
  76659. };
  76660. /**
  76661. * Imports a skeleton
  76662. */
  76663. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  76664. if (!newSkeleton) {
  76665. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  76666. }
  76667. if (!skins.babylonSkeleton) {
  76668. return newSkeleton;
  76669. }
  76670. // Find the root bones
  76671. var nodesToRoot = [];
  76672. var nodesToRootToAdd = [];
  76673. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  76674. newSkeleton.bones = [];
  76675. // Joints
  76676. for (var i = 0; i < skins.jointNames.length; i++) {
  76677. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76678. if (!jointNode) {
  76679. continue;
  76680. }
  76681. var node = jointNode.node;
  76682. if (!node) {
  76683. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  76684. continue;
  76685. }
  76686. var id = jointNode.id;
  76687. // Optimize, if the bone already exists...
  76688. var existingBone = gltfRuntime.scene.getBoneByID(id);
  76689. if (existingBone) {
  76690. newSkeleton.bones.push(existingBone);
  76691. continue;
  76692. }
  76693. // Search for parent bone
  76694. var foundBone = false;
  76695. var parentBone = null;
  76696. for (var j = 0; j < i; j++) {
  76697. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  76698. if (!jointNode_1) {
  76699. continue;
  76700. }
  76701. var joint = jointNode_1.node;
  76702. if (!joint) {
  76703. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  76704. continue;
  76705. }
  76706. var children = joint.children;
  76707. if (!children) {
  76708. continue;
  76709. }
  76710. foundBone = false;
  76711. for (var k = 0; k < children.length; k++) {
  76712. if (children[k] === id) {
  76713. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  76714. foundBone = true;
  76715. break;
  76716. }
  76717. }
  76718. if (foundBone) {
  76719. break;
  76720. }
  76721. }
  76722. // Create bone
  76723. var mat = configureBoneTransformation(node);
  76724. if (!parentBone && nodesToRoot.length > 0) {
  76725. parentBone = getNodeToRoot(nodesToRoot, id);
  76726. if (parentBone) {
  76727. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  76728. nodesToRootToAdd.push(parentBone);
  76729. }
  76730. }
  76731. }
  76732. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  76733. bone.id = id;
  76734. }
  76735. // Polish
  76736. var bones = newSkeleton.bones;
  76737. newSkeleton.bones = [];
  76738. for (var i = 0; i < skins.jointNames.length; i++) {
  76739. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76740. if (!jointNode) {
  76741. continue;
  76742. }
  76743. for (var j = 0; j < bones.length; j++) {
  76744. if (bones[j].id === jointNode.id) {
  76745. newSkeleton.bones.push(bones[j]);
  76746. break;
  76747. }
  76748. }
  76749. }
  76750. newSkeleton.prepare();
  76751. // Finish
  76752. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  76753. newSkeleton.bones.push(nodesToRootToAdd[i]);
  76754. }
  76755. return newSkeleton;
  76756. };
  76757. /**
  76758. * Imports a mesh and its geometries
  76759. */
  76760. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  76761. if (!newMesh) {
  76762. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  76763. newMesh.id = id;
  76764. }
  76765. if (!node.babylonNode) {
  76766. return newMesh;
  76767. }
  76768. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  76769. if (!newMesh.material) {
  76770. newMesh.material = multiMat;
  76771. }
  76772. var vertexData = new BABYLON.VertexData();
  76773. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  76774. var verticesStarts = new Array();
  76775. var verticesCounts = new Array();
  76776. var indexStarts = new Array();
  76777. var indexCounts = new Array();
  76778. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76779. var meshID = meshes[meshIndex];
  76780. var mesh = gltfRuntime.meshes[meshID];
  76781. if (!mesh) {
  76782. continue;
  76783. }
  76784. // Positions, normals and UVs
  76785. for (var i = 0; i < mesh.primitives.length; i++) {
  76786. // Temporary vertex data
  76787. var tempVertexData = new BABYLON.VertexData();
  76788. var primitive = mesh.primitives[i];
  76789. if (primitive.mode !== 4) {
  76790. // continue;
  76791. }
  76792. var attributes = primitive.attributes;
  76793. var accessor = null;
  76794. var buffer = null;
  76795. // Set positions, normal and uvs
  76796. for (var semantic in attributes) {
  76797. // Link accessor and buffer view
  76798. accessor = gltfRuntime.accessors[attributes[semantic]];
  76799. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76800. if (semantic === "NORMAL") {
  76801. tempVertexData.normals = new Float32Array(buffer.length);
  76802. tempVertexData.normals.set(buffer);
  76803. }
  76804. else if (semantic === "POSITION") {
  76805. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  76806. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  76807. for (var j = 0; j < buffer.length; j += 4) {
  76808. tempVertexData.positions[j] = buffer[j];
  76809. tempVertexData.positions[j + 1] = buffer[j + 1];
  76810. tempVertexData.positions[j + 2] = buffer[j + 2];
  76811. }
  76812. }
  76813. else {
  76814. tempVertexData.positions = new Float32Array(buffer.length);
  76815. tempVertexData.positions.set(buffer);
  76816. }
  76817. verticesCounts.push(tempVertexData.positions.length);
  76818. }
  76819. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  76820. var channel = Number(semantic.split("_")[1]);
  76821. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  76822. var uvs = new Float32Array(buffer.length);
  76823. uvs.set(buffer);
  76824. normalizeUVs(uvs);
  76825. tempVertexData.set(uvs, uvKind);
  76826. }
  76827. else if (semantic === "JOINT") {
  76828. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  76829. tempVertexData.matricesIndices.set(buffer);
  76830. }
  76831. else if (semantic === "WEIGHT") {
  76832. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  76833. tempVertexData.matricesWeights.set(buffer);
  76834. }
  76835. else if (semantic === "COLOR") {
  76836. tempVertexData.colors = new Float32Array(buffer.length);
  76837. tempVertexData.colors.set(buffer);
  76838. }
  76839. }
  76840. // Indices
  76841. accessor = gltfRuntime.accessors[primitive.indices];
  76842. if (accessor) {
  76843. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76844. tempVertexData.indices = new Int32Array(buffer.length);
  76845. tempVertexData.indices.set(buffer);
  76846. indexCounts.push(tempVertexData.indices.length);
  76847. }
  76848. else {
  76849. // Set indices on the fly
  76850. var indices = [];
  76851. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  76852. indices.push(j);
  76853. }
  76854. tempVertexData.indices = new Int32Array(indices);
  76855. indexCounts.push(tempVertexData.indices.length);
  76856. }
  76857. vertexData.merge(tempVertexData);
  76858. // Sub material
  76859. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  76860. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  76861. // Update vertices start and index start
  76862. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  76863. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  76864. }
  76865. }
  76866. // Apply geometry
  76867. geometry.setAllVerticesData(vertexData, false);
  76868. newMesh.computeWorldMatrix(true);
  76869. // Apply submeshes
  76870. newMesh.subMeshes = [];
  76871. var index = 0;
  76872. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76873. var meshID = meshes[meshIndex];
  76874. var mesh = gltfRuntime.meshes[meshID];
  76875. if (!mesh) {
  76876. continue;
  76877. }
  76878. for (var i = 0; i < mesh.primitives.length; i++) {
  76879. if (mesh.primitives[i].mode !== 4) {
  76880. //continue;
  76881. }
  76882. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  76883. index++;
  76884. }
  76885. }
  76886. // Finish
  76887. return newMesh;
  76888. };
  76889. /**
  76890. * Configure node transformation from position, rotation and scaling
  76891. */
  76892. var configureNode = function (newNode, position, rotation, scaling) {
  76893. if (newNode.position) {
  76894. newNode.position = position;
  76895. }
  76896. if (newNode.rotationQuaternion || newNode.rotation) {
  76897. newNode.rotationQuaternion = rotation;
  76898. }
  76899. if (newNode.scaling) {
  76900. newNode.scaling = scaling;
  76901. }
  76902. };
  76903. /**
  76904. * Configures node from transformation matrix
  76905. */
  76906. var configureNodeFromMatrix = function (newNode, node, parent) {
  76907. if (node.matrix) {
  76908. var position = new BABYLON.Vector3(0, 0, 0);
  76909. var rotation = new BABYLON.Quaternion();
  76910. var scaling = new BABYLON.Vector3(0, 0, 0);
  76911. var mat = BABYLON.Matrix.FromArray(node.matrix);
  76912. mat.decompose(scaling, rotation, position);
  76913. configureNode(newNode, position, rotation, scaling);
  76914. }
  76915. else if (node.translation && node.rotation && node.scale) {
  76916. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  76917. }
  76918. newNode.computeWorldMatrix(true);
  76919. };
  76920. /**
  76921. * Imports a node
  76922. */
  76923. var importNode = function (gltfRuntime, node, id, parent) {
  76924. var lastNode = null;
  76925. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  76926. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  76927. return null;
  76928. }
  76929. }
  76930. // Meshes
  76931. if (node.skin) {
  76932. if (node.meshes) {
  76933. var skin = gltfRuntime.skins[node.skin];
  76934. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  76935. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  76936. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  76937. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  76938. if (!skin.babylonSkeleton) {
  76939. skin.babylonSkeleton = newMesh.skeleton;
  76940. }
  76941. }
  76942. lastNode = newMesh;
  76943. }
  76944. }
  76945. else if (node.meshes) {
  76946. /**
  76947. * Improve meshes property
  76948. */
  76949. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  76950. lastNode = newMesh;
  76951. }
  76952. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  76953. var light = gltfRuntime.lights[node.light];
  76954. if (light) {
  76955. if (light.type === "ambient") {
  76956. var ambienLight = light[light.type];
  76957. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76958. hemiLight.name = node.name || "";
  76959. if (ambienLight.color) {
  76960. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  76961. }
  76962. lastNode = hemiLight;
  76963. }
  76964. else if (light.type === "directional") {
  76965. var directionalLight = light[light.type];
  76966. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76967. dirLight.name = node.name || "";
  76968. if (directionalLight.color) {
  76969. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  76970. }
  76971. lastNode = dirLight;
  76972. }
  76973. else if (light.type === "point") {
  76974. var pointLight = light[light.type];
  76975. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76976. ptLight.name = node.name || "";
  76977. if (pointLight.color) {
  76978. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  76979. }
  76980. lastNode = ptLight;
  76981. }
  76982. else if (light.type === "spot") {
  76983. var spotLight = light[light.type];
  76984. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  76985. spLight.name = node.name || "";
  76986. if (spotLight.color) {
  76987. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  76988. }
  76989. if (spotLight.fallOfAngle) {
  76990. spLight.angle = spotLight.fallOfAngle;
  76991. }
  76992. if (spotLight.fallOffExponent) {
  76993. spLight.exponent = spotLight.fallOffExponent;
  76994. }
  76995. lastNode = spLight;
  76996. }
  76997. }
  76998. }
  76999. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  77000. var camera = gltfRuntime.cameras[node.camera];
  77001. if (camera) {
  77002. if (camera.type === "orthographic") {
  77003. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77004. orthoCamera.name = node.name || "";
  77005. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  77006. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  77007. lastNode = orthoCamera;
  77008. }
  77009. else if (camera.type === "perspective") {
  77010. var perspectiveCamera = camera[camera.type];
  77011. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  77012. persCamera.name = node.name || "";
  77013. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  77014. if (!perspectiveCamera.aspectRatio) {
  77015. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  77016. }
  77017. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  77018. persCamera.maxZ = perspectiveCamera.zfar;
  77019. persCamera.minZ = perspectiveCamera.znear;
  77020. }
  77021. lastNode = persCamera;
  77022. }
  77023. }
  77024. }
  77025. // Empty node
  77026. if (!node.jointName) {
  77027. if (node.babylonNode) {
  77028. return node.babylonNode;
  77029. }
  77030. else if (lastNode === null) {
  77031. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  77032. node.babylonNode = dummy;
  77033. lastNode = dummy;
  77034. }
  77035. }
  77036. if (lastNode !== null) {
  77037. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  77038. configureNodeFromMatrix(lastNode, node, parent);
  77039. }
  77040. else {
  77041. var translation = node.translation || [0, 0, 0];
  77042. var rotation = node.rotation || [0, 0, 0, 1];
  77043. var scale = node.scale || [1, 1, 1];
  77044. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  77045. }
  77046. lastNode.updateCache(true);
  77047. node.babylonNode = lastNode;
  77048. }
  77049. return lastNode;
  77050. };
  77051. /**
  77052. * Traverses nodes and creates them
  77053. */
  77054. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  77055. if (meshIncluded === void 0) { meshIncluded = false; }
  77056. var node = gltfRuntime.nodes[id];
  77057. var newNode = null;
  77058. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  77059. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  77060. meshIncluded = true;
  77061. }
  77062. else {
  77063. meshIncluded = false;
  77064. }
  77065. }
  77066. else {
  77067. meshIncluded = true;
  77068. }
  77069. if (!node.jointName && meshIncluded) {
  77070. newNode = importNode(gltfRuntime, node, id, parent);
  77071. if (newNode !== null) {
  77072. newNode.id = id;
  77073. newNode.parent = parent;
  77074. }
  77075. }
  77076. if (node.children) {
  77077. for (var i = 0; i < node.children.length; i++) {
  77078. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  77079. }
  77080. }
  77081. };
  77082. /**
  77083. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  77084. */
  77085. var postLoad = function (gltfRuntime) {
  77086. // Nodes
  77087. var currentScene = gltfRuntime.currentScene;
  77088. if (currentScene) {
  77089. for (var i = 0; i < currentScene.nodes.length; i++) {
  77090. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77091. }
  77092. }
  77093. else {
  77094. for (var thing in gltfRuntime.scenes) {
  77095. currentScene = gltfRuntime.scenes[thing];
  77096. for (var i = 0; i < currentScene.nodes.length; i++) {
  77097. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77098. }
  77099. }
  77100. }
  77101. // Set animations
  77102. loadAnimations(gltfRuntime);
  77103. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  77104. var skeleton = gltfRuntime.scene.skeletons[i];
  77105. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  77106. }
  77107. };
  77108. /**
  77109. * onBind shaderrs callback to set uniforms and matrices
  77110. */
  77111. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  77112. var materialValues = material.values || technique.parameters;
  77113. for (var unif in unTreatedUniforms) {
  77114. var uniform = unTreatedUniforms[unif];
  77115. var type = uniform.type;
  77116. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  77117. if (uniform.semantic && !uniform.source && !uniform.node) {
  77118. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  77119. }
  77120. else if (uniform.semantic && (uniform.source || uniform.node)) {
  77121. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  77122. if (source === null) {
  77123. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  77124. }
  77125. if (source === null) {
  77126. continue;
  77127. }
  77128. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  77129. }
  77130. }
  77131. else {
  77132. var value = materialValues[technique.uniforms[unif]];
  77133. if (!value) {
  77134. continue;
  77135. }
  77136. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  77137. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  77138. if (texture === null || texture === undefined) {
  77139. continue;
  77140. }
  77141. shaderMaterial.getEffect().setTexture(unif, texture);
  77142. }
  77143. else {
  77144. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  77145. }
  77146. }
  77147. }
  77148. onSuccess(shaderMaterial);
  77149. };
  77150. /**
  77151. * Prepare uniforms to send the only one time
  77152. * Loads the appropriate textures
  77153. */
  77154. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  77155. var materialValues = material.values || technique.parameters;
  77156. var techniqueUniforms = technique.uniforms;
  77157. /**
  77158. * Prepare values here (not matrices)
  77159. */
  77160. for (var unif in unTreatedUniforms) {
  77161. var uniform = unTreatedUniforms[unif];
  77162. var type = uniform.type;
  77163. var value = materialValues[techniqueUniforms[unif]];
  77164. if (value === undefined) {
  77165. // In case the value is the same for all materials
  77166. value = uniform.value;
  77167. }
  77168. if (!value) {
  77169. continue;
  77170. }
  77171. var onLoadTexture = function (uniformName) {
  77172. return function (texture) {
  77173. if (uniform.value && uniformName) {
  77174. // Static uniform
  77175. shaderMaterial.setTexture(uniformName, texture);
  77176. delete unTreatedUniforms[uniformName];
  77177. }
  77178. };
  77179. };
  77180. // Texture (sampler2D)
  77181. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  77182. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  77183. }
  77184. else {
  77185. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  77186. // Static uniform
  77187. delete unTreatedUniforms[unif];
  77188. }
  77189. }
  77190. }
  77191. };
  77192. /**
  77193. * Shader compilation failed
  77194. */
  77195. var onShaderCompileError = function (program, shaderMaterial, onError) {
  77196. return function (effect, error) {
  77197. shaderMaterial.dispose(true);
  77198. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  77199. };
  77200. };
  77201. /**
  77202. * Shader compilation success
  77203. */
  77204. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  77205. return function (_) {
  77206. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  77207. shaderMaterial.onBind = function (mesh) {
  77208. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  77209. };
  77210. };
  77211. };
  77212. /**
  77213. * Returns the appropriate uniform if already handled by babylon
  77214. */
  77215. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  77216. for (var unif in technique.uniforms) {
  77217. var uniform = technique.uniforms[unif];
  77218. var uniformParameter = technique.parameters[uniform];
  77219. if (tokenizer.currentIdentifier === unif) {
  77220. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  77221. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  77222. if (transformIndex !== -1) {
  77223. delete unTreatedUniforms[unif];
  77224. return babylonTransforms[transformIndex];
  77225. }
  77226. }
  77227. }
  77228. }
  77229. return tokenizer.currentIdentifier;
  77230. };
  77231. /**
  77232. * All shaders loaded. Create materials one by one
  77233. */
  77234. var importMaterials = function (gltfRuntime) {
  77235. // Create materials
  77236. for (var mat in gltfRuntime.materials) {
  77237. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  77238. }
  77239. };
  77240. /**
  77241. * Implementation of the base glTF spec
  77242. */
  77243. var GLTFLoaderBase = /** @class */ (function () {
  77244. function GLTFLoaderBase() {
  77245. }
  77246. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  77247. var gltfRuntime = {
  77248. extensions: {},
  77249. accessors: {},
  77250. buffers: {},
  77251. bufferViews: {},
  77252. meshes: {},
  77253. lights: {},
  77254. cameras: {},
  77255. nodes: {},
  77256. images: {},
  77257. textures: {},
  77258. shaders: {},
  77259. programs: {},
  77260. samplers: {},
  77261. techniques: {},
  77262. materials: {},
  77263. animations: {},
  77264. skins: {},
  77265. extensionsUsed: [],
  77266. scenes: {},
  77267. buffersCount: 0,
  77268. shaderscount: 0,
  77269. scene: scene,
  77270. rootUrl: rootUrl,
  77271. loadedBufferCount: 0,
  77272. loadedBufferViews: {},
  77273. loadedShaderCount: 0,
  77274. importOnlyMeshes: false,
  77275. dummyNodes: []
  77276. };
  77277. // Parse
  77278. if (parsedData.extensions) {
  77279. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  77280. }
  77281. if (parsedData.extensionsUsed) {
  77282. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  77283. }
  77284. if (parsedData.buffers) {
  77285. parseBuffers(parsedData.buffers, gltfRuntime);
  77286. }
  77287. if (parsedData.bufferViews) {
  77288. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  77289. }
  77290. if (parsedData.accessors) {
  77291. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  77292. }
  77293. if (parsedData.meshes) {
  77294. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  77295. }
  77296. if (parsedData.lights) {
  77297. parseObject(parsedData.lights, "lights", gltfRuntime);
  77298. }
  77299. if (parsedData.cameras) {
  77300. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  77301. }
  77302. if (parsedData.nodes) {
  77303. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  77304. }
  77305. if (parsedData.images) {
  77306. parseObject(parsedData.images, "images", gltfRuntime);
  77307. }
  77308. if (parsedData.textures) {
  77309. parseObject(parsedData.textures, "textures", gltfRuntime);
  77310. }
  77311. if (parsedData.shaders) {
  77312. parseShaders(parsedData.shaders, gltfRuntime);
  77313. }
  77314. if (parsedData.programs) {
  77315. parseObject(parsedData.programs, "programs", gltfRuntime);
  77316. }
  77317. if (parsedData.samplers) {
  77318. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  77319. }
  77320. if (parsedData.techniques) {
  77321. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  77322. }
  77323. if (parsedData.materials) {
  77324. parseObject(parsedData.materials, "materials", gltfRuntime);
  77325. }
  77326. if (parsedData.animations) {
  77327. parseObject(parsedData.animations, "animations", gltfRuntime);
  77328. }
  77329. if (parsedData.skins) {
  77330. parseObject(parsedData.skins, "skins", gltfRuntime);
  77331. }
  77332. if (parsedData.scenes) {
  77333. gltfRuntime.scenes = parsedData.scenes;
  77334. }
  77335. if (parsedData.scene && parsedData.scenes) {
  77336. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  77337. }
  77338. return gltfRuntime;
  77339. };
  77340. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77341. var buffer = gltfRuntime.buffers[id];
  77342. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  77343. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  77344. }
  77345. else {
  77346. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  77347. if (request) {
  77348. onError(request.status + " " + request.statusText);
  77349. }
  77350. });
  77351. }
  77352. };
  77353. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77354. var texture = gltfRuntime.textures[id];
  77355. if (!texture || !texture.source) {
  77356. onError("");
  77357. return;
  77358. }
  77359. if (texture.babylonTexture) {
  77360. onSuccess(null);
  77361. return;
  77362. }
  77363. var source = gltfRuntime.images[texture.source];
  77364. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  77365. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  77366. }
  77367. else {
  77368. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  77369. if (request) {
  77370. onError(request.status + " " + request.statusText);
  77371. }
  77372. });
  77373. }
  77374. };
  77375. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77376. var texture = gltfRuntime.textures[id];
  77377. if (texture.babylonTexture) {
  77378. onSuccess(texture.babylonTexture);
  77379. return;
  77380. }
  77381. var sampler = gltfRuntime.samplers[texture.sampler];
  77382. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  77383. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  77384. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  77385. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  77386. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  77387. var blob = new Blob([buffer]);
  77388. var blobURL = URL.createObjectURL(blob);
  77389. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  77390. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  77391. if (sampler.wrapS !== undefined) {
  77392. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  77393. }
  77394. if (sampler.wrapT !== undefined) {
  77395. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  77396. }
  77397. newTexture.name = id;
  77398. texture.babylonTexture = newTexture;
  77399. onSuccess(newTexture);
  77400. };
  77401. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77402. var shader = gltfRuntime.shaders[id];
  77403. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  77404. var shaderString = atob(shader.uri.split(",")[1]);
  77405. onSuccess(shaderString);
  77406. }
  77407. else {
  77408. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  77409. if (request) {
  77410. onError(request.status + " " + request.statusText);
  77411. }
  77412. });
  77413. }
  77414. };
  77415. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77416. var material = gltfRuntime.materials[id];
  77417. if (!material.technique) {
  77418. if (onError) {
  77419. onError("No technique found.");
  77420. }
  77421. return;
  77422. }
  77423. var technique = gltfRuntime.techniques[material.technique];
  77424. if (!technique) {
  77425. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  77426. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  77427. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77428. onSuccess(defaultMaterial);
  77429. return;
  77430. }
  77431. var program = gltfRuntime.programs[technique.program];
  77432. var states = technique.states;
  77433. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  77434. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  77435. var newVertexShader = "";
  77436. var newPixelShader = "";
  77437. var vertexTokenizer = new Tokenizer(vertexShader);
  77438. var pixelTokenizer = new Tokenizer(pixelShader);
  77439. var unTreatedUniforms = {};
  77440. var uniforms = [];
  77441. var attributes = [];
  77442. var samplers = [];
  77443. // Fill uniform, sampler2D and attributes
  77444. for (var unif in technique.uniforms) {
  77445. var uniform = technique.uniforms[unif];
  77446. var uniformParameter = technique.parameters[uniform];
  77447. unTreatedUniforms[unif] = uniformParameter;
  77448. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  77449. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  77450. if (transformIndex !== -1) {
  77451. uniforms.push(babylonTransforms[transformIndex]);
  77452. delete unTreatedUniforms[unif];
  77453. }
  77454. else {
  77455. uniforms.push(unif);
  77456. }
  77457. }
  77458. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  77459. samplers.push(unif);
  77460. }
  77461. else {
  77462. uniforms.push(unif);
  77463. }
  77464. }
  77465. for (var attr in technique.attributes) {
  77466. var attribute = technique.attributes[attr];
  77467. var attributeParameter = technique.parameters[attribute];
  77468. if (attributeParameter.semantic) {
  77469. attributes.push(getAttribute(attributeParameter));
  77470. }
  77471. }
  77472. // Configure vertex shader
  77473. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  77474. var tokenType = vertexTokenizer.currentToken;
  77475. if (tokenType !== ETokenType.IDENTIFIER) {
  77476. newVertexShader += vertexTokenizer.currentString;
  77477. continue;
  77478. }
  77479. var foundAttribute = false;
  77480. for (var attr in technique.attributes) {
  77481. var attribute = technique.attributes[attr];
  77482. var attributeParameter = technique.parameters[attribute];
  77483. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  77484. newVertexShader += getAttribute(attributeParameter);
  77485. foundAttribute = true;
  77486. break;
  77487. }
  77488. }
  77489. if (foundAttribute) {
  77490. continue;
  77491. }
  77492. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  77493. }
  77494. // Configure pixel shader
  77495. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  77496. var tokenType = pixelTokenizer.currentToken;
  77497. if (tokenType !== ETokenType.IDENTIFIER) {
  77498. newPixelShader += pixelTokenizer.currentString;
  77499. continue;
  77500. }
  77501. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  77502. }
  77503. // Create shader material
  77504. var shaderPath = {
  77505. vertex: program.vertexShader + id,
  77506. fragment: program.fragmentShader + id
  77507. };
  77508. var options = {
  77509. attributes: attributes,
  77510. uniforms: uniforms,
  77511. samplers: samplers,
  77512. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  77513. };
  77514. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  77515. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  77516. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  77517. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  77518. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  77519. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77520. if (states && states.functions) {
  77521. var functions = states.functions;
  77522. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  77523. shaderMaterial.backFaceCulling = false;
  77524. }
  77525. var blendFunc = functions.blendFuncSeparate;
  77526. if (blendFunc) {
  77527. 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) {
  77528. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  77529. }
  77530. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77531. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  77532. }
  77533. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77534. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  77535. }
  77536. 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) {
  77537. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  77538. }
  77539. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  77540. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  77541. }
  77542. 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) {
  77543. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  77544. }
  77545. }
  77546. }
  77547. };
  77548. return GLTFLoaderBase;
  77549. }());
  77550. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  77551. /**
  77552. * glTF V1 Loader
  77553. */
  77554. var GLTFLoader = /** @class */ (function () {
  77555. function GLTFLoader() {
  77556. }
  77557. GLTFLoader.RegisterExtension = function (extension) {
  77558. if (GLTFLoader.Extensions[extension.name]) {
  77559. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  77560. return;
  77561. }
  77562. GLTFLoader.Extensions[extension.name] = extension;
  77563. };
  77564. GLTFLoader.prototype.dispose = function () {
  77565. // do nothing
  77566. };
  77567. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77568. var _this = this;
  77569. scene.useRightHandedSystem = true;
  77570. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77571. gltfRuntime.importOnlyMeshes = true;
  77572. if (meshesNames === "") {
  77573. gltfRuntime.importMeshesNames = [];
  77574. }
  77575. else if (typeof meshesNames === "string") {
  77576. gltfRuntime.importMeshesNames = [meshesNames];
  77577. }
  77578. else if (meshesNames && !(meshesNames instanceof Array)) {
  77579. gltfRuntime.importMeshesNames = [meshesNames];
  77580. }
  77581. else {
  77582. gltfRuntime.importMeshesNames = [];
  77583. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  77584. }
  77585. // Create nodes
  77586. _this._createNodes(gltfRuntime);
  77587. var meshes = new Array();
  77588. var skeletons = new Array();
  77589. // Fill arrays of meshes and skeletons
  77590. for (var nde in gltfRuntime.nodes) {
  77591. var node = gltfRuntime.nodes[nde];
  77592. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  77593. meshes.push(node.babylonNode);
  77594. }
  77595. }
  77596. for (var skl in gltfRuntime.skins) {
  77597. var skin = gltfRuntime.skins[skl];
  77598. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  77599. skeletons.push(skin.babylonSkeleton);
  77600. }
  77601. }
  77602. // Load buffers, shaders, materials, etc.
  77603. _this._loadBuffersAsync(gltfRuntime, function () {
  77604. _this._loadShadersAsync(gltfRuntime, function () {
  77605. importMaterials(gltfRuntime);
  77606. postLoad(gltfRuntime);
  77607. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77608. onSuccess(meshes, [], skeletons);
  77609. }
  77610. });
  77611. }, onProgress);
  77612. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77613. onSuccess(meshes, [], skeletons);
  77614. }
  77615. }, onError);
  77616. return true;
  77617. };
  77618. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77619. var _this = this;
  77620. scene.useRightHandedSystem = true;
  77621. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77622. // Load runtime extensios
  77623. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  77624. // Create nodes
  77625. _this._createNodes(gltfRuntime);
  77626. // Load buffers, shaders, materials, etc.
  77627. _this._loadBuffersAsync(gltfRuntime, function () {
  77628. _this._loadShadersAsync(gltfRuntime, function () {
  77629. importMaterials(gltfRuntime);
  77630. postLoad(gltfRuntime);
  77631. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  77632. onSuccess();
  77633. }
  77634. });
  77635. });
  77636. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  77637. onSuccess();
  77638. }
  77639. }, onError);
  77640. }, onError);
  77641. };
  77642. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  77643. var hasShaders = false;
  77644. var processShader = function (sha, shader) {
  77645. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  77646. gltfRuntime.loadedShaderCount++;
  77647. if (shaderString) {
  77648. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  77649. }
  77650. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  77651. onload();
  77652. }
  77653. }, function () {
  77654. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  77655. });
  77656. };
  77657. for (var sha in gltfRuntime.shaders) {
  77658. hasShaders = true;
  77659. var shader = gltfRuntime.shaders[sha];
  77660. if (shader) {
  77661. processShader.bind(this, sha, shader)();
  77662. }
  77663. else {
  77664. BABYLON.Tools.Error("No shader named: " + sha);
  77665. }
  77666. }
  77667. if (!hasShaders) {
  77668. onload();
  77669. }
  77670. };
  77671. ;
  77672. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  77673. var hasBuffers = false;
  77674. var processBuffer = function (buf, buffer) {
  77675. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  77676. gltfRuntime.loadedBufferCount++;
  77677. if (bufferView) {
  77678. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  77679. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  77680. }
  77681. gltfRuntime.loadedBufferViews[buf] = bufferView;
  77682. }
  77683. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  77684. onLoad();
  77685. }
  77686. }, function () {
  77687. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  77688. });
  77689. };
  77690. for (var buf in gltfRuntime.buffers) {
  77691. hasBuffers = true;
  77692. var buffer = gltfRuntime.buffers[buf];
  77693. if (buffer) {
  77694. processBuffer.bind(this, buf, buffer)();
  77695. }
  77696. else {
  77697. BABYLON.Tools.Error("No buffer named: " + buf);
  77698. }
  77699. }
  77700. if (!hasBuffers) {
  77701. onLoad();
  77702. }
  77703. };
  77704. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  77705. var currentScene = gltfRuntime.currentScene;
  77706. if (currentScene) {
  77707. // Only one scene even if multiple scenes are defined
  77708. for (var i = 0; i < currentScene.nodes.length; i++) {
  77709. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77710. }
  77711. }
  77712. else {
  77713. // Load all scenes
  77714. for (var thing in gltfRuntime.scenes) {
  77715. currentScene = gltfRuntime.scenes[thing];
  77716. for (var i = 0; i < currentScene.nodes.length; i++) {
  77717. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77718. }
  77719. }
  77720. }
  77721. };
  77722. GLTFLoader.Extensions = {};
  77723. return GLTFLoader;
  77724. }());
  77725. GLTF1.GLTFLoader = GLTFLoader;
  77726. ;
  77727. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  77728. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77729. })(BABYLON || (BABYLON = {}));
  77730. //# sourceMappingURL=babylon.glTFLoader.js.map
  77731. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77732. var BABYLON;
  77733. (function (BABYLON) {
  77734. var GLTF1;
  77735. (function (GLTF1) {
  77736. /**
  77737. * Utils functions for GLTF
  77738. */
  77739. var GLTFUtils = /** @class */ (function () {
  77740. function GLTFUtils() {
  77741. }
  77742. /**
  77743. * Sets the given "parameter" matrix
  77744. * @param scene: the {BABYLON.Scene} object
  77745. * @param source: the source node where to pick the matrix
  77746. * @param parameter: the GLTF technique parameter
  77747. * @param uniformName: the name of the shader's uniform
  77748. * @param shaderMaterial: the shader material
  77749. */
  77750. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  77751. var mat = null;
  77752. if (parameter.semantic === "MODEL") {
  77753. mat = source.getWorldMatrix();
  77754. }
  77755. else if (parameter.semantic === "PROJECTION") {
  77756. mat = scene.getProjectionMatrix();
  77757. }
  77758. else if (parameter.semantic === "VIEW") {
  77759. mat = scene.getViewMatrix();
  77760. }
  77761. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  77762. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  77763. }
  77764. else if (parameter.semantic === "MODELVIEW") {
  77765. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  77766. }
  77767. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  77768. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  77769. }
  77770. else if (parameter.semantic === "MODELINVERSE") {
  77771. mat = source.getWorldMatrix().invert();
  77772. }
  77773. else if (parameter.semantic === "VIEWINVERSE") {
  77774. mat = scene.getViewMatrix().invert();
  77775. }
  77776. else if (parameter.semantic === "PROJECTIONINVERSE") {
  77777. mat = scene.getProjectionMatrix().invert();
  77778. }
  77779. else if (parameter.semantic === "MODELVIEWINVERSE") {
  77780. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  77781. }
  77782. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  77783. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  77784. }
  77785. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  77786. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  77787. }
  77788. else {
  77789. debugger;
  77790. }
  77791. if (mat) {
  77792. switch (parameter.type) {
  77793. case GLTF1.EParameterType.FLOAT_MAT2:
  77794. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  77795. break;
  77796. case GLTF1.EParameterType.FLOAT_MAT3:
  77797. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  77798. break;
  77799. case GLTF1.EParameterType.FLOAT_MAT4:
  77800. shaderMaterial.setMatrix(uniformName, mat);
  77801. break;
  77802. default: break;
  77803. }
  77804. }
  77805. };
  77806. /**
  77807. * Sets the given "parameter" matrix
  77808. * @param shaderMaterial: the shader material
  77809. * @param uniform: the name of the shader's uniform
  77810. * @param value: the value of the uniform
  77811. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  77812. */
  77813. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  77814. switch (type) {
  77815. case GLTF1.EParameterType.FLOAT:
  77816. shaderMaterial.setFloat(uniform, value);
  77817. return true;
  77818. case GLTF1.EParameterType.FLOAT_VEC2:
  77819. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  77820. return true;
  77821. case GLTF1.EParameterType.FLOAT_VEC3:
  77822. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  77823. return true;
  77824. case GLTF1.EParameterType.FLOAT_VEC4:
  77825. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  77826. return true;
  77827. default: return false;
  77828. }
  77829. };
  77830. /**
  77831. * If the uri is a base64 string
  77832. * @param uri: the uri to test
  77833. */
  77834. GLTFUtils.IsBase64 = function (uri) {
  77835. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  77836. };
  77837. /**
  77838. * Decode the base64 uri
  77839. * @param uri: the uri to decode
  77840. */
  77841. GLTFUtils.DecodeBase64 = function (uri) {
  77842. var decodedString = atob(uri.split(",")[1]);
  77843. var bufferLength = decodedString.length;
  77844. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  77845. for (var i = 0; i < bufferLength; i++) {
  77846. bufferView[i] = decodedString.charCodeAt(i);
  77847. }
  77848. return bufferView.buffer;
  77849. };
  77850. /**
  77851. * Returns the wrap mode of the texture
  77852. * @param mode: the mode value
  77853. */
  77854. GLTFUtils.GetWrapMode = function (mode) {
  77855. switch (mode) {
  77856. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  77857. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  77858. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77859. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77860. }
  77861. };
  77862. /**
  77863. * Returns the byte stride giving an accessor
  77864. * @param accessor: the GLTF accessor objet
  77865. */
  77866. GLTFUtils.GetByteStrideFromType = function (accessor) {
  77867. // Needs this function since "byteStride" isn't requiered in glTF format
  77868. var type = accessor.type;
  77869. switch (type) {
  77870. case "VEC2": return 2;
  77871. case "VEC3": return 3;
  77872. case "VEC4": return 4;
  77873. case "MAT2": return 4;
  77874. case "MAT3": return 9;
  77875. case "MAT4": return 16;
  77876. default: return 1;
  77877. }
  77878. };
  77879. /**
  77880. * Returns the texture filter mode giving a mode value
  77881. * @param mode: the filter mode value
  77882. */
  77883. GLTFUtils.GetTextureFilterMode = function (mode) {
  77884. switch (mode) {
  77885. case GLTF1.ETextureFilterType.LINEAR:
  77886. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  77887. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  77888. case GLTF1.ETextureFilterType.NEAREST:
  77889. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  77890. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  77891. }
  77892. };
  77893. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  77894. var byteOffset = bufferView.byteOffset + byteOffset;
  77895. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  77896. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  77897. throw new Error("Buffer access is out of range");
  77898. }
  77899. var buffer = loadedBufferView.buffer;
  77900. byteOffset += loadedBufferView.byteOffset;
  77901. switch (componentType) {
  77902. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  77903. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  77904. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  77905. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  77906. default: return new Float32Array(buffer, byteOffset, byteLength);
  77907. }
  77908. };
  77909. /**
  77910. * Returns a buffer from its accessor
  77911. * @param gltfRuntime: the GLTF runtime
  77912. * @param accessor: the GLTF accessor
  77913. */
  77914. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  77915. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  77916. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  77917. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  77918. };
  77919. /**
  77920. * Decodes a buffer view into a string
  77921. * @param view: the buffer view
  77922. */
  77923. GLTFUtils.DecodeBufferToText = function (view) {
  77924. var result = "";
  77925. var length = view.byteLength;
  77926. for (var i = 0; i < length; ++i) {
  77927. result += String.fromCharCode(view[i]);
  77928. }
  77929. return result;
  77930. };
  77931. /**
  77932. * Returns the default material of gltf. Related to
  77933. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  77934. * @param scene: the Babylon.js scene
  77935. */
  77936. GLTFUtils.GetDefaultMaterial = function (scene) {
  77937. if (!GLTFUtils._DefaultMaterial) {
  77938. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  77939. "precision highp float;",
  77940. "",
  77941. "uniform mat4 worldView;",
  77942. "uniform mat4 projection;",
  77943. "",
  77944. "attribute vec3 position;",
  77945. "",
  77946. "void main(void)",
  77947. "{",
  77948. " gl_Position = projection * worldView * vec4(position, 1.0);",
  77949. "}"
  77950. ].join("\n");
  77951. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  77952. "precision highp float;",
  77953. "",
  77954. "uniform vec4 u_emission;",
  77955. "",
  77956. "void main(void)",
  77957. "{",
  77958. " gl_FragColor = u_emission;",
  77959. "}"
  77960. ].join("\n");
  77961. var shaderPath = {
  77962. vertex: "GLTFDefaultMaterial",
  77963. fragment: "GLTFDefaultMaterial"
  77964. };
  77965. var options = {
  77966. attributes: ["position"],
  77967. uniforms: ["worldView", "projection", "u_emission"],
  77968. samplers: new Array(),
  77969. needAlphaBlending: false
  77970. };
  77971. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  77972. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  77973. }
  77974. return GLTFUtils._DefaultMaterial;
  77975. };
  77976. // The GLTF default material
  77977. GLTFUtils._DefaultMaterial = null;
  77978. return GLTFUtils;
  77979. }());
  77980. GLTF1.GLTFUtils = GLTFUtils;
  77981. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77982. })(BABYLON || (BABYLON = {}));
  77983. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  77984. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77985. var BABYLON;
  77986. (function (BABYLON) {
  77987. var GLTF1;
  77988. (function (GLTF1) {
  77989. var GLTFLoaderExtension = /** @class */ (function () {
  77990. function GLTFLoaderExtension(name) {
  77991. this._name = name;
  77992. }
  77993. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  77994. get: function () {
  77995. return this._name;
  77996. },
  77997. enumerable: true,
  77998. configurable: true
  77999. });
  78000. /**
  78001. * Defines an override for loading the runtime
  78002. * Return true to stop further extensions from loading the runtime
  78003. */
  78004. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78005. return false;
  78006. };
  78007. /**
  78008. * Defines an onverride for creating gltf runtime
  78009. * Return true to stop further extensions from creating the runtime
  78010. */
  78011. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78012. return false;
  78013. };
  78014. /**
  78015. * Defines an override for loading buffers
  78016. * Return true to stop further extensions from loading this buffer
  78017. */
  78018. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  78019. return false;
  78020. };
  78021. /**
  78022. * Defines an override for loading texture buffers
  78023. * Return true to stop further extensions from loading this texture data
  78024. */
  78025. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78026. return false;
  78027. };
  78028. /**
  78029. * Defines an override for creating textures
  78030. * Return true to stop further extensions from loading this texture
  78031. */
  78032. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  78033. return false;
  78034. };
  78035. /**
  78036. * Defines an override for loading shader strings
  78037. * Return true to stop further extensions from loading this shader data
  78038. */
  78039. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78040. return false;
  78041. };
  78042. /**
  78043. * Defines an override for loading materials
  78044. * Return true to stop further extensions from loading this material
  78045. */
  78046. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78047. return false;
  78048. };
  78049. // ---------
  78050. // Utilities
  78051. // ---------
  78052. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78053. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78054. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  78055. }, function () {
  78056. setTimeout(function () {
  78057. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  78058. });
  78059. });
  78060. };
  78061. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78062. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78063. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  78064. }, function () {
  78065. setTimeout(function () {
  78066. onSuccess();
  78067. });
  78068. });
  78069. };
  78070. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  78071. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78072. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  78073. }, function () {
  78074. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  78075. });
  78076. };
  78077. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  78078. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  78079. };
  78080. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78081. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78082. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  78083. }, function () {
  78084. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  78085. });
  78086. };
  78087. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78088. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78089. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  78090. }, function () {
  78091. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  78092. });
  78093. };
  78094. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78095. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78096. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  78097. }, function () {
  78098. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  78099. });
  78100. };
  78101. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  78102. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  78103. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  78104. }, function () {
  78105. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  78106. });
  78107. };
  78108. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  78109. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  78110. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  78111. if (func(loaderExtension)) {
  78112. return;
  78113. }
  78114. }
  78115. defaultFunc();
  78116. };
  78117. return GLTFLoaderExtension;
  78118. }());
  78119. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  78120. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78121. })(BABYLON || (BABYLON = {}));
  78122. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  78123. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78124. var BABYLON;
  78125. (function (BABYLON) {
  78126. var GLTF1;
  78127. (function (GLTF1) {
  78128. var BinaryExtensionBufferName = "binary_glTF";
  78129. ;
  78130. ;
  78131. var GLTFBinaryExtension = /** @class */ (function (_super) {
  78132. __extends(GLTFBinaryExtension, _super);
  78133. function GLTFBinaryExtension() {
  78134. return _super.call(this, "KHR_binary_glTF") || this;
  78135. }
  78136. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  78137. var extensionsUsed = data.json.extensionsUsed;
  78138. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  78139. return false;
  78140. }
  78141. this._bin = data.bin;
  78142. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  78143. return true;
  78144. };
  78145. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78146. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  78147. return false;
  78148. }
  78149. if (id !== BinaryExtensionBufferName) {
  78150. return false;
  78151. }
  78152. onSuccess(this._bin);
  78153. return true;
  78154. };
  78155. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  78156. var texture = gltfRuntime.textures[id];
  78157. var source = gltfRuntime.images[texture.source];
  78158. if (!source.extensions || !(this.name in source.extensions)) {
  78159. return false;
  78160. }
  78161. var sourceExt = source.extensions[this.name];
  78162. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  78163. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  78164. onSuccess(buffer);
  78165. return true;
  78166. };
  78167. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  78168. var shader = gltfRuntime.shaders[id];
  78169. if (!shader.extensions || !(this.name in shader.extensions)) {
  78170. return false;
  78171. }
  78172. var binaryExtensionShader = shader.extensions[this.name];
  78173. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  78174. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  78175. setTimeout(function () {
  78176. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  78177. onSuccess(shaderString);
  78178. });
  78179. return true;
  78180. };
  78181. return GLTFBinaryExtension;
  78182. }(GLTF1.GLTFLoaderExtension));
  78183. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  78184. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  78185. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78186. })(BABYLON || (BABYLON = {}));
  78187. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  78188. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78189. var BABYLON;
  78190. (function (BABYLON) {
  78191. var GLTF1;
  78192. (function (GLTF1) {
  78193. ;
  78194. ;
  78195. ;
  78196. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  78197. __extends(GLTFMaterialsCommonExtension, _super);
  78198. function GLTFMaterialsCommonExtension() {
  78199. return _super.call(this, "KHR_materials_common") || this;
  78200. }
  78201. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  78202. if (!gltfRuntime.extensions)
  78203. return false;
  78204. var extension = gltfRuntime.extensions[this.name];
  78205. if (!extension)
  78206. return false;
  78207. // Create lights
  78208. var lights = extension.lights;
  78209. if (lights) {
  78210. for (var thing in lights) {
  78211. var light = lights[thing];
  78212. switch (light.type) {
  78213. case "ambient":
  78214. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  78215. var ambient = light.ambient;
  78216. if (ambient) {
  78217. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  78218. }
  78219. break;
  78220. case "point":
  78221. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  78222. var point = light.point;
  78223. if (point) {
  78224. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  78225. }
  78226. break;
  78227. case "directional":
  78228. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  78229. var directional = light.directional;
  78230. if (directional) {
  78231. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  78232. }
  78233. break;
  78234. case "spot":
  78235. var spot = light.spot;
  78236. if (spot) {
  78237. 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);
  78238. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  78239. }
  78240. break;
  78241. default:
  78242. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  78243. break;
  78244. }
  78245. }
  78246. }
  78247. return false;
  78248. };
  78249. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  78250. var material = gltfRuntime.materials[id];
  78251. if (!material || !material.extensions)
  78252. return false;
  78253. var extension = material.extensions[this.name];
  78254. if (!extension)
  78255. return false;
  78256. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  78257. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78258. if (extension.technique === "CONSTANT") {
  78259. standardMaterial.disableLighting = true;
  78260. }
  78261. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  78262. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  78263. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  78264. // Ambient
  78265. if (typeof extension.values.ambient === "string") {
  78266. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  78267. }
  78268. else {
  78269. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  78270. }
  78271. // Diffuse
  78272. if (typeof extension.values.diffuse === "string") {
  78273. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  78274. }
  78275. else {
  78276. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  78277. }
  78278. // Emission
  78279. if (typeof extension.values.emission === "string") {
  78280. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  78281. }
  78282. else {
  78283. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  78284. }
  78285. // Specular
  78286. if (typeof extension.values.specular === "string") {
  78287. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  78288. }
  78289. else {
  78290. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  78291. }
  78292. return true;
  78293. };
  78294. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  78295. // Create buffer from texture url
  78296. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  78297. // Create texture from buffer
  78298. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  78299. }, onError);
  78300. };
  78301. return GLTFMaterialsCommonExtension;
  78302. }(GLTF1.GLTFLoaderExtension));
  78303. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  78304. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  78305. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78306. })(BABYLON || (BABYLON = {}));
  78307. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  78308. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78309. var BABYLON;
  78310. (function (BABYLON) {
  78311. var GLTF2;
  78312. (function (GLTF2) {
  78313. /**
  78314. * Enums
  78315. */
  78316. var EComponentType;
  78317. (function (EComponentType) {
  78318. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  78319. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  78320. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  78321. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  78322. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  78323. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  78324. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  78325. var EMeshPrimitiveMode;
  78326. (function (EMeshPrimitiveMode) {
  78327. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  78328. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  78329. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  78330. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  78331. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  78332. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  78333. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  78334. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  78335. var ETextureMagFilter;
  78336. (function (ETextureMagFilter) {
  78337. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  78338. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  78339. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  78340. var ETextureMinFilter;
  78341. (function (ETextureMinFilter) {
  78342. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  78343. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  78344. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  78345. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  78346. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  78347. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  78348. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  78349. var ETextureWrapMode;
  78350. (function (ETextureWrapMode) {
  78351. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  78352. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  78353. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  78354. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  78355. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  78356. })(BABYLON || (BABYLON = {}));
  78357. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  78358. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78359. var BABYLON;
  78360. (function (BABYLON) {
  78361. var GLTF2;
  78362. (function (GLTF2) {
  78363. var GLTFLoaderTracker = /** @class */ (function () {
  78364. function GLTFLoaderTracker(onComplete) {
  78365. this._pendingCount = 0;
  78366. this._callback = onComplete;
  78367. }
  78368. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  78369. this._pendingCount++;
  78370. };
  78371. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  78372. if (--this._pendingCount === 0) {
  78373. this._callback();
  78374. }
  78375. };
  78376. return GLTFLoaderTracker;
  78377. }());
  78378. var GLTFLoader = /** @class */ (function () {
  78379. function GLTFLoader(parent) {
  78380. this._disposed = false;
  78381. this._renderReady = false;
  78382. this._requests = new Array();
  78383. this._renderReadyObservable = new BABYLON.Observable();
  78384. // Count of pending work that needs to complete before the asset is rendered.
  78385. this._renderPendingCount = 0;
  78386. // Count of pending work that needs to complete before the loader is disposed.
  78387. this._loaderPendingCount = 0;
  78388. this._loaderTrackers = new Array();
  78389. this._parent = parent;
  78390. }
  78391. GLTFLoader.RegisterExtension = function (extension) {
  78392. if (GLTFLoader.Extensions[extension.name]) {
  78393. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  78394. return;
  78395. }
  78396. GLTFLoader.Extensions[extension.name] = extension;
  78397. // Keep the order of registration so that extensions registered first are called first.
  78398. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  78399. };
  78400. GLTFLoader.prototype.dispose = function () {
  78401. if (this._disposed) {
  78402. return;
  78403. }
  78404. this._disposed = true;
  78405. // Abort requests that are not complete
  78406. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  78407. var request = _a[_i];
  78408. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  78409. request.abort();
  78410. }
  78411. }
  78412. // Revoke object urls created during load
  78413. if (this._gltf.textures) {
  78414. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  78415. var texture = _c[_b];
  78416. if (texture.url) {
  78417. URL.revokeObjectURL(texture.url);
  78418. }
  78419. }
  78420. }
  78421. };
  78422. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78423. var _this = this;
  78424. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  78425. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  78426. }, onProgress, onError);
  78427. };
  78428. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  78429. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  78430. };
  78431. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  78432. var _this = this;
  78433. this._tryCatchOnError(function () {
  78434. _this._loadData(data);
  78435. _this._babylonScene = scene;
  78436. _this._rootUrl = rootUrl;
  78437. _this._successCallback = onSuccess;
  78438. _this._progressCallback = onProgress;
  78439. _this._errorCallback = onError;
  78440. _this._addPendingData(_this);
  78441. _this._loadDefaultScene(nodeNames);
  78442. _this._loadAnimations();
  78443. _this._removePendingData(_this);
  78444. });
  78445. };
  78446. GLTFLoader.prototype._onProgress = function (event) {
  78447. if (this._progressCallback) {
  78448. this._progressCallback(event);
  78449. }
  78450. };
  78451. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  78452. if (this._renderReady) {
  78453. func();
  78454. }
  78455. else {
  78456. this._renderReadyObservable.add(func);
  78457. }
  78458. };
  78459. GLTFLoader.prototype._onRenderReady = function () {
  78460. this._rootNode.babylonMesh.setEnabled(true);
  78461. this._startAnimations();
  78462. this._successCallback();
  78463. this._renderReadyObservable.notifyObservers(this);
  78464. };
  78465. GLTFLoader.prototype._onComplete = function () {
  78466. if (this._parent.onComplete) {
  78467. this._parent.onComplete();
  78468. }
  78469. this.dispose();
  78470. };
  78471. GLTFLoader.prototype._loadData = function (data) {
  78472. this._gltf = data.json;
  78473. // Assign the index of each object for convinience.
  78474. GLTFLoader._AssignIndices(this._gltf.accessors);
  78475. GLTFLoader._AssignIndices(this._gltf.animations);
  78476. GLTFLoader._AssignIndices(this._gltf.buffers);
  78477. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  78478. GLTFLoader._AssignIndices(this._gltf.images);
  78479. GLTFLoader._AssignIndices(this._gltf.materials);
  78480. GLTFLoader._AssignIndices(this._gltf.meshes);
  78481. GLTFLoader._AssignIndices(this._gltf.nodes);
  78482. GLTFLoader._AssignIndices(this._gltf.scenes);
  78483. GLTFLoader._AssignIndices(this._gltf.skins);
  78484. GLTFLoader._AssignIndices(this._gltf.textures);
  78485. if (data.bin) {
  78486. var buffers = this._gltf.buffers;
  78487. if (buffers && buffers[0] && !buffers[0].uri) {
  78488. var binaryBuffer = buffers[0];
  78489. if (binaryBuffer.byteLength != data.bin.byteLength) {
  78490. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  78491. }
  78492. binaryBuffer.loadedData = data.bin;
  78493. }
  78494. else {
  78495. BABYLON.Tools.Warn("Unexpected BIN chunk");
  78496. }
  78497. }
  78498. };
  78499. GLTFLoader.prototype._getMeshes = function () {
  78500. var meshes = new Array();
  78501. // Root mesh is always first.
  78502. meshes.push(this._rootNode.babylonMesh);
  78503. var nodes = this._gltf.nodes;
  78504. if (nodes) {
  78505. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  78506. var node = nodes_1[_i];
  78507. if (node.babylonMesh) {
  78508. meshes.push(node.babylonMesh);
  78509. }
  78510. }
  78511. }
  78512. return meshes;
  78513. };
  78514. GLTFLoader.prototype._getSkeletons = function () {
  78515. var skeletons = new Array();
  78516. var skins = this._gltf.skins;
  78517. if (skins) {
  78518. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  78519. var skin = skins_1[_i];
  78520. if (skin.babylonSkeleton) {
  78521. skeletons.push(skin.babylonSkeleton);
  78522. }
  78523. }
  78524. }
  78525. return skeletons;
  78526. };
  78527. GLTFLoader.prototype._getAnimationTargets = function () {
  78528. var targets = new Array();
  78529. var animations = this._gltf.animations;
  78530. if (animations) {
  78531. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  78532. var animation = animations_1[_i];
  78533. targets.push.apply(targets, animation.targets);
  78534. }
  78535. }
  78536. return targets;
  78537. };
  78538. GLTFLoader.prototype._startAnimations = function () {
  78539. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  78540. var target = _a[_i];
  78541. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  78542. }
  78543. };
  78544. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  78545. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  78546. if (!scene) {
  78547. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  78548. }
  78549. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  78550. };
  78551. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  78552. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  78553. switch (this._parent.coordinateSystemMode) {
  78554. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  78555. if (!this._babylonScene.useRightHandedSystem) {
  78556. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  78557. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  78558. }
  78559. break;
  78560. }
  78561. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  78562. // do nothing
  78563. break;
  78564. }
  78565. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  78566. this._babylonScene.useRightHandedSystem = true;
  78567. break;
  78568. }
  78569. default: {
  78570. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  78571. return;
  78572. }
  78573. }
  78574. var nodeIndices = scene.nodes;
  78575. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  78576. node.parent = parentNode;
  78577. return true;
  78578. }, this._rootNode);
  78579. if (nodeNames) {
  78580. if (!(nodeNames instanceof Array)) {
  78581. nodeNames = [nodeNames];
  78582. }
  78583. var filteredNodeIndices_1 = new Array();
  78584. this._traverseNodes(context, nodeIndices, function (node) {
  78585. if (nodeNames.indexOf(node.name) !== -1) {
  78586. filteredNodeIndices_1.push(node.index);
  78587. return false;
  78588. }
  78589. return true;
  78590. }, this._rootNode);
  78591. nodeIndices = filteredNodeIndices_1;
  78592. }
  78593. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  78594. var index = nodeIndices_1[_i];
  78595. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  78596. if (!node) {
  78597. throw new Error(context + ": Failed to find node " + index);
  78598. }
  78599. this._loadNode("#/nodes/" + index, node);
  78600. }
  78601. // Disable the root mesh until the asset is ready to render.
  78602. this._rootNode.babylonMesh.setEnabled(false);
  78603. };
  78604. GLTFLoader.prototype._loadNode = function (context, node) {
  78605. node.babylonBones = {};
  78606. node.babylonAnimationTargets = [];
  78607. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  78608. return;
  78609. }
  78610. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  78611. this._loadTransform(node);
  78612. if (node.mesh != null) {
  78613. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  78614. if (!mesh) {
  78615. throw new Error(context + ": Failed to find mesh " + node.mesh);
  78616. }
  78617. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  78618. }
  78619. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  78620. node.babylonAnimationTargets.push(node.babylonMesh);
  78621. if (node.skin != null) {
  78622. var skin = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  78623. if (!skin) {
  78624. throw new Error(context + ": Failed to find skin " + node.skin);
  78625. }
  78626. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  78627. }
  78628. if (node.camera != null) {
  78629. // TODO: handle cameras
  78630. }
  78631. if (node.children) {
  78632. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  78633. var index = _a[_i];
  78634. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  78635. if (!childNode) {
  78636. throw new Error(context + ": Failed to find child node " + index);
  78637. }
  78638. this._loadNode("#/nodes/" + index, childNode);
  78639. }
  78640. }
  78641. };
  78642. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  78643. var _this = this;
  78644. var primitives = mesh.primitives;
  78645. if (!primitives || primitives.length === 0) {
  78646. throw new Error(context + ": Primitives are missing");
  78647. }
  78648. this._createMorphTargets(context, node, mesh);
  78649. this._loadAllVertexDataAsync(context, mesh, function () {
  78650. _this._loadMorphTargets(context, node, mesh);
  78651. var vertexData = new BABYLON.VertexData();
  78652. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  78653. var primitive = primitives_1[_i];
  78654. vertexData.merge(primitive.vertexData);
  78655. }
  78656. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  78657. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  78658. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  78659. node.babylonMesh.subMeshes = [];
  78660. var verticesStart = 0;
  78661. var indicesStart = 0;
  78662. for (var index = 0; index < primitives.length; index++) {
  78663. var vertexData_1 = primitives[index].vertexData;
  78664. var verticesCount = vertexData_1.positions.length;
  78665. var indicesCount = vertexData_1.indices.length;
  78666. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  78667. verticesStart += verticesCount;
  78668. indicesStart += indicesCount;
  78669. }
  78670. ;
  78671. });
  78672. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  78673. node.babylonMesh.material = multiMaterial;
  78674. var subMaterials = multiMaterial.subMaterials;
  78675. var _loop_1 = function (index) {
  78676. var primitive = primitives[index];
  78677. if (primitive.material == null) {
  78678. subMaterials[index] = this_1._getDefaultMaterial();
  78679. }
  78680. else {
  78681. var material_1 = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  78682. if (!material_1) {
  78683. throw new Error(context + ": Failed to find material " + primitive.material);
  78684. }
  78685. this_1._loadMaterial("#/materials/" + material_1.index, material_1, function (babylonMaterial, isNew) {
  78686. if (isNew && _this._parent.onMaterialLoaded) {
  78687. _this._parent.onMaterialLoaded(babylonMaterial);
  78688. }
  78689. if (_this._parent.onBeforeMaterialReadyAsync) {
  78690. _this._addLoaderPendingData(material_1);
  78691. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  78692. _this._tryCatchOnError(function () {
  78693. subMaterials[index] = babylonMaterial;
  78694. _this._removeLoaderPendingData(material_1);
  78695. });
  78696. });
  78697. }
  78698. else {
  78699. subMaterials[index] = babylonMaterial;
  78700. }
  78701. });
  78702. }
  78703. };
  78704. var this_1 = this;
  78705. for (var index = 0; index < primitives.length; index++) {
  78706. _loop_1(index);
  78707. }
  78708. ;
  78709. };
  78710. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  78711. var primitives = mesh.primitives;
  78712. var numRemainingPrimitives = primitives.length;
  78713. var _loop_2 = function (index) {
  78714. var primitive = primitives[index];
  78715. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  78716. primitive.vertexData = vertexData;
  78717. if (--numRemainingPrimitives === 0) {
  78718. onSuccess();
  78719. }
  78720. });
  78721. };
  78722. var this_2 = this;
  78723. for (var index = 0; index < primitives.length; index++) {
  78724. _loop_2(index);
  78725. }
  78726. };
  78727. /**
  78728. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  78729. * @param {ArrayBufferView} data
  78730. * @param {IGLTFAccessor} accessor
  78731. */
  78732. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  78733. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  78734. return data;
  78735. }
  78736. var buffer = data;
  78737. var factor = 1;
  78738. switch (accessor.componentType) {
  78739. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78740. factor = 1 / 255;
  78741. break;
  78742. }
  78743. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78744. factor = 1 / 65535;
  78745. break;
  78746. }
  78747. default: {
  78748. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78749. }
  78750. }
  78751. var result = new Float32Array(accessor.count * 2);
  78752. for (var i = 0; i < result.length; ++i) {
  78753. result[i] = buffer[i] * factor;
  78754. }
  78755. return result;
  78756. };
  78757. /**
  78758. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  78759. * @param {ArrayBufferView} data
  78760. * @param {IGLTFAccessor} accessor
  78761. */
  78762. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  78763. var colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  78764. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  78765. return data;
  78766. }
  78767. var buffer = data;
  78768. var factor = 1;
  78769. switch (accessor.componentType) {
  78770. case GLTF2.EComponentType.FLOAT: {
  78771. factor = 1;
  78772. break;
  78773. }
  78774. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  78775. factor = 1 / 255;
  78776. break;
  78777. }
  78778. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  78779. factor = 1 / 65535;
  78780. break;
  78781. }
  78782. default: {
  78783. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78784. }
  78785. }
  78786. var result = new Float32Array(accessor.count * 4);
  78787. if (colorComponentCount === 4) {
  78788. for (var i = 0; i < result.length; ++i) {
  78789. result[i] = buffer[i] * factor;
  78790. }
  78791. }
  78792. else {
  78793. var offset = 0;
  78794. for (var i = 0; i < result.length; ++i) {
  78795. if ((i + 1) % 4 === 0) {
  78796. result[i] = 1;
  78797. }
  78798. else {
  78799. result[i] = buffer[offset++] * factor;
  78800. }
  78801. }
  78802. }
  78803. return result;
  78804. };
  78805. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  78806. var _this = this;
  78807. var attributes = primitive.attributes;
  78808. if (!attributes) {
  78809. throw new Error(context + ": Attributes are missing");
  78810. }
  78811. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  78812. // TODO: handle other primitive modes
  78813. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  78814. }
  78815. var vertexData = new BABYLON.VertexData();
  78816. var numRemainingAttributes = Object.keys(attributes).length;
  78817. var _loop_3 = function (attribute) {
  78818. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  78819. if (!accessor) {
  78820. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78821. }
  78822. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78823. switch (attribute) {
  78824. case "POSITION": {
  78825. vertexData.positions = data;
  78826. break;
  78827. }
  78828. case "NORMAL": {
  78829. vertexData.normals = data;
  78830. break;
  78831. }
  78832. case "TANGENT": {
  78833. vertexData.tangents = data;
  78834. break;
  78835. }
  78836. case "TEXCOORD_0": {
  78837. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  78838. break;
  78839. }
  78840. case "TEXCOORD_1": {
  78841. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  78842. break;
  78843. }
  78844. case "JOINTS_0": {
  78845. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  78846. break;
  78847. }
  78848. case "WEIGHTS_0": {
  78849. //TODO: need to add support for normalized weights.
  78850. vertexData.matricesWeights = data;
  78851. break;
  78852. }
  78853. case "COLOR_0": {
  78854. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  78855. break;
  78856. }
  78857. default: {
  78858. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78859. break;
  78860. }
  78861. }
  78862. if (--numRemainingAttributes === 0) {
  78863. if (primitive.indices == null) {
  78864. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  78865. for (var i = 0; i < vertexData.indices.length; i++) {
  78866. vertexData.indices[i] = i;
  78867. }
  78868. onSuccess(vertexData);
  78869. }
  78870. else {
  78871. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  78872. if (!indicesAccessor) {
  78873. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  78874. }
  78875. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  78876. vertexData.indices = data;
  78877. onSuccess(vertexData);
  78878. });
  78879. }
  78880. }
  78881. });
  78882. };
  78883. var this_3 = this;
  78884. for (var attribute in attributes) {
  78885. _loop_3(attribute);
  78886. }
  78887. };
  78888. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  78889. var primitives = mesh.primitives;
  78890. var targets = primitives[0].targets;
  78891. if (!targets) {
  78892. return;
  78893. }
  78894. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  78895. var primitive = primitives_2[_i];
  78896. if (!primitive.targets || primitive.targets.length != targets.length) {
  78897. throw new Error(context + ": All primitives are required to list the same number of targets");
  78898. }
  78899. }
  78900. var morphTargetManager = new BABYLON.MorphTargetManager();
  78901. node.babylonMesh.morphTargetManager = morphTargetManager;
  78902. for (var index = 0; index < targets.length; index++) {
  78903. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  78904. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  78905. }
  78906. };
  78907. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  78908. var morphTargetManager = node.babylonMesh.morphTargetManager;
  78909. if (!morphTargetManager) {
  78910. return;
  78911. }
  78912. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  78913. var numTargets = morphTargetManager.numTargets;
  78914. for (var index = 0; index < numTargets; index++) {
  78915. var vertexData = new BABYLON.VertexData();
  78916. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78917. var primitive = _a[_i];
  78918. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  78919. }
  78920. if (!vertexData.positions) {
  78921. throw new Error(context + ": Positions are missing");
  78922. }
  78923. var target = morphTargetManager.getTarget(index);
  78924. target.setPositions(vertexData.positions);
  78925. target.setNormals(vertexData.normals);
  78926. target.setTangents(vertexData.tangents);
  78927. }
  78928. });
  78929. };
  78930. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  78931. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  78932. var _loop_4 = function (primitive) {
  78933. var targets = primitive.targets;
  78934. primitive.targetsVertexData = new Array(targets.length);
  78935. var _loop_5 = function (index) {
  78936. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  78937. primitive.targetsVertexData[index] = vertexData;
  78938. if (--numRemainingTargets === 0) {
  78939. onSuccess();
  78940. }
  78941. });
  78942. };
  78943. for (var index = 0; index < targets.length; index++) {
  78944. _loop_5(index);
  78945. }
  78946. };
  78947. var this_4 = this;
  78948. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78949. var primitive = _a[_i];
  78950. _loop_4(primitive);
  78951. }
  78952. };
  78953. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  78954. var targetVertexData = new BABYLON.VertexData();
  78955. var numRemainingAttributes = Object.keys(attributes).length;
  78956. var _loop_6 = function (attribute) {
  78957. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  78958. if (!accessor) {
  78959. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78960. }
  78961. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78962. // glTF stores morph target information as deltas while babylon.js expects the final data.
  78963. // As a result we have to add the original data to the delta to calculate the final data.
  78964. var values = data;
  78965. switch (attribute) {
  78966. case "POSITION": {
  78967. for (var i = 0; i < values.length; i++) {
  78968. values[i] += vertexData.positions[i];
  78969. }
  78970. targetVertexData.positions = values;
  78971. break;
  78972. }
  78973. case "NORMAL": {
  78974. for (var i = 0; i < values.length; i++) {
  78975. values[i] += vertexData.normals[i];
  78976. }
  78977. targetVertexData.normals = values;
  78978. break;
  78979. }
  78980. case "TANGENT": {
  78981. // Tangent data for morph targets is stored as xyz delta.
  78982. // The vertexData.tangent is stored as xyzw.
  78983. // So we need to skip every fourth vertexData.tangent.
  78984. for (var i = 0, j = 0; i < values.length; i++, j++) {
  78985. values[i] += vertexData.tangents[j];
  78986. if ((i + 1) % 3 == 0) {
  78987. j++;
  78988. }
  78989. }
  78990. targetVertexData.tangents = values;
  78991. break;
  78992. }
  78993. default: {
  78994. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78995. break;
  78996. }
  78997. }
  78998. if (--numRemainingAttributes === 0) {
  78999. onSuccess(targetVertexData);
  79000. }
  79001. });
  79002. };
  79003. var this_5 = this;
  79004. for (var attribute in attributes) {
  79005. _loop_6(attribute);
  79006. }
  79007. };
  79008. GLTFLoader.prototype._loadTransform = function (node) {
  79009. var position = BABYLON.Vector3.Zero();
  79010. var rotation = BABYLON.Quaternion.Identity();
  79011. var scaling = BABYLON.Vector3.One();
  79012. if (node.matrix) {
  79013. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  79014. matrix.decompose(scaling, rotation, position);
  79015. }
  79016. else {
  79017. if (node.translation)
  79018. position = BABYLON.Vector3.FromArray(node.translation);
  79019. if (node.rotation)
  79020. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  79021. if (node.scale)
  79022. scaling = BABYLON.Vector3.FromArray(node.scale);
  79023. }
  79024. node.babylonMesh.position = position;
  79025. node.babylonMesh.rotationQuaternion = rotation;
  79026. node.babylonMesh.scaling = scaling;
  79027. };
  79028. GLTFLoader.prototype._loadSkin = function (context, skin) {
  79029. var _this = this;
  79030. var skeletonId = "skeleton" + skin.index;
  79031. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  79032. if (skin.inverseBindMatrices == null) {
  79033. this._loadBones(context, skin, null);
  79034. }
  79035. else {
  79036. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  79037. if (!accessor) {
  79038. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  79039. }
  79040. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  79041. _this._loadBones(context, skin, data);
  79042. });
  79043. }
  79044. return skin.babylonSkeleton;
  79045. };
  79046. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  79047. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  79048. node.babylonBones[skin.index] = babylonBone;
  79049. node.babylonAnimationTargets.push(babylonBone);
  79050. return babylonBone;
  79051. };
  79052. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  79053. var babylonBones = {};
  79054. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  79055. var index = _a[_i];
  79056. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  79057. if (!node) {
  79058. throw new Error(context + ": Failed to find joint " + index);
  79059. }
  79060. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  79061. }
  79062. };
  79063. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  79064. var babylonBone = babylonBones[node.index];
  79065. if (babylonBone) {
  79066. return babylonBone;
  79067. }
  79068. var boneIndex = skin.joints.indexOf(node.index);
  79069. var baseMatrix = BABYLON.Matrix.Identity();
  79070. if (inverseBindMatrixData && boneIndex !== -1) {
  79071. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  79072. baseMatrix.invertToRef(baseMatrix);
  79073. }
  79074. var babylonParentBone = null;
  79075. if (node.index !== skin.skeleton && node.parent && node.parent !== this._rootNode) {
  79076. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  79077. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  79078. }
  79079. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  79080. babylonBones[node.index] = babylonBone;
  79081. return babylonBone;
  79082. };
  79083. GLTFLoader.prototype._getNodeMatrix = function (node) {
  79084. return node.matrix ?
  79085. BABYLON.Matrix.FromArray(node.matrix) :
  79086. 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());
  79087. };
  79088. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  79089. if (parentNode === void 0) { parentNode = null; }
  79090. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  79091. var index = indices_1[_i];
  79092. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  79093. if (!node) {
  79094. throw new Error(context + ": Failed to find node " + index);
  79095. }
  79096. this._traverseNode(context, node, action, parentNode);
  79097. }
  79098. };
  79099. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  79100. if (parentNode === void 0) { parentNode = null; }
  79101. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  79102. return;
  79103. }
  79104. if (!action(node, parentNode)) {
  79105. return;
  79106. }
  79107. if (node.children) {
  79108. this._traverseNodes(context, node.children, action, node);
  79109. }
  79110. };
  79111. GLTFLoader.prototype._loadAnimations = function () {
  79112. var animations = this._gltf.animations;
  79113. if (!animations) {
  79114. return;
  79115. }
  79116. for (var index = 0; index < animations.length; index++) {
  79117. var animation = animations[index];
  79118. this._loadAnimation("#/animations/" + index, animation);
  79119. }
  79120. };
  79121. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  79122. animation.targets = [];
  79123. for (var index = 0; index < animation.channels.length; index++) {
  79124. var channel = GLTFLoader._GetProperty(animation.channels, index);
  79125. if (!channel) {
  79126. throw new Error(context + ": Failed to find channel " + index);
  79127. }
  79128. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  79129. if (!sampler) {
  79130. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  79131. }
  79132. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  79133. }
  79134. };
  79135. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  79136. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  79137. if (!targetNode) {
  79138. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  79139. }
  79140. var targetPath;
  79141. var animationType;
  79142. switch (channel.target.path) {
  79143. case "translation": {
  79144. targetPath = "position";
  79145. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  79146. break;
  79147. }
  79148. case "rotation": {
  79149. targetPath = "rotationQuaternion";
  79150. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  79151. break;
  79152. }
  79153. case "scale": {
  79154. targetPath = "scaling";
  79155. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  79156. break;
  79157. }
  79158. case "weights": {
  79159. targetPath = "influence";
  79160. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  79161. break;
  79162. }
  79163. default: {
  79164. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  79165. }
  79166. }
  79167. var inputData;
  79168. var outputData;
  79169. var checkSuccess = function () {
  79170. if (!inputData || !outputData) {
  79171. return;
  79172. }
  79173. var outputBufferOffset = 0;
  79174. var getNextOutputValue;
  79175. switch (targetPath) {
  79176. case "position": {
  79177. getNextOutputValue = function () {
  79178. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  79179. outputBufferOffset += 3;
  79180. return value;
  79181. };
  79182. break;
  79183. }
  79184. case "rotationQuaternion": {
  79185. getNextOutputValue = function () {
  79186. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  79187. outputBufferOffset += 4;
  79188. return value;
  79189. };
  79190. break;
  79191. }
  79192. case "scaling": {
  79193. getNextOutputValue = function () {
  79194. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  79195. outputBufferOffset += 3;
  79196. return value;
  79197. };
  79198. break;
  79199. }
  79200. case "influence": {
  79201. getNextOutputValue = function () {
  79202. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  79203. var value = new Array(numTargets);
  79204. for (var i = 0; i < numTargets; i++) {
  79205. value[i] = outputData[outputBufferOffset++];
  79206. }
  79207. return value;
  79208. };
  79209. break;
  79210. }
  79211. }
  79212. var getNextKey;
  79213. switch (sampler.interpolation) {
  79214. case "LINEAR": {
  79215. getNextKey = function (frameIndex) { return ({
  79216. frame: inputData[frameIndex],
  79217. value: getNextOutputValue()
  79218. }); };
  79219. break;
  79220. }
  79221. case "CUBICSPLINE": {
  79222. getNextKey = function (frameIndex) { return ({
  79223. frame: inputData[frameIndex],
  79224. inTangent: getNextOutputValue(),
  79225. value: getNextOutputValue(),
  79226. outTangent: getNextOutputValue()
  79227. }); };
  79228. break;
  79229. }
  79230. default: {
  79231. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  79232. }
  79233. }
  79234. ;
  79235. var keys = new Array(inputData.length);
  79236. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  79237. keys[frameIndex] = getNextKey(frameIndex);
  79238. }
  79239. if (targetPath === "influence") {
  79240. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  79241. var _loop_7 = function (targetIndex) {
  79242. var morphTarget = morphTargetManager.getTarget(targetIndex);
  79243. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  79244. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  79245. babylonAnimation.setKeys(keys.map(function (key) { return ({
  79246. frame: key.frame,
  79247. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  79248. value: key.value[targetIndex],
  79249. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  79250. }); }));
  79251. morphTarget.animations.push(babylonAnimation);
  79252. animation.targets.push(morphTarget);
  79253. };
  79254. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  79255. _loop_7(targetIndex);
  79256. }
  79257. }
  79258. else {
  79259. var animationName = animation.name || "anim" + animation.index;
  79260. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  79261. babylonAnimation.setKeys(keys);
  79262. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  79263. var target = _a[_i];
  79264. target.animations.push(babylonAnimation.clone());
  79265. animation.targets.push(target);
  79266. }
  79267. }
  79268. };
  79269. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  79270. if (!inputAccessor) {
  79271. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  79272. }
  79273. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  79274. inputData = data;
  79275. checkSuccess();
  79276. });
  79277. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  79278. if (!outputAccessor) {
  79279. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  79280. }
  79281. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  79282. outputData = data;
  79283. checkSuccess();
  79284. });
  79285. };
  79286. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  79287. var _this = this;
  79288. this._addPendingData(buffer);
  79289. if (buffer.loadedData) {
  79290. onSuccess(buffer.loadedData);
  79291. this._removePendingData(buffer);
  79292. }
  79293. else if (buffer.loadedObservable) {
  79294. buffer.loadedObservable.add(function (buffer) {
  79295. onSuccess(buffer.loadedData);
  79296. _this._removePendingData(buffer);
  79297. });
  79298. }
  79299. else {
  79300. if (!buffer.uri) {
  79301. throw new Error(context + ": Uri is missing");
  79302. }
  79303. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  79304. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  79305. buffer.loadedData = new Uint8Array(data);
  79306. onSuccess(buffer.loadedData);
  79307. this._removePendingData(buffer);
  79308. }
  79309. else {
  79310. buffer.loadedObservable = new BABYLON.Observable();
  79311. buffer.loadedObservable.add(function (buffer) {
  79312. onSuccess(buffer.loadedData);
  79313. _this._removePendingData(buffer);
  79314. });
  79315. this._loadUri(context, buffer.uri, function (data) {
  79316. buffer.loadedData = data;
  79317. buffer.loadedObservable.notifyObservers(buffer);
  79318. buffer.loadedObservable = undefined;
  79319. });
  79320. }
  79321. }
  79322. };
  79323. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  79324. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  79325. if (!buffer) {
  79326. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  79327. }
  79328. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  79329. var data;
  79330. try {
  79331. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  79332. }
  79333. catch (e) {
  79334. throw new Error(context + ": " + e.message);
  79335. }
  79336. onSuccess(data);
  79337. });
  79338. };
  79339. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  79340. var _this = this;
  79341. if (accessor.sparse) {
  79342. throw new Error(context + ": Sparse accessors are not currently supported");
  79343. }
  79344. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  79345. if (!bufferView) {
  79346. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  79347. }
  79348. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  79349. var numComponents = GLTFLoader._GetNumComponents(accessor.type);
  79350. if (numComponents === 0) {
  79351. throw new Error(context + ": Invalid type " + accessor.type);
  79352. }
  79353. var data;
  79354. var byteOffset = accessor.byteOffset || 0;
  79355. var byteStride = bufferView.byteStride;
  79356. try {
  79357. switch (accessor.componentType) {
  79358. case GLTF2.EComponentType.BYTE: {
  79359. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79360. break;
  79361. }
  79362. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  79363. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79364. break;
  79365. }
  79366. case GLTF2.EComponentType.SHORT: {
  79367. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79368. break;
  79369. }
  79370. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  79371. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79372. break;
  79373. }
  79374. case GLTF2.EComponentType.UNSIGNED_INT: {
  79375. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79376. break;
  79377. }
  79378. case GLTF2.EComponentType.FLOAT: {
  79379. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  79380. break;
  79381. }
  79382. default: {
  79383. throw new Error(context + ": Invalid component type " + accessor.componentType);
  79384. }
  79385. }
  79386. }
  79387. catch (e) {
  79388. throw new Error(context + ": " + e);
  79389. }
  79390. onSuccess(data);
  79391. });
  79392. };
  79393. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  79394. byteOffset += data.byteOffset;
  79395. var targetLength = count * numComponents;
  79396. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  79397. return new typedArray(data.buffer, byteOffset, targetLength);
  79398. }
  79399. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  79400. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  79401. var targetBuffer = new typedArray(targetLength);
  79402. var sourceIndex = 0;
  79403. var targetIndex = 0;
  79404. while (targetIndex < targetLength) {
  79405. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  79406. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  79407. targetIndex++;
  79408. }
  79409. sourceIndex += elementStride;
  79410. }
  79411. return targetBuffer;
  79412. };
  79413. GLTFLoader.prototype._addPendingData = function (data) {
  79414. if (!this._renderReady) {
  79415. this._renderPendingCount++;
  79416. }
  79417. this._addLoaderPendingData(data);
  79418. };
  79419. GLTFLoader.prototype._removePendingData = function (data) {
  79420. if (!this._renderReady) {
  79421. if (--this._renderPendingCount === 0) {
  79422. this._renderReady = true;
  79423. this._onRenderReady();
  79424. }
  79425. }
  79426. this._removeLoaderPendingData(data);
  79427. };
  79428. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  79429. this._loaderPendingCount++;
  79430. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  79431. var tracker = _a[_i];
  79432. tracker._addPendingData(data);
  79433. }
  79434. };
  79435. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  79436. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  79437. var tracker = _a[_i];
  79438. tracker._removePendingData(data);
  79439. }
  79440. if (--this._loaderPendingCount === 0) {
  79441. this._onComplete();
  79442. }
  79443. };
  79444. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  79445. var _this = this;
  79446. var tracker = new GLTFLoaderTracker(function () {
  79447. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  79448. onComplete();
  79449. });
  79450. this._loaderTrackers.push(tracker);
  79451. this._addLoaderPendingData(tracker);
  79452. action();
  79453. this._removeLoaderPendingData(tracker);
  79454. };
  79455. GLTFLoader.prototype._getDefaultMaterial = function () {
  79456. if (!this._defaultMaterial) {
  79457. var id = "__gltf_default";
  79458. var material = this._babylonScene.getMaterialByName(id);
  79459. if (!material) {
  79460. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  79461. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79462. material.metallic = 1;
  79463. material.roughness = 1;
  79464. }
  79465. this._defaultMaterial = material;
  79466. }
  79467. return this._defaultMaterial;
  79468. };
  79469. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  79470. var babylonMaterial = material.babylonMaterial;
  79471. // Ensure metallic workflow
  79472. babylonMaterial.metallic = 1;
  79473. babylonMaterial.roughness = 1;
  79474. var properties = material.pbrMetallicRoughness;
  79475. if (!properties) {
  79476. return;
  79477. }
  79478. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  79479. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  79480. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  79481. if (properties.baseColorTexture) {
  79482. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  79483. if (!texture) {
  79484. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  79485. }
  79486. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  79487. }
  79488. if (properties.metallicRoughnessTexture) {
  79489. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  79490. if (!texture) {
  79491. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  79492. }
  79493. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  79494. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  79495. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  79496. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  79497. }
  79498. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  79499. };
  79500. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  79501. if (material.babylonMaterial) {
  79502. assign(material.babylonMaterial, false);
  79503. return;
  79504. }
  79505. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  79506. return;
  79507. }
  79508. this._createPbrMaterial(material);
  79509. this._loadMaterialBaseProperties(context, material);
  79510. this._loadMaterialMetallicRoughnessProperties(context, material);
  79511. assign(material.babylonMaterial, true);
  79512. };
  79513. GLTFLoader.prototype._createPbrMaterial = function (material) {
  79514. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  79515. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79516. material.babylonMaterial = babylonMaterial;
  79517. };
  79518. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  79519. var babylonMaterial = material.babylonMaterial;
  79520. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  79521. if (material.doubleSided) {
  79522. babylonMaterial.backFaceCulling = false;
  79523. babylonMaterial.twoSidedLighting = true;
  79524. }
  79525. if (material.normalTexture) {
  79526. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  79527. if (!texture) {
  79528. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  79529. }
  79530. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  79531. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  79532. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  79533. if (material.normalTexture.scale != null) {
  79534. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  79535. }
  79536. }
  79537. if (material.occlusionTexture) {
  79538. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  79539. if (!texture) {
  79540. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  79541. }
  79542. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  79543. babylonMaterial.useAmbientInGrayScale = true;
  79544. if (material.occlusionTexture.strength != null) {
  79545. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  79546. }
  79547. }
  79548. if (material.emissiveTexture) {
  79549. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  79550. if (!texture) {
  79551. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  79552. }
  79553. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  79554. }
  79555. };
  79556. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  79557. var babylonMaterial = material.babylonMaterial;
  79558. var alphaMode = material.alphaMode || "OPAQUE";
  79559. switch (alphaMode) {
  79560. case "OPAQUE": {
  79561. // default is opaque
  79562. break;
  79563. }
  79564. case "MASK": {
  79565. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  79566. if (colorFactor) {
  79567. if (colorFactor[3] == 0) {
  79568. babylonMaterial.alphaCutOff = 1;
  79569. }
  79570. else {
  79571. babylonMaterial.alphaCutOff /= colorFactor[3];
  79572. }
  79573. }
  79574. if (babylonMaterial.albedoTexture) {
  79575. babylonMaterial.albedoTexture.hasAlpha = true;
  79576. }
  79577. break;
  79578. }
  79579. case "BLEND": {
  79580. if (colorFactor) {
  79581. babylonMaterial.alpha = colorFactor[3];
  79582. }
  79583. if (babylonMaterial.albedoTexture) {
  79584. babylonMaterial.albedoTexture.hasAlpha = true;
  79585. babylonMaterial.useAlphaFromAlbedoTexture = true;
  79586. }
  79587. break;
  79588. }
  79589. default: {
  79590. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  79591. }
  79592. }
  79593. };
  79594. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  79595. var _this = this;
  79596. var sampler = (texture.sampler == null ? {} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  79597. if (!sampler) {
  79598. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  79599. }
  79600. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  79601. var samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  79602. this._addPendingData(texture);
  79603. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  79604. _this._tryCatchOnError(function () {
  79605. _this._removePendingData(texture);
  79606. });
  79607. }, function (message) {
  79608. _this._tryCatchOnError(function () {
  79609. throw new Error(context + ": " + message);
  79610. });
  79611. });
  79612. if (texture.url) {
  79613. babylonTexture.updateURL(texture.url);
  79614. }
  79615. else if (texture.dataReadyObservable) {
  79616. texture.dataReadyObservable.add(function (texture) {
  79617. babylonTexture.updateURL(texture.url);
  79618. });
  79619. }
  79620. else {
  79621. texture.dataReadyObservable = new BABYLON.Observable();
  79622. texture.dataReadyObservable.add(function (texture) {
  79623. babylonTexture.updateURL(texture.url);
  79624. });
  79625. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  79626. if (!image_1) {
  79627. throw new Error(context + ": Failed to find source " + texture.source);
  79628. }
  79629. this._loadImage("#/images/" + image_1.index, image_1, function (data) {
  79630. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  79631. texture.dataReadyObservable.notifyObservers(texture);
  79632. texture.dataReadyObservable = undefined;
  79633. });
  79634. }
  79635. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  79636. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  79637. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  79638. babylonTexture.name = texture.name || "texture" + texture.index;
  79639. if (this._parent.onTextureLoaded) {
  79640. this._parent.onTextureLoaded(babylonTexture);
  79641. }
  79642. return babylonTexture;
  79643. };
  79644. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  79645. if (image.uri) {
  79646. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  79647. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  79648. }
  79649. else {
  79650. this._loadUri(context, image.uri, onSuccess);
  79651. }
  79652. }
  79653. else {
  79654. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  79655. if (!bufferView) {
  79656. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  79657. }
  79658. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  79659. }
  79660. };
  79661. GLTFLoader.prototype._loadUri = function (context, uri, onSuccess) {
  79662. var _this = this;
  79663. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  79664. throw new Error(context + ": Uri '" + uri + "' is invalid");
  79665. }
  79666. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  79667. _this._tryCatchOnError(function () {
  79668. onSuccess(new Uint8Array(data));
  79669. });
  79670. }, function (event) {
  79671. _this._tryCatchOnError(function () {
  79672. _this._onProgress(event);
  79673. });
  79674. }, this._babylonScene.database, true, function (request) {
  79675. _this._tryCatchOnError(function () {
  79676. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  79677. });
  79678. });
  79679. if (request) {
  79680. this._requests.push(request);
  79681. }
  79682. };
  79683. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  79684. if (this._disposed) {
  79685. return;
  79686. }
  79687. try {
  79688. handler();
  79689. }
  79690. catch (e) {
  79691. BABYLON.Tools.Error("glTF Loader: " + e.message);
  79692. if (this._errorCallback) {
  79693. this._errorCallback(e.message);
  79694. }
  79695. this.dispose();
  79696. }
  79697. };
  79698. GLTFLoader._AssignIndices = function (array) {
  79699. if (array) {
  79700. for (var index = 0; index < array.length; index++) {
  79701. array[index].index = index;
  79702. }
  79703. }
  79704. };
  79705. GLTFLoader._GetProperty = function (array, index) {
  79706. if (!array || index == undefined || !array[index]) {
  79707. return null;
  79708. }
  79709. return array[index];
  79710. };
  79711. GLTFLoader._GetTextureWrapMode = function (mode) {
  79712. // Set defaults if undefined
  79713. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  79714. switch (mode) {
  79715. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  79716. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  79717. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  79718. default:
  79719. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  79720. return BABYLON.Texture.WRAP_ADDRESSMODE;
  79721. }
  79722. };
  79723. GLTFLoader._GetTextureSamplingMode = function (magFilter, minFilter) {
  79724. // Set defaults if undefined
  79725. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  79726. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  79727. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  79728. switch (minFilter) {
  79729. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  79730. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  79731. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  79732. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  79733. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  79734. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79735. default:
  79736. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79737. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79738. }
  79739. }
  79740. else {
  79741. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  79742. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  79743. }
  79744. switch (minFilter) {
  79745. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  79746. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  79747. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79748. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  79749. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  79750. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  79751. default:
  79752. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79753. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79754. }
  79755. }
  79756. };
  79757. GLTFLoader._GetNumComponents = function (type) {
  79758. switch (type) {
  79759. case "SCALAR": return 1;
  79760. case "VEC2": return 2;
  79761. case "VEC3": return 3;
  79762. case "VEC4": return 4;
  79763. case "MAT2": return 4;
  79764. case "MAT3": return 9;
  79765. case "MAT4": return 16;
  79766. }
  79767. return 0;
  79768. };
  79769. GLTFLoader.Extensions = {};
  79770. return GLTFLoader;
  79771. }());
  79772. GLTF2.GLTFLoader = GLTFLoader;
  79773. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  79774. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79775. })(BABYLON || (BABYLON = {}));
  79776. //# sourceMappingURL=babylon.glTFLoader.js.map
  79777. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79778. var BABYLON;
  79779. (function (BABYLON) {
  79780. var GLTF2;
  79781. (function (GLTF2) {
  79782. /**
  79783. * Utils functions for GLTF
  79784. */
  79785. var GLTFUtils = /** @class */ (function () {
  79786. function GLTFUtils() {
  79787. }
  79788. /**
  79789. * If the uri is a base64 string
  79790. * @param uri: the uri to test
  79791. */
  79792. GLTFUtils.IsBase64 = function (uri) {
  79793. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  79794. };
  79795. /**
  79796. * Decode the base64 uri
  79797. * @param uri: the uri to decode
  79798. */
  79799. GLTFUtils.DecodeBase64 = function (uri) {
  79800. var decodedString = atob(uri.split(",")[1]);
  79801. var bufferLength = decodedString.length;
  79802. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  79803. for (var i = 0; i < bufferLength; i++) {
  79804. bufferView[i] = decodedString.charCodeAt(i);
  79805. }
  79806. return bufferView.buffer;
  79807. };
  79808. GLTFUtils.ValidateUri = function (uri) {
  79809. return (uri.indexOf("..") === -1);
  79810. };
  79811. return GLTFUtils;
  79812. }());
  79813. GLTF2.GLTFUtils = GLTFUtils;
  79814. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79815. })(BABYLON || (BABYLON = {}));
  79816. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  79817. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79818. var BABYLON;
  79819. (function (BABYLON) {
  79820. var GLTF2;
  79821. (function (GLTF2) {
  79822. var GLTFLoaderExtension = /** @class */ (function () {
  79823. function GLTFLoaderExtension() {
  79824. this.enabled = true;
  79825. }
  79826. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  79827. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  79828. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  79829. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  79830. var _this = this;
  79831. if (!property.extensions) {
  79832. return false;
  79833. }
  79834. var extension = property.extensions[this.name];
  79835. if (!extension) {
  79836. return false;
  79837. }
  79838. // Clear out the extension before executing the action to avoid recursing into the same property.
  79839. property.extensions[this.name] = undefined;
  79840. action(context + "extensions/" + this.name, extension, function () {
  79841. // Restore the extension after completing the action.
  79842. property.extensions[_this.name] = extension;
  79843. });
  79844. return true;
  79845. };
  79846. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  79847. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  79848. };
  79849. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  79850. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  79851. };
  79852. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  79853. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  79854. };
  79855. GLTFLoaderExtension._ApplyExtensions = function (action) {
  79856. var extensions = GLTFLoaderExtension._Extensions;
  79857. if (!extensions) {
  79858. return false;
  79859. }
  79860. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  79861. var extension = extensions_1[_i];
  79862. if (extension.enabled && action(extension)) {
  79863. return true;
  79864. }
  79865. }
  79866. return false;
  79867. };
  79868. //
  79869. // Utilities
  79870. //
  79871. GLTFLoaderExtension._Extensions = [];
  79872. return GLTFLoaderExtension;
  79873. }());
  79874. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  79875. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79876. })(BABYLON || (BABYLON = {}));
  79877. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  79878. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  79879. var BABYLON;
  79880. (function (BABYLON) {
  79881. var GLTF2;
  79882. (function (GLTF2) {
  79883. var Extensions;
  79884. (function (Extensions) {
  79885. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  79886. var MSFTLOD = /** @class */ (function (_super) {
  79887. __extends(MSFTLOD, _super);
  79888. function MSFTLOD() {
  79889. return _super !== null && _super.apply(this, arguments) || this;
  79890. }
  79891. Object.defineProperty(MSFTLOD.prototype, "name", {
  79892. get: function () {
  79893. return "MSFT_lod";
  79894. },
  79895. enumerable: true,
  79896. configurable: true
  79897. });
  79898. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  79899. return this._loadExtension(context, node, function (context, extension, onComplete) {
  79900. for (var i = extension.ids.length - 1; i >= 0; i--) {
  79901. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  79902. if (!lodNode) {
  79903. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  79904. }
  79905. loader._traverseNode(context, lodNode, action, parentNode);
  79906. }
  79907. loader._traverseNode(context, node, action, parentNode);
  79908. onComplete();
  79909. });
  79910. };
  79911. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  79912. var _this = this;
  79913. return this._loadExtension(context, node, function (context, extension, onComplete) {
  79914. var nodes = [node];
  79915. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  79916. var index = _a[_i];
  79917. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  79918. if (!lodNode) {
  79919. throw new Error(context + ": Failed to find node " + index);
  79920. }
  79921. nodes.push(lodNode);
  79922. }
  79923. loader._addLoaderPendingData(node);
  79924. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  79925. loader._removeLoaderPendingData(node);
  79926. onComplete();
  79927. });
  79928. });
  79929. };
  79930. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  79931. var _this = this;
  79932. loader._whenAction(function () {
  79933. loader._loadNode(context, nodes[index]);
  79934. }, function () {
  79935. if (index !== nodes.length - 1) {
  79936. var previousNode = nodes[index + 1];
  79937. previousNode.babylonMesh.setEnabled(false);
  79938. }
  79939. if (index === 0) {
  79940. onComplete();
  79941. return;
  79942. }
  79943. setTimeout(function () {
  79944. loader._tryCatchOnError(function () {
  79945. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  79946. });
  79947. }, MSFTLOD.MinimalLODDelay);
  79948. });
  79949. };
  79950. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  79951. var _this = this;
  79952. return this._loadExtension(context, material, function (context, extension, onComplete) {
  79953. var materials = [material];
  79954. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  79955. var index = _a[_i];
  79956. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  79957. if (!lodMaterial) {
  79958. throw new Error(context + ": Failed to find material " + index);
  79959. }
  79960. materials.push(lodMaterial);
  79961. }
  79962. loader._addLoaderPendingData(material);
  79963. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  79964. loader._removeLoaderPendingData(material);
  79965. onComplete();
  79966. });
  79967. });
  79968. };
  79969. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  79970. var _this = this;
  79971. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  79972. assign(babylonMaterial, isNew);
  79973. if (index === 0) {
  79974. onComplete();
  79975. return;
  79976. }
  79977. // Load the next LOD when the loader is ready to render and
  79978. // all active material textures of the current LOD are loaded.
  79979. loader._executeWhenRenderReady(function () {
  79980. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  79981. setTimeout(function () {
  79982. loader._tryCatchOnError(function () {
  79983. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  79984. });
  79985. }, MSFTLOD.MinimalLODDelay);
  79986. });
  79987. });
  79988. });
  79989. };
  79990. /**
  79991. * Specify the minimal delay between LODs in ms (default = 250)
  79992. */
  79993. MSFTLOD.MinimalLODDelay = 250;
  79994. return MSFTLOD;
  79995. }(GLTF2.GLTFLoaderExtension));
  79996. Extensions.MSFTLOD = MSFTLOD;
  79997. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  79998. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  79999. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80000. })(BABYLON || (BABYLON = {}));
  80001. //# sourceMappingURL=MSFT_lod.js.map
  80002. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  80003. var BABYLON;
  80004. (function (BABYLON) {
  80005. var GLTF2;
  80006. (function (GLTF2) {
  80007. var Extensions;
  80008. (function (Extensions) {
  80009. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  80010. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  80011. function KHRMaterialsPbrSpecularGlossiness() {
  80012. return _super !== null && _super.apply(this, arguments) || this;
  80013. }
  80014. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  80015. get: function () {
  80016. return "KHR_materials_pbrSpecularGlossiness";
  80017. },
  80018. enumerable: true,
  80019. configurable: true
  80020. });
  80021. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  80022. var _this = this;
  80023. return this._loadExtension(context, material, function (context, extension, onComplete) {
  80024. loader._createPbrMaterial(material);
  80025. loader._loadMaterialBaseProperties(context, material);
  80026. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  80027. assign(material.babylonMaterial, true);
  80028. });
  80029. };
  80030. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  80031. var babylonMaterial = material.babylonMaterial;
  80032. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  80033. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  80034. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  80035. if (properties.diffuseTexture) {
  80036. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  80037. if (!texture) {
  80038. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  80039. }
  80040. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  80041. }
  80042. if (properties.specularGlossinessTexture) {
  80043. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  80044. if (!texture) {
  80045. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  80046. }
  80047. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  80048. babylonMaterial.reflectivityTexture.hasAlpha = true;
  80049. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  80050. }
  80051. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  80052. };
  80053. return KHRMaterialsPbrSpecularGlossiness;
  80054. }(GLTF2.GLTFLoaderExtension));
  80055. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  80056. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  80057. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  80058. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80059. })(BABYLON || (BABYLON = {}));
  80060. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  80061. (function universalModuleDefinition(root, factory) {
  80062. if (root && root["BABYLON"]) {
  80063. return;
  80064. }
  80065. if(typeof exports === 'object' && typeof module === 'object')
  80066. module.exports = factory();
  80067. else if(typeof define === 'function' && define.amd)
  80068. define([], factory);
  80069. else if(typeof exports === 'object')
  80070. exports["BABYLON"] = factory();
  80071. else {
  80072. root["BABYLON"] = factory();
  80073. }
  80074. })(this, function() {
  80075. return BABYLON;
  80076. });